Repository: basco-johnkevin/laravelsnippets Branch: master Commit: 0a29988a9d24 Files: 615 Total size: 3.3 MB Directory structure: gitextract_pialv810/ ├── .gitattributes ├── .gitignore ├── app/ │ ├── LaraSnipp/ │ │ ├── Command/ │ │ │ └── CommentsCommand.php │ │ ├── Composer/ │ │ │ └── LayoutMasterComposer.php │ │ ├── LaraSnippServiceProvider.php │ │ ├── Mailer/ │ │ │ ├── Mailer.php │ │ │ └── UserMailer.php │ │ ├── Observer/ │ │ │ ├── ObserverServiceProvider.php │ │ │ ├── Snippet/ │ │ │ │ └── SnippetObserver.php │ │ │ └── User/ │ │ │ └── UserObserver.php │ │ ├── Repo/ │ │ │ ├── EloquentBaseRepository.php │ │ │ ├── RepoServiceProvider.php │ │ │ ├── Snippet/ │ │ │ │ ├── EloquentSnippetRepository.php │ │ │ │ └── SnippetRepositoryInterface.php │ │ │ ├── Tag/ │ │ │ │ ├── EloquentTagRepository.php │ │ │ │ └── TagRepositoryInterface.php │ │ │ └── User/ │ │ │ ├── EloquentUserRepository.php │ │ │ └── UserRepositoryInterface.php │ │ └── Service/ │ │ ├── Form/ │ │ │ ├── FormServiceProvider.php │ │ │ ├── Snippet/ │ │ │ │ ├── SnippetForm.php │ │ │ │ └── SnippetFormLaravelValidator.php │ │ │ └── User/ │ │ │ ├── UserForm.php │ │ │ └── UserFormLaravelValidator.php │ │ └── Validation/ │ │ ├── AbstractLaravelValidator.php │ │ └── ValidableInterface.php │ ├── commands/ │ │ └── .gitkeep │ ├── config/ │ │ ├── app.php │ │ ├── auth.php │ │ ├── cache.php │ │ ├── compile.php │ │ ├── database.php │ │ ├── disqus.php │ │ ├── mail.php │ │ ├── packages/ │ │ │ └── .gitkeep │ │ ├── purifier.php │ │ ├── queue.php │ │ ├── remote.php │ │ ├── session.php │ │ ├── site.php │ │ ├── testing/ │ │ │ ├── app.php │ │ │ ├── cache.php │ │ │ ├── database.php │ │ │ ├── mail.php │ │ │ └── session.php │ │ ├── view.php │ │ └── workbench.php │ ├── controllers/ │ │ ├── .gitkeep │ │ ├── Admin/ │ │ │ └── IndexController.php │ │ ├── AuthController.php │ │ ├── BaseController.php │ │ ├── HomeController.php │ │ ├── Member/ │ │ │ ├── SnippetController.php │ │ │ └── UserController.php │ │ ├── RemindersController.php │ │ ├── SnippetController.php │ │ ├── TagController.php │ │ ├── UserController.php │ │ └── website/ │ │ └── PagesController.php │ ├── database/ │ │ ├── migrations/ │ │ │ ├── .gitkeep │ │ │ ├── 2013_11_08_145020_create_snippets_table.php │ │ │ ├── 2013_12_05_122548_create_users_table.php │ │ │ ├── 2013_12_05_122952_add_author_id_in_snippets_table.php │ │ │ ├── 2013_12_08_055430_add_slug_and_activation_key_and_active_in_users_table.php │ │ │ ├── 2013_12_09_125456_drop_active_in_users_table.php │ │ │ ├── 2013_12_09_130122_add_active_in_users_table.php │ │ │ ├── 2013_12_10_112312_add_approved_in_snippets_table.php │ │ │ ├── 2013_12_10_132447_add_slug_in_snippets_table.php │ │ │ ├── 2013_12_11_012940_create_roles_table.php │ │ │ ├── 2013_12_11_013036_add_role_id_in_users_table.php │ │ │ ├── 2013_12_11_013559_add_description_credits_to_resource_deleted_at_in_snippets_table.php │ │ │ ├── 2013_12_11_014226_create_tags_table.php │ │ │ ├── 2013_12_11_014317_create_snippet_tag_table.php │ │ │ ├── 2013_12_11_103428_add_slug_in_tags_table.php │ │ │ ├── 2013_12_12_093641_add_remaining_columns_in_users_table.php │ │ │ ├── 2013_12_19_134131_create_password_reminders_table.php │ │ │ ├── 2014_01_04_072223_add_disqus_columns_to_snippets_table.php │ │ │ ├── 2014_01_06_212314_create_user_starred_table.php │ │ │ └── 2014_04_17_151653_add_remember_token_to_users_table.php │ │ └── seeds/ │ │ ├── .gitkeep │ │ ├── DatabaseSeeder.php │ │ ├── RoleSeeder.php │ │ └── TagSeeder.php │ ├── filters.php │ ├── lang/ │ │ └── en/ │ │ ├── pagination.php │ │ ├── reminders.php │ │ └── validation.php │ ├── libraries/ │ │ └── SiteHelpers.php │ ├── macros.php │ ├── models/ │ │ ├── BaseModel.php │ │ ├── Role.php │ │ ├── Snippet.php │ │ ├── Starred.php │ │ ├── Tag.php │ │ └── User.php │ ├── routes.php │ ├── start/ │ │ ├── artisan.php │ │ ├── global.php │ │ └── local.php │ ├── storage/ │ │ ├── .gitignore │ │ ├── cache/ │ │ │ └── .gitignore │ │ ├── logs/ │ │ │ └── .gitignore │ │ ├── meta/ │ │ │ └── .gitignore │ │ ├── sessions/ │ │ │ └── .gitignore │ │ └── views/ │ │ └── .gitignore │ ├── tests/ │ │ ├── TestCase.php │ │ ├── functional/ │ │ │ └── Controller/ │ │ │ ├── AuthControllerTest.php │ │ │ ├── HomeControllerTest.php │ │ │ ├── Member/ │ │ │ │ ├── SnippetControllerTest.php │ │ │ │ └── UserControllerTest.php │ │ │ ├── SnippetControllerTest.php │ │ │ ├── TagControllerTest.php │ │ │ └── UserControllerTest.php │ │ ├── integration/ │ │ │ ├── Model/ │ │ │ │ └── UserModelTest.php │ │ │ └── Repo/ │ │ │ ├── EloquentSnippetRepositoryTest.php │ │ │ └── EloquentUserRepositoryTest.php │ │ └── unit/ │ │ └── Model/ │ │ └── UserModelTest.php │ └── views/ │ ├── admin/ │ │ ├── index.blade.php │ │ ├── layouts/ │ │ │ └── master.blade.php │ │ └── partials/ │ │ └── navbar.blade.php │ ├── auth/ │ │ ├── login.blade.php │ │ └── signup.blade.php │ ├── emails/ │ │ └── auth/ │ │ ├── activate.blade.php │ │ └── reminder.blade.php │ ├── layouts/ │ │ └── master.blade.php │ ├── member/ │ │ ├── snippets/ │ │ │ ├── create.blade.php │ │ │ └── edit.blade.php │ │ └── users/ │ │ └── dashboard.blade.php │ ├── partials/ │ │ ├── footer.blade.php │ │ ├── header.blade.php │ │ ├── notifications.blade.php │ │ ├── pagination.blade.php │ │ ├── search-narrow.blade.php │ │ ├── search.blade.php │ │ ├── searchForm.blade.php │ │ ├── sidebars/ │ │ │ ├── default.blade.php │ │ │ ├── snippet.blade.php │ │ │ └── widgets/ │ │ │ ├── author.blade.php │ │ │ ├── categories.blade.php │ │ │ ├── social.blade.php │ │ │ └── top-contributors.blade.php │ │ └── snippets.php │ ├── password/ │ │ ├── remind.blade.php │ │ └── reset.blade.php │ ├── snippets/ │ │ ├── index.blade.php │ │ └── show.blade.php │ ├── tags/ │ │ └── snippets.blade.php │ ├── users/ │ │ ├── index.blade.php │ │ ├── profile.blade.php │ │ ├── settings.blade.php │ │ └── snippets.blade.php │ └── website/ │ └── pages/ │ ├── 404.blade.php │ ├── index.blade.php │ └── roadmap.blade.php ├── artisan ├── bootstrap/ │ ├── autoload.php │ ├── paths.php │ └── start.php ├── composer.json ├── gulpfile.js ├── package.json ├── phpunit.xml ├── public/ │ ├── .htaccess │ ├── administration/ │ │ ├── css/ │ │ │ ├── sb-admin-2.css │ │ │ └── timeline.css │ │ └── js/ │ │ └── sb-admin-2.js │ ├── assets/ │ │ ├── coffee/ │ │ │ ├── common.coffee │ │ │ └── snippet.coffee │ │ ├── css/ │ │ │ └── styles.css │ │ ├── js/ │ │ │ ├── common.js │ │ │ ├── snippet.js │ │ │ └── vendors/ │ │ │ └── json2/ │ │ │ └── json2.js │ │ └── scss/ │ │ ├── core/ │ │ │ ├── _band.scss │ │ │ ├── _global.scss │ │ │ ├── _mixins.scss │ │ │ └── _variables.scss │ │ ├── pages/ │ │ │ ├── _profiles.scss │ │ │ └── _snippet.scss │ │ ├── partials/ │ │ │ ├── _breadcrumbs.scss │ │ │ ├── _footer.scss │ │ │ ├── _nav-bar.scss │ │ │ ├── _pagination.scss │ │ │ ├── _search-band.scss │ │ │ ├── _sidebar.scss │ │ │ └── _snippets.scss │ │ └── styles.scss │ ├── index.php │ ├── packages/ │ │ ├── .gitkeep │ │ ├── chosen_v1.0.0/ │ │ │ ├── chosen.css │ │ │ ├── chosen.jquery.js │ │ │ ├── chosen.proto.js │ │ │ ├── docsupport/ │ │ │ │ ├── prism.css │ │ │ │ ├── prism.js │ │ │ │ └── style.css │ │ │ ├── index.html │ │ │ ├── index.proto.html │ │ │ └── options.html │ │ ├── codemirror-3.19/ │ │ │ ├── .gitattributes │ │ │ ├── .gitignore │ │ │ ├── .travis.yml │ │ │ ├── AUTHORS │ │ │ ├── CONTRIBUTING.md │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── addon/ │ │ │ │ ├── comment/ │ │ │ │ │ ├── comment.js │ │ │ │ │ └── continuecomment.js │ │ │ │ ├── dialog/ │ │ │ │ │ ├── dialog.css │ │ │ │ │ └── dialog.js │ │ │ │ ├── display/ │ │ │ │ │ ├── fullscreen.css │ │ │ │ │ ├── fullscreen.js │ │ │ │ │ └── placeholder.js │ │ │ │ ├── edit/ │ │ │ │ │ ├── closebrackets.js │ │ │ │ │ ├── closetag.js │ │ │ │ │ ├── continuelist.js │ │ │ │ │ ├── matchbrackets.js │ │ │ │ │ ├── matchtags.js │ │ │ │ │ └── trailingspace.js │ │ │ │ ├── fold/ │ │ │ │ │ ├── brace-fold.js │ │ │ │ │ ├── comment-fold.js │ │ │ │ │ ├── foldcode.js │ │ │ │ │ ├── foldgutter.css │ │ │ │ │ ├── foldgutter.js │ │ │ │ │ ├── indent-fold.js │ │ │ │ │ └── xml-fold.js │ │ │ │ ├── hint/ │ │ │ │ │ ├── anyword-hint.js │ │ │ │ │ ├── css-hint.js │ │ │ │ │ ├── html-hint.js │ │ │ │ │ ├── javascript-hint.js │ │ │ │ │ ├── pig-hint.js │ │ │ │ │ ├── python-hint.js │ │ │ │ │ ├── show-hint.css │ │ │ │ │ ├── show-hint.js │ │ │ │ │ ├── sql-hint.js │ │ │ │ │ └── xml-hint.js │ │ │ │ ├── lint/ │ │ │ │ │ ├── coffeescript-lint.js │ │ │ │ │ ├── css-lint.js │ │ │ │ │ ├── javascript-lint.js │ │ │ │ │ ├── json-lint.js │ │ │ │ │ ├── lint.css │ │ │ │ │ └── lint.js │ │ │ │ ├── merge/ │ │ │ │ │ ├── dep/ │ │ │ │ │ │ └── diff_match_patch.js │ │ │ │ │ ├── merge.css │ │ │ │ │ └── merge.js │ │ │ │ ├── mode/ │ │ │ │ │ ├── loadmode.js │ │ │ │ │ ├── multiplex.js │ │ │ │ │ ├── multiplex_test.js │ │ │ │ │ └── overlay.js │ │ │ │ ├── runmode/ │ │ │ │ │ ├── colorize.js │ │ │ │ │ ├── runmode-standalone.js │ │ │ │ │ ├── runmode.js │ │ │ │ │ └── runmode.node.js │ │ │ │ ├── scroll/ │ │ │ │ │ └── scrollpastend.js │ │ │ │ ├── search/ │ │ │ │ │ ├── match-highlighter.js │ │ │ │ │ ├── search.js │ │ │ │ │ └── searchcursor.js │ │ │ │ ├── selection/ │ │ │ │ │ ├── active-line.js │ │ │ │ │ └── mark-selection.js │ │ │ │ ├── tern/ │ │ │ │ │ ├── tern.css │ │ │ │ │ ├── tern.js │ │ │ │ │ └── worker.js │ │ │ │ └── wrap/ │ │ │ │ └── hardwrap.js │ │ │ ├── bin/ │ │ │ │ ├── authors.sh │ │ │ │ ├── compress │ │ │ │ ├── lint │ │ │ │ └── source-highlight │ │ │ ├── bower.json │ │ │ ├── demo/ │ │ │ │ ├── activeline.html │ │ │ │ ├── anywordhint.html │ │ │ │ ├── bidi.html │ │ │ │ ├── btree.html │ │ │ │ ├── buffers.html │ │ │ │ ├── changemode.html │ │ │ │ ├── closebrackets.html │ │ │ │ ├── closetag.html │ │ │ │ ├── complete.html │ │ │ │ ├── emacs.html │ │ │ │ ├── folding.html │ │ │ │ ├── fullscreen.html │ │ │ │ ├── hardwrap.html │ │ │ │ ├── html5complete.html │ │ │ │ ├── indentwrap.html │ │ │ │ ├── lint.html │ │ │ │ ├── loadmode.html │ │ │ │ ├── marker.html │ │ │ │ ├── markselection.html │ │ │ │ ├── matchhighlighter.html │ │ │ │ ├── matchtags.html │ │ │ │ ├── merge.html │ │ │ │ ├── multiplex.html │ │ │ │ ├── mustache.html │ │ │ │ ├── placeholder.html │ │ │ │ ├── preview.html │ │ │ │ ├── resize.html │ │ │ │ ├── runmode.html │ │ │ │ ├── search.html │ │ │ │ ├── spanaffectswrapping_shim.html │ │ │ │ ├── tern.html │ │ │ │ ├── theme.html │ │ │ │ ├── trailingspace.html │ │ │ │ ├── variableheight.html │ │ │ │ ├── vim.html │ │ │ │ ├── visibletabs.html │ │ │ │ ├── widget.html │ │ │ │ └── xmlcomplete.html │ │ │ ├── doc/ │ │ │ │ ├── activebookmark.js │ │ │ │ ├── compress.html │ │ │ │ ├── docs.css │ │ │ │ ├── internals.html │ │ │ │ ├── manual.html │ │ │ │ ├── realworld.html │ │ │ │ ├── releases.html │ │ │ │ ├── reporting.html │ │ │ │ ├── upgrade_v2.2.html │ │ │ │ └── upgrade_v3.html │ │ │ ├── index.html │ │ │ ├── keymap/ │ │ │ │ ├── emacs.js │ │ │ │ ├── extra.js │ │ │ │ └── vim.js │ │ │ ├── lib/ │ │ │ │ ├── codemirror.css │ │ │ │ └── codemirror.js │ │ │ ├── mode/ │ │ │ │ ├── apl/ │ │ │ │ │ ├── apl.js │ │ │ │ │ └── index.html │ │ │ │ ├── asterisk/ │ │ │ │ │ ├── asterisk.js │ │ │ │ │ └── index.html │ │ │ │ ├── clike/ │ │ │ │ │ ├── clike.js │ │ │ │ │ ├── index.html │ │ │ │ │ └── scala.html │ │ │ │ ├── clojure/ │ │ │ │ │ ├── clojure.js │ │ │ │ │ └── index.html │ │ │ │ ├── cobol/ │ │ │ │ │ ├── cobol.js │ │ │ │ │ └── index.html │ │ │ │ ├── coffeescript/ │ │ │ │ │ ├── coffeescript.js │ │ │ │ │ └── index.html │ │ │ │ ├── commonlisp/ │ │ │ │ │ ├── commonlisp.js │ │ │ │ │ └── index.html │ │ │ │ ├── css/ │ │ │ │ │ ├── css.js │ │ │ │ │ ├── index.html │ │ │ │ │ ├── scss.html │ │ │ │ │ ├── scss_test.js │ │ │ │ │ └── test.js │ │ │ │ ├── d/ │ │ │ │ │ ├── d.js │ │ │ │ │ └── index.html │ │ │ │ ├── diff/ │ │ │ │ │ ├── diff.js │ │ │ │ │ └── index.html │ │ │ │ ├── dtd/ │ │ │ │ │ ├── dtd.js │ │ │ │ │ └── index.html │ │ │ │ ├── ecl/ │ │ │ │ │ ├── ecl.js │ │ │ │ │ └── index.html │ │ │ │ ├── eiffel/ │ │ │ │ │ ├── eiffel.js │ │ │ │ │ └── index.html │ │ │ │ ├── erlang/ │ │ │ │ │ ├── erlang.js │ │ │ │ │ └── index.html │ │ │ │ ├── fortran/ │ │ │ │ │ ├── fortran.js │ │ │ │ │ └── index.html │ │ │ │ ├── gas/ │ │ │ │ │ ├── gas.js │ │ │ │ │ └── index.html │ │ │ │ ├── gfm/ │ │ │ │ │ ├── gfm.js │ │ │ │ │ ├── index.html │ │ │ │ │ └── test.js │ │ │ │ ├── gherkin/ │ │ │ │ │ ├── gherkin.js │ │ │ │ │ └── index.html │ │ │ │ ├── go/ │ │ │ │ │ ├── go.js │ │ │ │ │ └── index.html │ │ │ │ ├── groovy/ │ │ │ │ │ ├── groovy.js │ │ │ │ │ └── index.html │ │ │ │ ├── haml/ │ │ │ │ │ ├── haml.js │ │ │ │ │ ├── index.html │ │ │ │ │ └── test.js │ │ │ │ ├── haskell/ │ │ │ │ │ ├── haskell.js │ │ │ │ │ └── index.html │ │ │ │ ├── haxe/ │ │ │ │ │ ├── haxe.js │ │ │ │ │ └── index.html │ │ │ │ ├── htmlembedded/ │ │ │ │ │ ├── htmlembedded.js │ │ │ │ │ └── index.html │ │ │ │ ├── htmlmixed/ │ │ │ │ │ ├── htmlmixed.js │ │ │ │ │ └── index.html │ │ │ │ ├── http/ │ │ │ │ │ ├── http.js │ │ │ │ │ └── index.html │ │ │ │ ├── index.html │ │ │ │ ├── jade/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── jade.js │ │ │ │ ├── javascript/ │ │ │ │ │ ├── index.html │ │ │ │ │ ├── javascript.js │ │ │ │ │ ├── test.js │ │ │ │ │ └── typescript.html │ │ │ │ ├── jinja2/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── jinja2.js │ │ │ │ ├── less/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── less.js │ │ │ │ ├── livescript/ │ │ │ │ │ ├── index.html │ │ │ │ │ ├── livescript.js │ │ │ │ │ └── livescript.ls │ │ │ │ ├── lua/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── lua.js │ │ │ │ ├── markdown/ │ │ │ │ │ ├── index.html │ │ │ │ │ ├── markdown.js │ │ │ │ │ └── test.js │ │ │ │ ├── meta.js │ │ │ │ ├── mirc/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── mirc.js │ │ │ │ ├── nginx/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── nginx.js │ │ │ │ ├── ntriples/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── ntriples.js │ │ │ │ ├── ocaml/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── ocaml.js │ │ │ │ ├── octave/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── octave.js │ │ │ │ ├── pascal/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── pascal.js │ │ │ │ ├── perl/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── perl.js │ │ │ │ ├── php/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── php.js │ │ │ │ ├── pig/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── pig.js │ │ │ │ ├── properties/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── properties.js │ │ │ │ ├── python/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── python.js │ │ │ │ ├── q/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── q.js │ │ │ │ ├── r/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── r.js │ │ │ │ ├── rpm/ │ │ │ │ │ ├── changes/ │ │ │ │ │ │ ├── changes.js │ │ │ │ │ │ └── index.html │ │ │ │ │ └── spec/ │ │ │ │ │ ├── index.html │ │ │ │ │ ├── spec.css │ │ │ │ │ └── spec.js │ │ │ │ ├── rst/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── rst.js │ │ │ │ ├── ruby/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── ruby.js │ │ │ │ ├── rust/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── rust.js │ │ │ │ ├── sass/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── sass.js │ │ │ │ ├── scheme/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── scheme.js │ │ │ │ ├── shell/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── shell.js │ │ │ │ ├── sieve/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── sieve.js │ │ │ │ ├── smalltalk/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── smalltalk.js │ │ │ │ ├── smarty/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── smarty.js │ │ │ │ ├── smartymixed/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── smartymixed.js │ │ │ │ ├── sparql/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── sparql.js │ │ │ │ ├── sql/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── sql.js │ │ │ │ ├── stex/ │ │ │ │ │ ├── index.html │ │ │ │ │ ├── stex.js │ │ │ │ │ └── test.js │ │ │ │ ├── tcl/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── tcl.js │ │ │ │ ├── tiddlywiki/ │ │ │ │ │ ├── index.html │ │ │ │ │ ├── tiddlywiki.css │ │ │ │ │ └── tiddlywiki.js │ │ │ │ ├── tiki/ │ │ │ │ │ ├── index.html │ │ │ │ │ ├── tiki.css │ │ │ │ │ └── tiki.js │ │ │ │ ├── toml/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── toml.js │ │ │ │ ├── turtle/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── turtle.js │ │ │ │ ├── vb/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── vb.js │ │ │ │ ├── vbscript/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── vbscript.js │ │ │ │ ├── velocity/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── velocity.js │ │ │ │ ├── verilog/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── verilog.js │ │ │ │ ├── xml/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── xml.js │ │ │ │ ├── xquery/ │ │ │ │ │ ├── index.html │ │ │ │ │ ├── test.js │ │ │ │ │ └── xquery.js │ │ │ │ ├── yaml/ │ │ │ │ │ ├── index.html │ │ │ │ │ └── yaml.js │ │ │ │ └── z80/ │ │ │ │ ├── index.html │ │ │ │ └── z80.js │ │ │ ├── package.json │ │ │ ├── test/ │ │ │ │ ├── comment_test.js │ │ │ │ ├── doc_test.js │ │ │ │ ├── driver.js │ │ │ │ ├── emacs_test.js │ │ │ │ ├── index.html │ │ │ │ ├── lint/ │ │ │ │ │ ├── acorn.js │ │ │ │ │ ├── lint.js │ │ │ │ │ └── walk.js │ │ │ │ ├── mode_test.css │ │ │ │ ├── mode_test.js │ │ │ │ ├── phantom_driver.js │ │ │ │ ├── run.js │ │ │ │ ├── test.js │ │ │ │ └── vim_test.js │ │ │ └── theme/ │ │ │ ├── 3024-day.css │ │ │ ├── 3024-night.css │ │ │ ├── ambiance-mobile.css │ │ │ ├── ambiance.css │ │ │ ├── base16-dark.css │ │ │ ├── base16-light.css │ │ │ ├── blackboard.css │ │ │ ├── cobalt.css │ │ │ ├── eclipse.css │ │ │ ├── elegant.css │ │ │ ├── erlang-dark.css │ │ │ ├── lesser-dark.css │ │ │ ├── mbo.css │ │ │ ├── midnight.css │ │ │ ├── monokai.css │ │ │ ├── neat.css │ │ │ ├── night.css │ │ │ ├── paraiso-dark.css │ │ │ ├── paraiso-light.css │ │ │ ├── rubyblue.css │ │ │ ├── solarized.css │ │ │ ├── the-matrix.css │ │ │ ├── tomorrow-night-eighties.css │ │ │ ├── twilight.css │ │ │ ├── vibrant-ink.css │ │ │ ├── xq-dark.css │ │ │ └── xq-light.css │ │ ├── google-code-prettify/ │ │ │ ├── lang-apollo.js │ │ │ ├── lang-basic.js │ │ │ ├── lang-clj.js │ │ │ ├── lang-css.js │ │ │ ├── lang-dart.js │ │ │ ├── lang-erlang.js │ │ │ ├── lang-go.js │ │ │ ├── lang-hs.js │ │ │ ├── lang-lisp.js │ │ │ ├── lang-llvm.js │ │ │ ├── lang-lua.js │ │ │ ├── lang-matlab.js │ │ │ ├── lang-ml.js │ │ │ ├── lang-mumps.js │ │ │ ├── lang-n.js │ │ │ ├── lang-pascal.js │ │ │ ├── lang-proto.js │ │ │ ├── lang-r.js │ │ │ ├── lang-rd.js │ │ │ ├── lang-scala.js │ │ │ ├── lang-sql.js │ │ │ ├── lang-tcl.js │ │ │ ├── lang-tex.js │ │ │ ├── lang-vb.js │ │ │ ├── lang-vhdl.js │ │ │ ├── lang-wiki.js │ │ │ ├── lang-xq.js │ │ │ ├── lang-yaml.js │ │ │ ├── prettify.css │ │ │ ├── prettify.js │ │ │ └── run_prettify.js │ │ └── jquery-file-upload-8.9.0/ │ │ ├── .gitignore │ │ ├── CONTRIBUTING.md │ │ ├── README.md │ │ ├── angularjs.html │ │ ├── basic-plus.html │ │ ├── basic.html │ │ ├── blueimp-file-upload.jquery.json │ │ ├── bower.json │ │ ├── cors/ │ │ │ ├── postmessage.html │ │ │ └── result.html │ │ ├── css/ │ │ │ ├── demo-ie8.css │ │ │ ├── demo.css │ │ │ ├── jquery.fileupload-noscript.css │ │ │ ├── jquery.fileupload-ui-noscript.css │ │ │ ├── jquery.fileupload-ui.css │ │ │ ├── jquery.fileupload.css │ │ │ └── style.css │ │ ├── index.html │ │ ├── jquery-ui.html │ │ ├── js/ │ │ │ ├── app.js │ │ │ ├── cors/ │ │ │ │ ├── jquery.postmessage-transport.js │ │ │ │ └── jquery.xdr-transport.js │ │ │ ├── jquery.fileupload-angular.js │ │ │ ├── jquery.fileupload-audio.js │ │ │ ├── jquery.fileupload-image.js │ │ │ ├── jquery.fileupload-jquery-ui.js │ │ │ ├── jquery.fileupload-process.js │ │ │ ├── jquery.fileupload-ui.js │ │ │ ├── jquery.fileupload-validate.js │ │ │ ├── jquery.fileupload-video.js │ │ │ ├── jquery.fileupload.js │ │ │ ├── jquery.iframe-transport.js │ │ │ ├── main.js │ │ │ └── vendor/ │ │ │ └── jquery.ui.widget.js │ │ ├── package.json │ │ ├── server/ │ │ │ ├── gae-go/ │ │ │ │ ├── app/ │ │ │ │ │ └── main.go │ │ │ │ ├── app.yaml │ │ │ │ └── static/ │ │ │ │ └── robots.txt │ │ │ ├── gae-python/ │ │ │ │ ├── app.yaml │ │ │ │ ├── main.py │ │ │ │ └── static/ │ │ │ │ └── robots.txt │ │ │ ├── node/ │ │ │ │ ├── .gitignore │ │ │ │ ├── package.json │ │ │ │ ├── public/ │ │ │ │ │ └── files/ │ │ │ │ │ └── .gitignore │ │ │ │ ├── server.js │ │ │ │ └── tmp/ │ │ │ │ └── .gitignore │ │ │ └── php/ │ │ │ ├── UploadHandler.php │ │ │ ├── files/ │ │ │ │ ├── .gitignore │ │ │ │ └── .htaccess │ │ │ └── index.php │ │ └── test/ │ │ ├── index.html │ │ └── test.js │ ├── robots.txt │ └── sitemap.xml ├── readme.md ├── server.php ├── vagrant.pp └── vagrantfile ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ * text=auto ================================================ FILE: .gitignore ================================================ /bootstrap/compiled.php /vendor composer.phar .DS_Store Thumbs.db # OSX .DS_Store # Project specific .sass-cache /public/uploads # local settings /app/config/local # production settings /app/config/production # test site basic auth public/.htpasswd # vagrant .vagrant /node_modules/ /.idea/ composer.lock ================================================ FILE: app/LaraSnipp/Command/CommentsCommand.php ================================================ info("Getting comment counts..."); $key = Config::get("disqus.key"); $forum = Config::get("disqus.shortname"); $endpoint = Config::get("disqus.endpoint"); $snippets = Snippet::orderBy("updated_comments_at", "asc")->take(50)->get(); foreach ($snippets as $snippet) { $link = sprintf($endpoint, $key, $forum, "snippet-" . $snippet->slug); $session = curl_init($link); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($session); curl_close($session); $data = json_decode($response); if ($data->code == 0) { $snippet->comments = $data->response->posts; $snippet->updated_comments_at = date("Y-m-d H:i:s"); $snippet->save(); $this->info($link); } } } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return []; } /** * Get the console command options. * * @return array */ protected function getOptions() { return []; } } ================================================ FILE: app/LaraSnipp/Composer/LayoutMasterComposer.php ================================================ commands( "larasnipp.command.comments" ); } /** * Bootstrap the application * * @return void */ public function boot() { $app = $this->app; // $app->singleton('redis', function() // { // return Redis::connection(); // }); $this->_bootComposers(); } private function _bootComposers() { } public function provides() { return [ "larasnipp.command.comments" ]; } } ================================================ FILE: app/LaraSnipp/Mailer/Mailer.php ================================================ from(\Config::get('site.mail_from'), \Config::get('site.name')); $message->to($user->email, $user->full_name)->subject($subject); }); } } ================================================ FILE: app/LaraSnipp/Mailer/UserMailer.php ================================================ $user, 'activationUrl' => route('auth.getActivateAccount', array($user->slug, $user->activation_key)) ); $subject = 'Please activate your account'; $view = 'emails.auth.activate'; return $this->sendTo($user, $subject, $view, $data); } } ================================================ FILE: app/LaraSnipp/Observer/ObserverServiceProvider.php ================================================ author_id = Auth::user()->id; } } ================================================ FILE: app/LaraSnipp/Observer/User/UserObserver.php ================================================ userMailer = $userMailer; } /** * Assign a role to the user that's being created (member by default) * * @param $user */ public function creating($user) { // generate activation key for the user being created $user->activation_key = md5(uniqid(rand(), true)); // @TODO: use a Role repository $role = \Role::where('name', 'member')->first(); $user->role()->associate($role); } /** * When the user was created, send the activation email * * @param $user */ public function created($user) { $this->userMailer->sendActivationEmail($user); } } ================================================ FILE: app/LaraSnipp/Repo/EloquentBaseRepository.php ================================================ model = $model; } /** * Returns all records * * @return mixed */ public function all() { return $this->model->all(); } /** * Create a new model * * @param array Data to create a new object * @return boolean */ public function create(array $data) { $model = $this->model->create($data); if (!$model) { return false; } return true; } /** * Get single model by slug * * @param string slug * @return object object of model */ public function bySlug($slug) { return $this->model->whereSlug($slug)->first(); } /** * Updates the model with the provided input * * @param $model * @param array $input * @return mixed */ public function update($model, array $input) { $model->fill($input); return $model->save(); } } ================================================ FILE: app/LaraSnipp/Repo/RepoServiceProvider.php ================================================ app; $app->bind('LaraSnipp\Repo\Snippet\SnippetRepositoryInterface', function ($app) { return new EloquentSnippetRepository( new Snippet, $app->make('LaraSnipp\Repo\Tag\TagRepositoryInterface'), $app->make('LaraSnipp\Repo\User\UserRepositoryInterface') ); }); $app->bind('LaraSnipp\Repo\User\UserRepositoryInterface', function ($app) { return new EloquentUserRepository(new User); }); $app->bind('LaraSnipp\Repo\Tag\TagRepositoryInterface', function ($app) { return new EloquentTagRepository(new Tag); }); } } ================================================ FILE: app/LaraSnipp/Repo/Snippet/EloquentSnippetRepository.php ================================================ snippet = $snippet; $this->tag = $tag; $this->user = $user; } /** * Get paginated snippets * * @param int $perPage * @param boolean $all Show published or all * @param $q * @return StdClass Object with $items and $totalItems for pagination */ public function byPage($perPage = 30, $all = false, $q = null) { $query = $q ? $this->snippet->like('title', $q)->orderBy('created_at', 'desc')->with('Starred') : $this->snippet->orderBy('created_at', 'desc')->with('Starred'); if (!$all) { $query->where('approved', 1); } return $query->paginate($perPage); } /** * Get total snippets count * * @todo I hate that this is public for the decorators. * Perhaps interface it? * @param bool $all * @return int Total snippets */ protected function totalSnippets($all = false) { if (!$all) { return $this->snippet->where('approved', 1)->count(); } return $this->snippet->count(); } /** * Get snippets by their tag * * @param $slug * @param int $page * @param int $limit * @internal param \LaraSnipp\Repo\Snippet\URL $string slug of tag * @internal param Number $int of snippets per page * @return StdClass Object with $items and $totalItems for pagination */ public function byTag($slug, $page = 1, $limit = 10) { $tag = $this->tag->bySlug($slug); $result = new \StdClass; $result->page = $page; $result->limit = $limit; $result->totalItems = 0; $result->items = array(); $result->tag = ''; if (!$tag) { return $result; } $snippets = $tag->snippets() ->where('approved', 1) ->orderBy('created_at', 'desc') ->skip($limit * ($page - 1)) ->take($limit) ->get(); $result->totalItems = $this->totalByTag($slug); $result->items = $snippets->all(); // attach tag in the result object so we can use it when needed $result->tag = $tag; return $result; } /** * Get total snippets count per tag * * @todo I hate that this is public for the decorators * Perhaps interface it? * @param $slug * @internal param string $tag Tag slug * @return int Total snippets per tag */ protected function totalByTag($slug) { return $this->tag->bySlug($slug) ->snippets() ->where('approved', 1) ->count(); } /** * Get snippets ordered by their number of views/hits * * @param int|string $limit Number of maximum snippets to return * @return \Illuminate\Database\Eloquent\Collection */ public function getMostViewed($limit = 5) { $redis = App::make('redis'); $mostViewedSnippets = $redis->zRevRange('hits', 0, $limit, array('withscores' => true)); $snippetIds = array(); // if there are no recorded hits in redis // lets return a blank eloquent collection if (empty($mostViewedSnippets)) { return new \Illuminate\Database\Eloquent\Collection; } foreach ($mostViewedSnippets as $snippet) { array_push($snippetIds, $snippet[0]); } $ids = implode(',', $snippetIds); // get all snippets at once and ordered by the current order // of ids inside $snippetIds array // // NOTE: here is the format // // Raw SQL: // SELECT * FROM snippets WHERE id IN (1,2) ORDER BY FIELD(id,2,1); // // Eloquent + raw query // $snippets = static::whereIn('id', $snippetIds) // ->orderByRaw(DB::raw("FIELD(id, 2,1)")) // ->get(); $snippets = $this->snippet->whereIn('id', $snippetIds) ->orderByRaw(DB::raw("FIELD(id, $ids)")) ->take($limit) ->get(); return $snippets; } /** * Get snippets by their author * * @param string $slug Slug of author * @param int $page Page number * @param int $limit Number of snippets per page * @param bool $all * @return StdClass Object with $items and $totalItems for pagination */ public function byAuthor($slug, $page = 1, $limit = 10, $all = false) { $user = $this->user->bySlug($slug); $result = new \StdClass; $result->page = $page; $result->limit = $limit; $result->totalItems = 0; $result->items = array(); if (!$user) { return $result; } $query = $user->snippets() ->orderBy('created_at', 'desc') ->skip($limit * ($page - 1)) ->take($limit); if (!$all) { $query->where('approved', 1); } $snippets = $query->get(); $result->totalItems = $this->totalByAuthor($slug); $result->items = $snippets->all(); // attach user in the result object so we can use it when needed $result->user = $user; return $result; } /** * Get total snippets count per author * * @todo I hate that this is public for the decorators * Perhaps interface it? * @param string $slug Author slug * @return int Total snippets per author */ protected function totalByAuthor($slug) { return $this->user->bySlug($slug) ->snippets() ->where('approved', 1) ->count(); } /** * Create a snippet * * @param array $data Array of inputs * @return boolean */ public function create(array $data) { if ($snippet = $this->snippet->create($data)) { if (isset($data['tags'])) { $snippet->tags()->sync($data['tags']); } else { $snippet->tags()->detach(); } return true; } return false; } /** * Update a snippet * * @param Illuminate\Database\Eloquent\Model $snippet Snippet Model * @param array $input * @internal param array $data Array of inputs * @return boolean */ public function update($snippet, array $input) { $snippet->fill($input); if ($snippet->save()) { if (isset($input['tags'])) { $snippet->tags()->sync($input['tags']); } else { $snippet->tags()->detach(); } return true; } return false; } /** * Get snippets by their slug * * @param string $slug Slug of snippet * @param boolean $all Wether to include not yet approved snippets * @return Illuminate\Database\Eloquent\Model */ public function bySlug($slug, $all = false) { $query = $this->model->whereSlug($slug); if (!$all) { $query->where('approved', 1); } return $query->first(); } } ================================================ FILE: app/LaraSnipp/Repo/Snippet/SnippetRepositoryInterface.php ================================================ tag = $tag; } } ================================================ FILE: app/LaraSnipp/Repo/Tag/TagRepositoryInterface.php ================================================ user = $user; } /** * Get top snippets contributors * * @param int $limit Results per page * @return Illuminate\Database\Eloquent\Collection */ public function getTopSnippetContributors($limit = 5) { return $this->user->from('users AS u') ->join('snippets AS s', 'u.id', '=', 's.author_id', 'LEFT OUTER') ->where('u.active', '=', 1) ->where('s.approved', '=', 1) ->whereRaw('s.deleted_at IS NULL') ->groupBy('s.author_id') ->orderBy('snippets_count', 'DESC') ->take($limit) ->get(array('u.id', 'u.first_name', 'u.last_name', 'u.slug', DB::raw('count(s.author_id) AS snippets_count'))); } /** * Get paginated users * * @param int $page Number of snippet per page * @param int $limit Results per page * @param boolean $all Show only active users or all * @return StdClass Object with $items and $totalItems for pagination */ public function byPage($page = 1, $limit = 10, $all = false) { $result = new \StdClass; $result->page = $page; $result->limit = $limit; $result->totalItems = 0; $result->items = array(); $query = $this->user->orderBy('created_at', 'desc'); if (! $all) { $query->where('active', 1); } $users = $query->skip($limit * ($page-1)) ->take($limit) ->get(); $result->totalItems = $this->totalUsers($all); $result->items = $users->all(); return $result; } /** * Get total users count * * @todo I hate that this is public for the decorators. * Perhaps interface it? * @param bool $all * @return int Total users */ protected function totalUsers($all = false) { if (! $all) { return $this->user->where('active', 1)->count(); } return $this->user->count(); } } ================================================ FILE: app/LaraSnipp/Repo/User/UserRepositoryInterface.php ================================================ app; $app->bind('LaraSnipp\Service\Form\User\UserForm', function ($app) { return new UserForm( new UserFormLaravelValidator($app['validator']), $app->make('LaraSnipp\Repo\User\UserRepositoryInterface') ); }); $app->bind('LaraSnipp\Service\Form\Snippet\SnippetForm', function ($app) { return new SnippetForm( new SnippetFormLaravelValidator($app['validator']), $app->make('LaraSnipp\Repo\Snippet\SnippetRepositoryInterface'), $app->make('LaraSnipp\Repo\Tag\TagRepositoryInterface') ); }); } } ================================================ FILE: app/LaraSnipp/Service/Form/Snippet/SnippetForm.php ================================================ validator = $validator; $this->snippet = $snippet; $this->tag = $tag; } /** * Create a new snippet * * @param array $input * @return boolean */ public function create(array $input) { if (!$this->valid($input, 'creating')) { return false; } // validate if tags chosen are valid // @TODO: move this into a helper so we can re-use this one $tagIds = $this->tag->all()->lists('id'); if (isset($input['tags']) && count($input['tags']) > 0) { foreach ($input['tags'] as $id) { if (!in_array($id, $tagIds)) { return App::abort(404); } } } return $this->snippet->create($input); } /** * Update the snippet * * @param $slug * @param array $input * @return bool|\LaraSnipp\Repo\Snippet\Illuminate\Database\Eloquent\Model */ public function update($slug, array $input) { $snippet = $this->snippet->bySlug($slug, $all = true); if (!$snippet->isTheAuthor(Auth::user())) { return App::abort(404); } if (!$this->valid($input, 'updating')) { return false; } // validate if tags chosen are valid // @TODO: move this into a helper so we can re-use this one $tagIds = $this->tag->all()->lists('id'); if (isset($input['tags']) && count($input['tags']) > 0) { foreach ($input['tags'] as $id) { if (!in_array($id, $tagIds)) { return App::abort(404); } } } if (!$this->snippet->update($snippet, $input)) return false; return $snippet; } /** * Return any validation errors * * @return array */ public function errors() { return $this->validator->errors(); } /** * Test if form validator passes * * @param array $input * @return boolean */ protected function valid(array $input, $mode) { return $this->validator->with($input)->passes($mode); } } ================================================ FILE: app/LaraSnipp/Service/Form/Snippet/SnippetFormLaravelValidator.php ================================================ [ 'title' => 'required', 'body' => 'required', 'resource' => 'url' ], 'updating' => [ 'title' => 'required', 'body' => 'required', 'resource' => 'url' ] ]; } ================================================ FILE: app/LaraSnipp/Service/Form/User/UserForm.php ================================================ validator = $validator; $this->user = $user; } /** * Create a new user * * @param array $input * @return boolean */ public function create(array $input) { if (!$this->valid($input, 'creating')) { return false; } return $this->user->create($input); } /** * Updates an existent user * * @param $user * @param array $input * @return bool */ public function update($user, array $input) { if (!$this->valid($input, 'updating')) { return false; } return $this->user->update($user, $input); } /** * Return any validation errors * * @return array */ public function errors() { return $this->validator->errors(); } /** * Test if form validator passes * * @param array $input * @param $mode : creating || updating * @return bool */ protected function valid(array $input, $mode) { return $this->validator->with($input)->passes($mode); } } ================================================ FILE: app/LaraSnipp/Service/Form/User/UserFormLaravelValidator.php ================================================ [ 'username' => 'required|between:3,16|unique:users', 'password' => 'required|min:4|confirmed', 'password_confirmation' => 'required|min:4', 'email' => 'required|email|unique:users', 'first_name' => 'required', 'last_name' => 'required' ], 'updating' => [ 'password' => 'min:8|confirmed', 'password_confirmation' => 'min:8', 'first_name' => 'required', 'last_name' => 'required', 'twitter_url' => 'url', 'facebook_url' => 'url', 'github_url' => 'url', 'website_url' => 'url' ] ]; } ================================================ FILE: app/LaraSnipp/Service/Validation/AbstractLaravelValidator.php ================================================ value array * * @var Array */ protected $data = array(); /** * Validation errors * * @var Array */ protected $errors = array(); /** * Validation rules * * @var Array */ protected $rules = array(); public function __construct(Factory $validator) { $this->validator = $validator; } /** * Set data to validate * * @param array $data * @return \LaraSnipp\Service\Validation\AbstractLaravelValidator */ public function with(array $data) { $this->data = $data; return $this; } /** * Validation passes or fails * * @param string $mode * @return bool */ public function passes($mode = 'creating') { if ($mode === 'updating') { $validator = $this->validator->make($this->data, $this->rules['updating']); } else { $validator = $this->validator->make($this->data, $this->rules['creating']); } if ($validator->fails()) { $this->errors = $validator->messages(); return false; } return true; } /** * Return errors, if any * * @return array */ public function errors() { return $this->errors; } } ================================================ FILE: app/LaraSnipp/Service/Validation/ValidableInterface.php ================================================ false, /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => 'http://localhost', /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'UTC', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => 'YourSecretKey!!!', /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => array( 'Illuminate\Foundation\Providers\ArtisanServiceProvider', 'Illuminate\Auth\AuthServiceProvider', 'Illuminate\Cache\CacheServiceProvider', 'Illuminate\Foundation\Providers\CommandCreatorServiceProvider', 'Illuminate\Session\CommandsServiceProvider', 'Illuminate\Foundation\Providers\ComposerServiceProvider', 'Illuminate\Routing\ControllerServiceProvider', 'Illuminate\Cookie\CookieServiceProvider', 'Illuminate\Database\DatabaseServiceProvider', 'Illuminate\Encryption\EncryptionServiceProvider', 'Illuminate\Filesystem\FilesystemServiceProvider', 'Illuminate\Hashing\HashServiceProvider', 'Illuminate\Html\HtmlServiceProvider', 'Illuminate\Foundation\Providers\KeyGeneratorServiceProvider', 'Illuminate\Log\LogServiceProvider', 'Illuminate\Mail\MailServiceProvider', 'Illuminate\Foundation\Providers\MaintenanceServiceProvider', 'Illuminate\Database\MigrationServiceProvider', 'Illuminate\Foundation\Providers\OptimizeServiceProvider', 'Illuminate\Pagination\PaginationServiceProvider', 'Illuminate\Foundation\Providers\PublisherServiceProvider', 'Illuminate\Queue\QueueServiceProvider', 'Illuminate\Redis\RedisServiceProvider', 'Illuminate\Auth\Reminders\ReminderServiceProvider', 'Illuminate\Foundation\Providers\RouteListServiceProvider', 'Illuminate\Database\SeedServiceProvider', 'Illuminate\Foundation\Providers\ServerServiceProvider', 'Illuminate\Session\SessionServiceProvider', 'Illuminate\Foundation\Providers\TinkerServiceProvider', 'Illuminate\Translation\TranslationServiceProvider', 'Illuminate\Validation\ValidationServiceProvider', 'Illuminate\View\ViewServiceProvider', 'Illuminate\Workbench\WorkbenchServiceProvider', 'Illuminate\Remote\RemoteServiceProvider', // app specific 'LaraSnipp\Repo\RepoServiceProvider', 'LaraSnipp\Service\Form\FormServiceProvider', 'LaraSnipp\Observer\ObserverServiceProvider', 'LaraSnipp\LaraSnippServiceProvider', // 3rd party 'Cviebrock\EloquentSluggable\SluggableServiceProvider', 'Mews\Purifier\PurifierServiceProvider', 'Bugsnag\BugsnagLaravel\BugsnagLaravelServiceProvider' ), /* |-------------------------------------------------------------------------- | Service Provider Manifest |-------------------------------------------------------------------------- | | The service provider manifest is used by Laravel to lazy load service | providers which are not needed for each request, as well to keep a | list of all of the services. Here, you may set its storage spot. | */ 'manifest' => storage_path().'/meta', /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => array( 'App' => 'Illuminate\Support\Facades\App', 'Artisan' => 'Illuminate\Support\Facades\Artisan', 'Auth' => 'Illuminate\Support\Facades\Auth', 'Blade' => 'Illuminate\Support\Facades\Blade', 'Cache' => 'Illuminate\Support\Facades\Cache', 'ClassLoader' => 'Illuminate\Support\ClassLoader', 'Config' => 'Illuminate\Support\Facades\Config', 'Controller' => 'Illuminate\Routing\Controller', 'Cookie' => 'Illuminate\Support\Facades\Cookie', 'Crypt' => 'Illuminate\Support\Facades\Crypt', 'DB' => 'Illuminate\Support\Facades\DB', 'Eloquent' => 'Illuminate\Database\Eloquent\Model', 'Event' => 'Illuminate\Support\Facades\Event', 'File' => 'Illuminate\Support\Facades\File', 'Form' => 'Illuminate\Support\Facades\Form', 'Hash' => 'Illuminate\Support\Facades\Hash', 'HTML' => 'Illuminate\Support\Facades\HTML', 'Input' => 'Illuminate\Support\Facades\Input', 'Lang' => 'Illuminate\Support\Facades\Lang', 'Log' => 'Illuminate\Support\Facades\Log', 'Mail' => 'Illuminate\Support\Facades\Mail', 'Paginator' => 'Illuminate\Support\Facades\Paginator', 'Password' => 'Illuminate\Support\Facades\Password', 'Queue' => 'Illuminate\Support\Facades\Queue', 'Redirect' => 'Illuminate\Support\Facades\Redirect', 'Redis' => 'Illuminate\Support\Facades\Redis', 'Request' => 'Illuminate\Support\Facades\Request', 'Response' => 'Illuminate\Support\Facades\Response', 'Route' => 'Illuminate\Support\Facades\Route', 'Schema' => 'Illuminate\Support\Facades\Schema', 'Seeder' => 'Illuminate\Database\Seeder', 'Session' => 'Illuminate\Support\Facades\Session', 'Str' => 'Illuminate\Support\Str', 'URL' => 'Illuminate\Support\Facades\URL', 'Validator' => 'Illuminate\Support\Facades\Validator', 'View' => 'Illuminate\Support\Facades\View', 'SSH' => 'Illuminate\Support\Facades\SSH', // 3rd party 'Sluggable' => 'Cviebrock\EloquentSluggable\Facades\Sluggable', 'Purifier' => 'Mews\Purifier\Facades\Purifier', 'Bugsnag' => 'Bugsnag\BugsnagLaravel\BugsnagFacade' ), 'cipher' => MCRYPT_RIJNDAEL_256 ); ================================================ FILE: app/config/auth.php ================================================ 'eloquent', /* |-------------------------------------------------------------------------- | Authentication Model |-------------------------------------------------------------------------- | | When using the "Eloquent" authentication driver, we need to know which | Eloquent model should be used to retrieve your users. Of course, it | is often just the "User" model but you may use whatever you like. | */ 'model' => 'User', /* |-------------------------------------------------------------------------- | Authentication Table |-------------------------------------------------------------------------- | | When using the "Database" authentication driver, we need to know which | table should be used to retrieve your users. We have chosen a basic | default value but you may easily change it to any table you like. | */ 'table' => 'users', /* |-------------------------------------------------------------------------- | Password Reminder Settings |-------------------------------------------------------------------------- | | Here you may set the settings for password reminders, including a view | that should be used as your password reminder e-mail. You will also | be able to set the name of the table that holds the reset tokens. | | The "expire" time is the number of minutes that the reminder should be | considered valid. This security feature keeps tokens short-lived so | they have less time to be guessed. You may change this as needed. | */ 'reminder' => array( 'email' => 'emails.auth.reminder', 'table' => 'password_reminders', 'expire' => 60, ), ); ================================================ FILE: app/config/cache.php ================================================ 'file', /* |-------------------------------------------------------------------------- | File Cache Location |-------------------------------------------------------------------------- | | When using the "file" cache driver, we need a location where the cache | files may be stored. A sensible default has been specified, but you | are free to change it to any other place on disk that you desire. | */ 'path' => storage_path().'/cache', /* |-------------------------------------------------------------------------- | Database Cache Connection |-------------------------------------------------------------------------- | | When using the "database" cache driver you may specify the connection | that should be used to store the cached items. When this option is | null the default database connection will be utilized for cache. | */ 'connection' => null, /* |-------------------------------------------------------------------------- | Database Cache Table |-------------------------------------------------------------------------- | | When using the "database" cache driver we need to know the table that | should be used to store the cached items. A default table name has | been provided but you're free to change it however you deem fit. | */ 'table' => 'cache', /* |-------------------------------------------------------------------------- | Memcached Servers |-------------------------------------------------------------------------- | | Now you may specify an array of your Memcached servers that should be | used when utilizing the Memcached cache driver. All of the servers | should contain a value for "host", "port", and "weight" options. | */ 'memcached' => array( array('host' => '127.0.0.1', 'port' => 11211, 'weight' => 100), ), /* |-------------------------------------------------------------------------- | Cache Key Prefix |-------------------------------------------------------------------------- | | When utilizing a RAM based store such as APC or Memcached, there might | be other applications utilizing the same cache. So, we'll specify a | value to get prefixed to all our keys so we can avoid collisions. | */ 'prefix' => 'laravel', ); ================================================ FILE: app/config/compile.php ================================================ PDO::FETCH_CLASS, /* |-------------------------------------------------------------------------- | Default Database Connection Name |-------------------------------------------------------------------------- | | Here you may specify which of the database connections below you wish | to use as your default connection for all database work. Of course | you may use many connections at once using the Database library. | */ 'default' => 'mysql', /* |-------------------------------------------------------------------------- | Database Connections |-------------------------------------------------------------------------- | | Here are each of the database connections setup for your application. | Of course, examples of configuring each database platform that is | supported by Laravel is shown below to make development simple. | | | All database work in Laravel is done through the PHP PDO facilities | so make sure you have the driver for your particular database of | choice installed on your machine before you begin development. | */ 'connections' => array( 'sqlite' => array( 'driver' => 'sqlite', 'database' => __DIR__.'/../database/production.sqlite', 'prefix' => '', ), 'mysql' => array( 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'database', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ), 'pgsql' => array( 'driver' => 'pgsql', 'host' => 'localhost', 'database' => 'database', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'prefix' => '', 'schema' => 'public', ), 'sqlsrv' => array( 'driver' => 'sqlsrv', 'host' => 'localhost', 'database' => 'database', 'username' => 'root', 'password' => '', 'prefix' => '', ), ), /* |-------------------------------------------------------------------------- | Migration Repository Table |-------------------------------------------------------------------------- | | This table keeps track of all the migrations that have already run for | your application. Using this information, we can determine which of | the migrations on disk have not actually be run in the databases. | */ 'migrations' => 'migrations', /* |-------------------------------------------------------------------------- | Redis Databases |-------------------------------------------------------------------------- | | Redis is an open source, fast, and advanced key-value store that also | provides a richer set of commands than a typical key-value systems | such as APC or Memcached. Laravel makes it easy to dig right in. | */ 'redis' => array( 'cluster' => false, 'default' => array( 'host' => '127.0.0.1', 'port' => 6379, 'database' => 0, ), ), ); ================================================ FILE: app/config/disqus.php ================================================ null, "shortname" => null, "endpoint" => "http://disqus.com/api/3.0/threads/details.json?api_key=%s&forum=%s&thread:ident=%s" ]; ================================================ FILE: app/config/mail.php ================================================ 'smtp', /* |-------------------------------------------------------------------------- | SMTP Host Address |-------------------------------------------------------------------------- | | Here you may provide the host address of the SMTP server used by your | applications. A default option is provided that is compatible with | the Postmark mail service, which will provide reliable delivery. | */ 'host' => 'smtp.mailgun.org', /* |-------------------------------------------------------------------------- | SMTP Host Port |-------------------------------------------------------------------------- | | This is the SMTP port used by your application to delivery e-mails to | users of your application. Like the host we have set this value to | stay compatible with the Postmark e-mail application by default. | */ 'port' => 587, /* |-------------------------------------------------------------------------- | Global "From" Address |-------------------------------------------------------------------------- | | You may wish for all e-mails sent by your application to be sent from | the same address. Here, you may specify a name and address that is | used globally for all e-mails that are sent by your application. | */ 'from' => array('address' => null, 'name' => null), /* |-------------------------------------------------------------------------- | E-Mail Encryption Protocol |-------------------------------------------------------------------------- | | Here you may specify the encryption protocol that should be used when | the application send e-mail messages. A sensible default using the | transport layer security protocol should provide great security. | */ 'encryption' => 'tls', /* |-------------------------------------------------------------------------- | SMTP Server Username |-------------------------------------------------------------------------- | | If your SMTP server requires a username for authentication, you should | set it here. This will get used to authenticate with your server on | connection. You may also set the "password" value below this one. | */ 'username' => null, /* |-------------------------------------------------------------------------- | SMTP Server Password |-------------------------------------------------------------------------- | | Here you may set the password required by your SMTP server to send out | messages from your application. This will be given to the server on | connection so that the application will be able to send messages. | */ 'password' => null, /* |-------------------------------------------------------------------------- | Sendmail System Path |-------------------------------------------------------------------------- | | When using the "sendmail" driver to send e-mails, we will need to know | the path to where Sendmail lives on this server. A default path has | been provided here, which will work well on most of your systems. | */ 'sendmail' => '/usr/sbin/sendmail -bs', /* |-------------------------------------------------------------------------- | Mail "Pretend" |-------------------------------------------------------------------------- | | When this option is enabled, e-mail will not actually be sent over the | web and will instead be written to your application's logs files so | you may inspect the message. This is great for local development. | */ 'pretend' => false, ); ================================================ FILE: app/config/packages/.gitkeep ================================================ ================================================ FILE: app/config/purifier.php ================================================ 'UTF-8', 'finalize' => true, 'preload' => false, 'settings' => array( 'default' => array( 'HTML.Doctype' => 'XHTML 1.0 Strict', 'HTML.Allowed' => 'code,div,b,strong,i,em,a[href|title],ul,ol,li,p[style],br,span[style],img[width|height|alt|src]', 'CSS.AllowedProperties' => 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align', 'AutoFormat.AutoParagraph' => true, 'AutoFormat.RemoveEmpty' => true, ), ), ); ================================================ FILE: app/config/queue.php ================================================ 'sync', /* |-------------------------------------------------------------------------- | Queue Connections |-------------------------------------------------------------------------- | | Here you may configure the connection information for each server that | is used by your application. A default configuration has been added | for each back-end shipped with Laravel. You are free to add more. | */ 'connections' => array( 'sync' => array( 'driver' => 'sync', ), 'beanstalkd' => array( 'driver' => 'beanstalkd', 'host' => 'localhost', 'queue' => 'default', ), 'sqs' => array( 'driver' => 'sqs', 'key' => 'your-public-key', 'secret' => 'your-secret-key', 'queue' => 'your-queue-url', 'region' => 'us-east-1', ), 'iron' => array( 'driver' => 'iron', 'project' => 'your-project-id', 'token' => 'your-token', 'queue' => 'your-queue-name', ), 'redis' => array( 'driver' => 'redis', 'queue' => 'default', ), ), /* |-------------------------------------------------------------------------- | Failed Queue Jobs |-------------------------------------------------------------------------- | | These options configure the behavior of failed queue job logging so you | can control which database and table are used to store the jobs that | have failed. You may change them to any database / table you wish. | */ 'failed' => array( 'database' => 'mysql', 'table' => 'failed_jobs', ), ); ================================================ FILE: app/config/remote.php ================================================ 'production', /* |-------------------------------------------------------------------------- | Remote Server Connections |-------------------------------------------------------------------------- | | These are the servers that will be accessible via the SSH task runner | facilities of Laravel. This feature radically simplifies executing | tasks on your servers, such as deploying out these applications. | */ 'connections' => array( 'production' => array( 'host' => '', 'username' => '', 'password' => '', 'key' => '', 'keyphrase' => '', 'root' => '/var/www', ), ), /* |-------------------------------------------------------------------------- | Remote Server Groups |-------------------------------------------------------------------------- | | Here you may list connections under a single group name, which allows | you to easily access all of the servers at once using a short name | that is extremely easy to remember, such as "web" or "database". | */ 'groups' => array( 'web' => array('production') ), ); ================================================ FILE: app/config/session.php ================================================ 'file', /* |-------------------------------------------------------------------------- | Session Lifetime |-------------------------------------------------------------------------- | | Here you may specify the number of minutes that you wish the session | to be allowed to remain idle before it expires. If you want them | to immediately expire on the browser closing, set that option. | */ 'lifetime' => 120, 'expire_on_close' => false, /* |-------------------------------------------------------------------------- | Session File Location |-------------------------------------------------------------------------- | | When using the native session driver, we need a location where session | files may be stored. A default has been set for you but a different | location may be specified. This is only needed for file sessions. | */ 'files' => storage_path().'/sessions', /* |-------------------------------------------------------------------------- | Session Database Connection |-------------------------------------------------------------------------- | | When using the "database" or "redis" session drivers, you may specify a | connection that should be used to manage these sessions. This should | correspond to a connection in your database configuration options. | */ 'connection' => null, /* |-------------------------------------------------------------------------- | Session Database Table |-------------------------------------------------------------------------- | | When using the "database" session driver, you may specify the table we | should use to manage the sessions. Of course, a sensible default is | provided for you; however, you are free to change this as needed. | */ 'table' => 'sessions', /* |-------------------------------------------------------------------------- | Session Sweeping Lottery |-------------------------------------------------------------------------- | | Some session drivers must manually sweep their storage location to get | rid of old sessions from storage. Here are the chances that it will | happen on a given request. By default, the odds are 2 out of 100. | */ 'lottery' => array(2, 100), /* |-------------------------------------------------------------------------- | Session Cookie Name |-------------------------------------------------------------------------- | | Here you may change the name of the cookie used to identify a session | instance by ID. The name specified here will get used every time a | new session cookie is created by the framework for every driver. | */ 'cookie' => 'laravel_session', /* |-------------------------------------------------------------------------- | Session Cookie Path |-------------------------------------------------------------------------- | | The session cookie path determines the path for which the cookie will | be regarded as available. Typically, this will be the root path of | your application but you are free to change this when necessary. | */ 'path' => '/', /* |-------------------------------------------------------------------------- | Session Cookie Domain |-------------------------------------------------------------------------- | | Here you may change the domain of the cookie used to identify a session | in your application. This will determine which domains the cookie is | available to in your application. A sensible default has been set. | */ 'domain' => null, /* |-------------------------------------------------------------------------- | HTTPS Only Cookies |-------------------------------------------------------------------------- | | By setting this option to true, session cookies will only be sent back | to the server if the browser has a HTTPS connection. This will keep | the cookie from being sent to you if it can not be done securely. | */ 'secure' => false, ); ================================================ FILE: app/config/site.php ================================================ 'http://www.laravelsnippets.com', 'url_short' => 'laravelsnippets.com', /* |-------------------------------------------------------------------------- | Google Analytics Config |-------------------------------------------------------------------------- */ 'ga_code' => 'UA-45609720-1', /* |-------------------------------------------------------------------------- | Facebook Config |-------------------------------------------------------------------------- */ 'facebook_url' => 'https://www.facebook.com/LaravelSnippets', 'facebook_username' => 'laravelsnippets', /* |-------------------------------------------------------------------------- | Twitter Config |-------------------------------------------------------------------------- */ 'twitter_url' => 'https://twitter.com/laravelsnippets', 'twitter_username' => 'laravelsnippets', 'twitter_via' => 'LaravelSnippets #Laravel #snippet', /* |-------------------------------------------------------------------------- | Header Config |-------------------------------------------------------------------------- */ 'title' => 'LaravelSnippets.com', 'meta_description' => 'A repository of useful code snippets for Laravel framework', 'meta_author' => 'John Kevin M. Basco', /* |-------------------------------------------------------------------------- | Footer Config |-------------------------------------------------------------------------- */ 'footer_copyright' => '© laravelsnippets.com by John Kevin M. Basco | Mayon Volcano Software Ltd.', /* |-------------------------------------------------------------------------- | Misc Config |-------------------------------------------------------------------------- */ 'name' => 'Laravel Snippets', 'welcome_message' => '

Welcome to laravelsnippets.com

A repository of useful code snippets for Laravel PHP framework. Submit, grab and share!

Source code of the site - Github link . We accept pull requests! =)

', 'repo_url' => '//github.com/basco-johnkevin/laravelsnippets', 'mail_from' => 'basco.johnkevin@gmail.com', 'snippetsPerPage' => 30 ); ================================================ FILE: app/config/testing/app.php ================================================ true, ); ================================================ FILE: app/config/testing/cache.php ================================================ 'array', ); ================================================ FILE: app/config/testing/database.php ================================================ 'mysql', /* |-------------------------------------------------------------------------- | Database Connections |-------------------------------------------------------------------------- | | Here are each of the database connections setup for your application. | Of course, examples of configuring each database platform that is | supported by Laravel is shown below to make development simple. | | | All database work in Laravel is done through the PHP PDO facilities | so make sure you have the driver for your particular database of | choice installed on your machine before you begin development. | */ 'connections' => array( 'mysql' => array( 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'test.larasnipp', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ), ), /* |-------------------------------------------------------------------------- | Redis Databases |-------------------------------------------------------------------------- | | Redis is an open source, fast, and advanced key-value store that also | provides a richer set of commands than a typical key-value systems | such as APC or Memcached. Laravel makes it easy to dig right in. | */ 'redis' => array( 'cluster' => false, 'default' => array( 'host' => '127.0.0.1', 'port' => 6379, 'database' => 5, ), ), ); ================================================ FILE: app/config/testing/mail.php ================================================ true, ); ================================================ FILE: app/config/testing/session.php ================================================ 'array', ); ================================================ FILE: app/config/view.php ================================================ array(__DIR__.'/../views'), /* |-------------------------------------------------------------------------- | Pagination View |-------------------------------------------------------------------------- | | This view will be used to render the pagination link output, and can | be easily customized here to show any view you like. A clean view | compatible with Twitter's Bootstrap is given to you by default. | */ // 'pagination' => 'pagination::bootstrap-3', 'pagination' => 'partials/pagination', ); ================================================ FILE: app/config/workbench.php ================================================ '', /* |-------------------------------------------------------------------------- | Workbench Author E-Mail Address |-------------------------------------------------------------------------- | | Like the option above, your e-mail address is used when generating new | workbench packages. The e-mail is placed in your composer.json file | automatically after the package is created by the workbench tool. | */ 'email' => '', ); ================================================ FILE: app/controllers/.gitkeep ================================================ ================================================ FILE: app/controllers/Admin/IndexController.php ================================================ user = $user; $this->userForm = $userForm; } /** * Show signup form * GET /signup */ public function getSignup() { return View::make('auth.signup'); } /** * Process signup form * POST /signup */ public function postSignup() { if ($this->userForm->create(Input::all())) { return Redirect::route('auth.getLogin') ->with('message', 'Successfully registered. Please check your email and activate your account.') ->with('messageType', "success"); } return Redirect::route('auth.getSignup') ->withInput() ->withErrors($this->userForm->errors()); } /** * Activate account * GET /auth/activate/{slug}/key/{activation_key} */ public function getActivateAccount($userSlug, $activationKey) { $user = $this->user->bySlug($userSlug); if ($user->isActive()) { return Redirect::route('home') ->with('message', 'This user account is already active.'); } if ($user->activate($activationKey)) { Auth::login($user); return Redirect::route('home') ->with('message', 'Your account is now activated.') ->with('messageType', "success"); } else { return Redirect::route('home') ->with('message', 'Invalid activation key.'); } } /** * Show login form * GET /login */ public function getLogin() { return View::make('auth.login'); } /** * Process login * POST /login */ public function postLogin() { $params = array( 'username' => Input::get('username'), 'password' => Input::get('password'), 'active' => 1 ); if (Auth::attempt($params)) { // if next is present, redirect to that url $next = Input::get('next'); if ($next) return Redirect::to($next); return Redirect::route('home'); } return Redirect::route('auth.getLogin') ->with('message', 'Wrong username or password') ->withInput(); } /** * Process logout * GET /logout */ public function getLogout() { Auth::logout(); return Redirect::route('auth.getLogin'); } } ================================================ FILE: app/controllers/BaseController.php ================================================ layout)) { $this->layout = View::make($this->layout); } } } ================================================ FILE: app/controllers/HomeController.php ================================================ snippet = $snippet; $this->user = $user; $this->tag = $tag; } /** * Show home page * GET / */ public function getIndex() { $perPage = Config::get('site.snippetsPerPage'); $snippets = $this->snippet->byPage($perPage); $topSnippetContributors = $this->user->getTopSnippetContributors(); $mostViewedSnippets = $this->snippet->getMostViewed(10); $tags = $this->tag->all(); return View::make('website.pages.index', compact('snippets', 'topSnippetContributors', 'mostViewedSnippets', 'tags')); } } ================================================ FILE: app/controllers/Member/SnippetController.php ================================================ snippet = $snippet; $this->user = $user; $this->tag = $tag; $this->snippetForm = $snippetForm; } /** * Show a single snippet of a user * GET /members/snippets/{slug} * * @param string $slug Slug of a snippet */ public function getShow($slug) { $snippet = $this->snippet->bySlug($slug, $all = true); if (!$snippet) { return App::abort(404); } $user = Auth::user(); $has_starred = !empty($user) ? $user->hasStarred($snippet->id) : false; $tags = $this->tag->all(); $topSnippetContributors = $this->user->getTopSnippetContributors(); return View::make('snippets.show', compact('snippet', 'has_starred', 'tags', 'topSnippetContributors')); } /** * Show the snippet create form * GET /members/submit/snippet */ public function getCreate() { $tags = $this->tag->all()->lists('name', 'id'); return View::make('member.snippets.create', compact('tags')); } /** * Process snippet submission * POST /members/submit/snippet */ public function postStore() { if ($this->snippetForm->create(Input::all())) { return Redirect::route('member.snippet.getCreate') ->with('message', "Your snippet is now submitted and waiting for admin's approval") ->with('messageType', "success"); } return Redirect::route('member.snippet.getCreate') ->withInput() ->withErrors($this->snippetForm->errors()); } /** * Show the snippet edit form * GET /members/snippets/{slug}/edit */ public function getEdit($slug) { $snippet = $this->snippet->bySlug($slug, $all = true); // validate that the user updating the snippet is the snippet author if (!$snippet->isTheAuthor(Auth::user())) return App::abort(404); $tags = $this->tag->all()->lists('name', 'id'); return View::make('member.snippets.edit', compact('snippet', 'tags')); } /** * Process edit snippet form * POST /members/snippets/{slug}/update */ public function postUpdate($slug) { if ($snippet = $this->snippetForm->update($slug, Input::all())) { return Redirect::route('member.snippet.getShow', $snippet->slug) ->with('message', 'Update successful') ->with('messageType', 'success'); } return Redirect::back() ->withInput() ->withErrors($this->snippetForm->errors()); } } ================================================ FILE: app/controllers/Member/UserController.php ================================================ snippet = $snippet; } /** * Show dashboard with snippets and starred snippets of the current logged-in user * GET /members/dashboard */ public function dashboard() { $page = Input::get('page', 1); // Candidate for config item $perPage = 10; $pagiData = $this->snippet->byAuthor(Auth::user()->slug, $page, $perPage, $all = true); $my_snippets = Paginator::make($pagiData->items, $pagiData->totalItems, $perPage); $user = Auth::user(); $starred_snippets = $user->starred()->with('Snippet')->get(); return View::make('member.users.dashboard', compact('my_snippets', 'starred_snippets')); } } ================================================ FILE: app/controllers/RemindersController.php ================================================ with('message', 'Your email is invalid'); case Password::REMINDER_SENT: return Redirect::route('password.remind')->with('message', 'The password reminder has been sent. Check your email')->with('messageType', "success"); } } /** * Display the password reset view for the given token. * * @param string $token * @return \Illuminate\Http\Response */ public function getReset($token = null) { if (is_null($token)) { App::abort(404); } return View::make('password.reset')->with('token', $token); } /** * Handle a POST request to reset a user's password. * * @return \Illuminate\Http\Response */ public function postReset() { $credentials = Input::only( 'email', 'password', 'password_confirmation', 'token' ); $response = Password::reset($credentials, function ($user, $password) { $user->password = $password; $user->save(); }); switch ($response) { case Password::INVALID_PASSWORD: case Password::INVALID_TOKEN: return Redirect::route('password.remind')->with('message', "Your password remind request has expired or is invalid. Please request another one.") ->with('messageType', "warning"); case Password::INVALID_USER: return Redirect::route('password.reset')->with('message', "Whoops something went terribily wrong! Please retry") ->with('messageType', "danger"); case Password::PASSWORD_RESET: return Redirect::route('auth.getLogin')->with('message', 'Password successfully updated. Now log in')->with('messageType', 'success'); } } } ================================================ FILE: app/controllers/SnippetController.php ================================================ snippet = $snippet; $this->user = $user; $this->tag = $tag; } /** * Show listing of snippets * GET /snippets */ public function getIndex() { $perPage = Config::get('site.snippetsPerPage'); if (Request::has('q') and Request::get('q') !== '') $snippets = $this->snippet->byPage($perPage, false, e(Request::get('q'))); else $snippets = $this->snippet->byPage($perPage); $tags = $this->tag->all(); $topSnippetContributors = $this->user->getTopSnippetContributors(); return View::make('snippets.index', compact('snippets', 'tags', 'topSnippetContributors')); } /** * Show an individual snippet * GET /snippets/{slug} * @param $slug * @return */ public function getShow($slug) { $snippet = $this->snippet->bySlug($slug); if (!$snippet) { return App::abort(404); } $user = Auth::user(); $has_starred = !empty($user) ? $user->hasStarred($snippet->id) : false; # check cookie readlist $cookieName = md5('snippet.readlist'); $cookieJson = Cookie::get($cookieName); $cookieArray = json_decode($cookieJson); if (is_null($cookieArray) or !in_array($snippet->id, $cookieArray)) { # increment hit count if snippet id not exist cookie $snippet->incrementHits(); # put cookie the snippet id $cookieArray[] = $snippet->id; # attached all cookies for one week. Cookie::queue($cookieName, json_encode($cookieArray), 10080); } $tags = $this->tag->all(); $topSnippetContributors = $this->user->getTopSnippetContributors(); return View::make('snippets.show', compact('snippet', 'has_starred', 'tags', 'topSnippetContributors')); } /** * Stars a snippet * GET /snippets/{slug}/star * @param $slug * @return */ public function starSnippet($slug) { $snippet = $this->snippet->bySlug($slug); $user = Auth::user(); if (empty($user)) { return Redirect::route('snippet.getShow', array($slug)) ->with( 'message', sprintf( 'Only logged in users can star snippets. Please %s or %s.', link_to_route('auth.getLogin', 'login'), link_to_route('auth.getSignup', 'signup') ) ); } $user->starSnippet($snippet->id); return Redirect::route('snippet.getShow', array($slug)); } /** * Unstars a snippet * GET /snippets/{slug}/unstar * @param $slug * @return */ public function unstarSnippet($slug) { $snippet = $this->snippet->bySlug($slug); $user = Auth::user(); if (empty($user)) { return Redirect::route('snippet.getShow', array($slug)) ->with( 'message', sprintf( 'Only logged in users can unstar snippets. Please %s or %s.', link_to_route('auth.getLogin', 'login'), link_to_route('auth.getSignup', 'signup') ) ); } $user->unStarSnippet($snippet->id); return Redirect::route('snippet.getShow', array($slug)); } } ================================================ FILE: app/controllers/TagController.php ================================================ tag = $tag; $this->snippet = $snippet; $this->user = $user; } /** * Show listing of snippets filtered by a tag * GET /tags/{slug} */ public function getShow($slug) { $page = Input::get('page', 1); // Candidate for config item $perPage = 30; $pagiData = $this->snippet->byTag($slug, $page, $perPage); if (!$pagiData->tag) { return App::abort(404); } $tag = $pagiData->tag; $snippets = Paginator::make($pagiData->items, $pagiData->totalItems, $perPage); $tags = $this->tag->all(); $topSnippetContributors = $this->user->getTopSnippetContributors(); return View::make('tags.snippets', compact('snippets', 'tag', 'tags', 'topSnippetContributors')); } } ================================================ FILE: app/controllers/UserController.php ================================================ user = $user; $this->snippet = $snippet; $this->userForm = $userForm; } /** * Show listing of users * GET /profiles */ public function getIndex() { $page = Input::get('page', 1); // Candidate for config item $perPage = 12; $pagiData = $this->user->byPage($page, $perPage); $users = Paginator::make($pagiData->items, $pagiData->totalItems, $perPage); return View::make('users.index', compact('users')); } /** * Show profile of a user * GET /profiles/{slug} */ public function getProfile($slug) { $user = $this->user->bySlug($slug); if (!$user) { return App::abort(404); } return View::make('users.profile', compact('user')); } /** * Show listing of snippets of a user * GET /profiles/{slug}/snippets * @param $slug * @return */ public function getSnippets($slug) { $page = Input::get('page', 1); // Candidate for config item $perPage = 10; $pagiData = $this->snippet->byAuthor($slug, $page, $perPage); $user = $pagiData->user; $snippets = Paginator::make($pagiData->items, $pagiData->totalItems, $perPage); return View::make('users.snippets', compact('snippets', 'user')); } /** * Show user's settings page * GET /profiles/{slug}/settings * @param $slug */ public function getSettings($slug) { $user = Auth::user(); return View::make('users.settings', compact('user')); } /** * Updates user settings * @param $slug * @return mixed */ public function putSettings($slug) { $user = Auth::user(); $result = $this->userForm->update($user, Input::all()); if ($result) { return Redirect::route('user.getSettings', $slug) ->with('message', 'Successfully updated your settings.') ->with('messageType', "success"); } else { return Redirect::route('user.getSettings', $slug) ->withInput() ->withErrors($this->userForm->errors()); } } } ================================================ FILE: app/controllers/website/PagesController.php ================================================ increments('id'); $table->string('title'); $table->text('body'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('snippets'); } } ================================================ FILE: app/database/migrations/2013_12_05_122548_create_users_table.php ================================================ increments('id'); $table->string('username'); $table->string('email'); $table->string('password'); $table->string('first_name'); $table->string('last_name'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } } ================================================ FILE: app/database/migrations/2013_12_05_122952_add_author_id_in_snippets_table.php ================================================ unsignedInteger('author_id'); $table->foreign('author_id')->references('id')->on('users'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('snippets', function ($table) { $table->dropForeign('snippets_author_id_foreign'); $table->dropColumn('author_id'); }); } } ================================================ FILE: app/database/migrations/2013_12_08_055430_add_slug_and_activation_key_and_active_in_users_table.php ================================================ string('slug'); $table->string('activation_key'); $table->string('active'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function ($table) { $table->dropColumn('slug'); $table->dropColumn('activation_key'); $table->dropColumn('active'); }); } } ================================================ FILE: app/database/migrations/2013_12_09_125456_drop_active_in_users_table.php ================================================ dropColumn('active'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function ($table) { $table->string('active'); }); } } ================================================ FILE: app/database/migrations/2013_12_09_130122_add_active_in_users_table.php ================================================ string('active')->default(0); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function ($table) { $table->dropColumn('active'); }); } } ================================================ FILE: app/database/migrations/2013_12_10_112312_add_approved_in_snippets_table.php ================================================ boolean('approved')->default(0); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('snippets', function ($table) { $table->dropColumn('approved'); }); } } ================================================ FILE: app/database/migrations/2013_12_10_132447_add_slug_in_snippets_table.php ================================================ string('slug')->default(0); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('snippets', function ($table) { $table->dropColumn('slug'); }); } } ================================================ FILE: app/database/migrations/2013_12_11_012940_create_roles_table.php ================================================ increments('id'); $table->string('name'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('roles'); } } ================================================ FILE: app/database/migrations/2013_12_11_013036_add_role_id_in_users_table.php ================================================ unsignedInteger('role_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function ($table) { $table->dropColumn('role_id'); }); } } ================================================ FILE: app/database/migrations/2013_12_11_013559_add_description_credits_to_resource_deleted_at_in_snippets_table.php ================================================ text('description')->nullable(); $table->string('credits_to')->nullable(); $table->string('resource')->nullable(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('snippets', function ($table) { $table->dropColumn('description'); $table->dropColumn('credits_to'); $table->dropColumn('resource'); $table->dropColumn('deleted_at'); }); } } ================================================ FILE: app/database/migrations/2013_12_11_014226_create_tags_table.php ================================================ increments('id'); $table->string('name'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('tags'); } } ================================================ FILE: app/database/migrations/2013_12_11_014317_create_snippet_tag_table.php ================================================ increments('id'); $table->unsignedInteger('snippet_id'); $table->unsignedInteger('tag_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('snippet_tag'); } } ================================================ FILE: app/database/migrations/2013_12_11_103428_add_slug_in_tags_table.php ================================================ string('slug'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('tags', function ($table) { $table->dropColumn('slug'); }); } } ================================================ FILE: app/database/migrations/2013_12_12_093641_add_remaining_columns_in_users_table.php ================================================ string('twitter_url')->nullable(); $table->string('facebook_url')->nullable(); $table->string('github_url')->nullable(); $table->string('website_url')->nullable(); $table->string('photo_url')->nullable(); $table->text('about_me')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function ($table) { $table->dropColumn('twitter_url'); $table->dropColumn('facebook_url'); $table->dropColumn('github_url'); $table->dropColumn('website_url'); $table->dropColumn('photo_url'); $table->dropColumn('about_me'); }); } } ================================================ FILE: app/database/migrations/2013_12_19_134131_create_password_reminders_table.php ================================================ string('email')->index(); $table->string('token')->index(); $table->timestamp('created_at'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('password_reminders'); } } ================================================ FILE: app/database/migrations/2014_01_04_072223_add_disqus_columns_to_snippets_table.php ================================================ timestamp("updated_comments_at"); $table->integer("comments"); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table("snippets", function ($table) { $table->dropColumn("updated_comments_at"); $table->dropColumn("comments"); }); } } ================================================ FILE: app/database/migrations/2014_01_06_212314_create_user_starred_table.php ================================================ increments('id'); $table->unsignedInteger('user_id'); $table->unsignedInteger('snippet_id'); $table->index('user_id'); $table->index('snippet_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('user_starred'); } } ================================================ FILE: app/database/migrations/2014_04_17_151653_add_remember_token_to_users_table.php ================================================ string('remember_token', 100)->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function(Blueprint $table) { $table->dropColumn('remember_token'); }); } } ================================================ FILE: app/database/seeds/.gitkeep ================================================ ================================================ FILE: app/database/seeds/DatabaseSeeder.php ================================================ call('RoleSeeder'); $this->call('TagSeeder'); } } ================================================ FILE: app/database/seeds/RoleSeeder.php ================================================ generate(); } } private function generate() { $roles = array( 'admin', 'member' ); foreach ($roles as $role) { Role::create(array( 'name' => $role )); } } } ================================================ FILE: app/database/seeds/TagSeeder.php ================================================ generate(); } } private function generate() { $tags = array( 'auth' => 'auth', 'eloquent' => 'eloquent' ); foreach ($tags as $name => $slug) { Tag::create(array( 'name' => $name, 'slug' => $slug )); } } } ================================================ FILE: app/filters.php ================================================ $nextUrl))->with('message', $message); } return Redirect::route('auth.getLogin'); } }); Route::filter('admin', function ($route, $request) { if (!Auth::user()->isAdmin()) { return App::abort(401, 'You are not authorized.'); } }); Route::filter('auth.basic', function () { return Auth::basic(); }); /* |-------------------------------------------------------------------------- | Guest Filter |-------------------------------------------------------------------------- | | The "guest" filter is the counterpart of the authentication filters as | it simply checks that the current user is not logged in. A redirect | response will be issued if they are, which you may freely change. | */ Route::filter('guest', function () { if (Auth::check()) return Redirect::to('/'); }); /* |-------------------------------------------------------------------------- | CSRF Protection Filter |-------------------------------------------------------------------------- | | The CSRF filter is responsible for protecting your application against | cross-site request forgery attacks. If this special token in a user | session does not match the one given in this request, we'll bail. | */ Route::filter('csrf', function () { if (Session::token() != Input::get('_token')) { throw new Illuminate\Session\TokenMismatchException; } }); ================================================ FILE: app/lang/en/pagination.php ================================================ '« Previous', 'next' => 'Next »', ); ================================================ FILE: app/lang/en/reminders.php ================================================ "Passwords must be at least six characters and match the confirmation.", "user" => "We can't find a user with that e-mail address.", "token" => "This password reset token is invalid.", "sent" => "Password reminder sent!", ); ================================================ FILE: app/lang/en/validation.php ================================================ "The :attribute must be accepted.", "active_url" => "The :attribute is not a valid URL.", "after" => "The :attribute must be a date after :date.", "alpha" => "The :attribute may only contain letters.", "alpha_dash" => "The :attribute may only contain letters, numbers, and dashes.", "alpha_num" => "The :attribute may only contain letters and numbers.", "array" => "The :attribute must be an array.", "before" => "The :attribute must be a date before :date.", "between" => array( "numeric" => "The :attribute must be between :min and :max.", "file" => "The :attribute must be between :min and :max kilobytes.", "string" => "The :attribute must be between :min and :max characters.", "array" => "The :attribute must have between :min and :max items.", ), "confirmed" => "The :attribute confirmation does not match.", "date" => "The :attribute is not a valid date.", "date_format" => "The :attribute does not match the format :format.", "different" => "The :attribute and :other must be different.", "digits" => "The :attribute must be :digits digits.", "digits_between" => "The :attribute must be between :min and :max digits.", "email" => "The :attribute format is invalid.", "exists" => "The selected :attribute is invalid.", "image" => "The :attribute must be an image.", "in" => "The selected :attribute is invalid.", "integer" => "The :attribute must be an integer.", "ip" => "The :attribute must be a valid IP address.", "max" => array( "numeric" => "The :attribute may not be greater than :max.", "file" => "The :attribute may not be greater than :max kilobytes.", "string" => "The :attribute may not be greater than :max characters.", "array" => "The :attribute may not have more than :max items.", ), "mimes" => "The :attribute must be a file of type: :values.", "min" => array( "numeric" => "The :attribute must be at least :min.", "file" => "The :attribute must be at least :min kilobytes.", "string" => "The :attribute must be at least :min characters.", "array" => "The :attribute must have at least :min items.", ), "not_in" => "The selected :attribute is invalid.", "numeric" => "The :attribute must be a number.", "regex" => "The :attribute format is invalid.", "required" => "The :attribute field is required.", "required_if" => "The :attribute field is required when :other is :value.", "required_with" => "The :attribute field is required when :values is present.", "required_without" => "The :attribute field is required when :values is not present.", "same" => "The :attribute and :other must match.", "size" => array( "numeric" => "The :attribute must be :size.", "file" => "The :attribute must be :size kilobytes.", "string" => "The :attribute must be :size characters.", "array" => "The :attribute must contain :size items.", ), "unique" => "The :attribute has already been taken.", "url" => "The :attribute format is invalid.", /* |-------------------------------------------------------------------------- | Custom Validation Language Lines |-------------------------------------------------------------------------- | | Here you may specify custom validation messages for attributes using the | convention "attribute.rule" to name the lines. This makes it quick to | specify a specific custom language line for a given attribute rule. | */ 'custom' => array(), /* |-------------------------------------------------------------------------- | Custom Validation Attributes |-------------------------------------------------------------------------- | | The following language lines are used to swap attribute place-holders | with something more reader friendly such as E-Mail Address instead | of "email". This simply helps us make messages a little cleaner. | */ 'attributes' => array(), ); ================================================ FILE: app/libraries/SiteHelpers.php ================================================ type); } return !empty($body_classes) ? implode(' ', $body_classes) : NULL; } /** * Returns breadcrumbs made up by URI segments * * @return string */ public static function breadcrumbs() { $breadcrumbs = []; $crumbs = Request::segments(); if (count($crumbs) < 2) { return; } $url = ""; end($crumbs); $last_key = key($crumbs); foreach ($crumbs as $key => $crumb) { $url .= '/' . $crumb; $crumb = ucwords($crumb); if ($key != $last_key) { $crumb = '' . link_to($url, $crumb, ['rel' => 'v:url', 'property' => 'v:title']) . ''; } else if (Request::segment(1) === 'snippets') { $crumb = ""; } else { $crumb = '' . $crumb . ''; } array_push($breadcrumbs, $crumb); } $return = '
'; $return .= ''; $return .= '
'; return $return; } /** * Returns li wrapped link with active class * * @param string $url * @param string $title * @param bool $has_sub_menu * @param array $attributes * @param bool $secure * @return string */ public static function navLinkTo($url, $title, $has_sub_menu = false, $attributes = [], $secure = null) { $purl = parse_url($url); $uri = ltrim($purl['path'], '/'); $link = ''; } return $link; } /** * Returns URL with prepended protocol * * @param string $url * @param bool $https optional * @return string */ public static function url($url, $https = false) { $http = $https ? 'https://' : 'http://'; return $http . str_replace(['http://', 'https://'], '', $url); } } ================================================ FILE: app/macros.php ================================================ "form-control" . $class, "placeholder" => $placeholder ]; if (!empty($options['parameters'])) { $parameters = array_merge($parameters, $options['parameters']); } $error = ""; if (!empty($options["error"])) { $error = $options["error"]->has($name) ? $options["error"]->first($name) : NULL; } if ($type !== "hidden") { $markup .= "
"; } switch ($type) { case "text": if (empty($options['no_label'])) { $markup .= Form::rawLabel($name, $label, [ "class" => "control-label" ]); } $markup .= Form::text($name, $value, $parameters); break; case "textarea": if (empty($options['no_label'])) { $markup .= Form::rawLabel($name, $label, [ "class" => "control-label" ]); } $markup .= Form::textarea($name, $value, $parameters); break; case "password": if (empty($options['no_label'])) { $markup .= Form::rawLabel($name, $label, [ "class" => "control-label" ]); } $markup .= Form::password($name, $parameters); break; case "checkbox": $markup .= "
"; if (empty($options['no_label'])) { $markup .= ""; } $markup .= "
"; break; case "hidden": $markup .= Form::hidden($name, $value); break; case "select": if (empty($options['no_label'])) { $markup .= Form::rawLabel($name, $label, [ "class" => "control-label" ]); } if (!in_array('multiple', $parameters)) { $options['options'] = [NULL => 'Choose an option'] + $options['options']; } $markup .= Form::select($name, $options['options'], $value, $parameters); break; case "radio": $markup .= "
"; if (empty($options['no_label'])) { $markup .= ""; } $markup .= "
"; break; } if ($error) { $markup .= ""; $markup .= $error; $markup .= ""; } if ($type !== "hidden") { $markup .= "
"; } return $markup; }); HTML::macro('submit', function ($value = null, $options = []) { $options['class'] = !empty($options['class']) ? 'btn btn-info ' . $options['class'] : 'btn btn-info'; return Form::input('submit', null, $value, $options); }); HTML::macro('snippets', function ($snippets, $show_pagination = true) { include(app_path() . '/views/partials/snippets.php'); if ($show_pagination) { echo $snippets->appends(Input::except('page'))->links(); } }); ================================================ FILE: app/models/BaseModel.php ================================================ created_at->diffForHumans(); } /** * Get human updated at date * * @return mixed */ public function getHumanUpdatedAtAttribute() { return $this->updated_at->diffForHumans(); } } ================================================ FILE: app/models/Role.php ================================================ 'title', 'save_to' => 'slug', ); /** * The snippet belongs to a user * * @return mixed */ public function author() { return $this->belongsTo('User'); } /** * The snippet has many tags * * @return mixed */ public function tags() { return $this->belongsToMany('Tag'); } /** * Hits eloquent accessor * * @return string */ public function getHitsAttribute() { $redis = App::make('redis'); return $redis->zScore('hits', $this->id); } /** * Determine if Snippet has hits/views * * @return boolean */ public function hasHits() { return $this->hits ? true : false; } /** * Determine if the passed User is the Snippet author * * @param User $user User instance * @return boolean */ public function isTheAuthor($user) { return $this->author_id === $user->id; } /** * Increment hits count */ public function incrementHits() { $redis = App::make('redis'); $redis->zIncrBy('hits', 1, $this->id); } /** * Tests links for twitter/url */ protected function testLink($url) { stream_context_set_default( [ "http" => [ "method" => "HEAD" ] ] ); try { $headers = get_headers($url); } catch (Exception $e) { return false; } foreach ($headers as $header) { if (stristr($header, "200 OK")) { return $url; } } return false; } /** * Gets links for twitter/url */ public function getCreditsToLinkAttribute() { $creditsTo = $this->attributes["credits_to"]; $twitterHandle = str_replace("@", "", $creditsTo); $twitterLink = Cache::remember("credits_to_link_twitter_" . $creditsTo, 60, function () use ($twitterHandle) { $url = "http://twitter.com/" . $twitterHandle; return $this->testLink($url); }); if ($twitterLink) { return $twitterLink; } $normalLink = Cache::remember("credits_to_link_normal_" . $creditsTo, 60, function () use ($creditsTo) { return $this->testLink($creditsTo); }); if ($normalLink) { return $normalLink; } return null; } /** * A snippet can be starred by users * * @return mixed */ public function starred() { return $this->hasMany('Starred'); } public function scopeLike($query, $field, $value) { return $query->where($field, 'LIKE', "%$value%"); } } ================================================ FILE: app/models/Starred.php ================================================ belongsTo('Snippet'); } } ================================================ FILE: app/models/Tag.php ================================================ 'name', 'save_to' => 'slug', ); public function snippets() { return $this->belongsToMany('Snippet'); } /** * Determine if Tag has snippets * * @return boolean */ public function hasSnippets() { return $this->snippets()->where('approved', 1)->count() ? true : false; } } ================================================ FILE: app/models/User.php ================================================ 'full_name', 'save_to' => 'slug', ); /** * Define a one-to-many relationship. * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function snippets() { return $this->hasMany('Snippet', 'author_id'); } /** * A user has a role, like administration etc. * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function role() { return $this->belongsTo('Role'); } /** * The user has starred snippets * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function starred() { return $this->hasMany('Starred'); } /** * Get the unique identifier for the user. * * @return mixed */ public function getAuthIdentifier() { return $this->getKey(); } /** * Get the password for the user. * * @return string */ public function getAuthPassword() { return $this->password; } /** * Get the token value for the "remember me" session. * * @return string */ public function getRememberToken() { return $this->remember_token; } /** * Set the token value for the "remember me" session. * * @param string $value * @return void */ public function setRememberToken($value) { $this->remember_token = $value; } /** * Get the column name for the "remember me" token. * * @return string */ public function getRememberTokenName() { return 'remember_token'; } /** * Get the e-mail address where password reminders are sent. * * @return string */ public function getReminderEmail() { return $this->email; } /** * Full name eloquent accessor * * @return string */ public function getFullNameAttribute() { return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name); } /** * Returns the absolute url for the profile picture * @return string */ public function getAbsPhotoUrlAttribute() { if (!$this->photo_url) { $hash = md5(trim(strtolower($this->attributes["email"]))); return "http://www.gravatar.com/avatar/" . $hash . "?s=120"; } $assetsDir = asset('/'); return $assetsDir . $this->photo_url; } /** * Gets the number of snippets that a user has * @return mixed */ public function getSnippetsCountAttribute() { return $this->snippets()->where('approved', 1)->count(); } /** * Password eloquent mutator * * @param $value * @return string */ public function setPasswordAttribute($value) { $this->attributes['password'] = Hash::make($value); } /** * Checks if user is active * * @return boolean */ public function isActive() { return $this->active ? true : false; } /** * Activates a user * * @param $key * @throws RuntimeException * @return boolean */ public function activate($key) { if ($this->activation_key === $key) { $this->active = 1; if ($this->save()) { return true; } throw new \RuntimeException('Saving to database failed.'); } return false; } /** * Checks if user is administration * * @return boolean */ public function isAdmin() { return $this->role->name === 'admin'; } /** * Checks if a user has starred a snippet * * @param integer $snippet_id * @return bool */ public function hasStarred($snippet_id) { return $this->starred()->whereSnippetId($snippet_id)->count() ? true : false; } /** * Stars a snippet * * @param integer $snippet_id * @return bool */ public function starSnippet($snippet_id) { if ($this->hasStarred($snippet_id)) { return; } $this->starred()->create(array('snippet_id' => $snippet_id)); } /** * Unstars a snippet * * @param integer $snippet_id * @return bool */ public function unstarSnippet($snippet_id) { if (!$this->hasStarred($snippet_id)) { return; } $this->starred()->whereSnippetId($snippet_id)->delete(); } } ================================================ FILE: app/routes.php ================================================ '404', 'uses' => function() { return View::make('website.pages.404'); }]); # Pages Route::get('/', ['as' => 'home', 'uses' => 'HomeController@getIndex']); Route::get('roadmap', ['as' => 'pages.roadmap', 'uses' => 'Website\PagesController@showRoadmap']); # Signup Route::get('signup', ['as' => 'auth.getSignup', 'uses' => 'AuthController@getSignup']); Route::post('signup', ['before' => 'csrf', 'as' => 'auth.postSignup', 'uses' => 'AuthController@postSignup']); # Login Route::get('login', ['as' => 'auth.getLogin', 'uses' => 'AuthController@getLogin']); Route::post('login', ['before' => 'csrf', 'as' => 'auth.postLogin', 'uses' => 'AuthController@postLogin']); # Logout Route::get('logout', ['as' => 'auth.getLogout', 'uses' => 'AuthController@getLogout']); Route::get('auth/activate/{userSlug}/key/{activationKey}', ['as' => 'auth.getActivateAccount', 'uses' => 'AuthController@getActivateAccount']); /** * Snippet Routes */ Route::get('snippets', ['as' => 'snippet.getIndex', 'uses' => 'SnippetController@getIndex']); Route::get('snippets/{slug}', ['as' => 'snippet.getShow', 'uses' => 'SnippetController@getShow']); Route::get('snippets/{slug}/star', ['as' => 'snippet.star', 'uses' => 'SnippetController@starSnippet']); Route::get('snippets/{slug}/unstar', ['as' => 'snippet.unStar', 'uses' => 'SnippetController@unstarSnippet']); /** * Tag Routes */ Route::get('tags/{slug}', ['as' => 'tag.getShow', 'uses' => 'TagController@getShow']); /** * Password Reset Routes */ Route::get('password/remind', ['as' => 'password.remind', 'uses' => 'RemindersController@getRemind']); Route::post('password/remind', ['before' => 'csrf', 'as' => 'password.remind', 'uses' => 'RemindersController@postRemind']); Route::get('password/reset/{token}', ['as' => 'password.reset', 'uses' => 'RemindersController@getReset']); Route::post('password/reset/{token}', ['before' => 'csrf', 'as' => 'password.reset', 'uses' => 'RemindersController@postReset']); /** * Profile Routes */ Route::get('profiles', ['as' => 'user.getIndex', 'uses' => 'UserController@getIndex']); Route::get('profiles/{slug}', ['as' => 'user.getProfile', 'uses' => 'UserController@getProfile']); Route::get('profiles/{slug}/settings', ['as' => 'user.getSettings', 'uses' => 'UserController@getSettings']); Route::put('profiles/{slug}/settings', ['as' => 'user.putSettings', 'uses' => 'UserController@putSettings']); Route::get('profiles/{slug}/snippets', ['as' => 'user.getSnippets', 'uses' => 'UserController@getSnippets']); /** * Member Routes */ Route::group( ['prefix' => 'members', 'before' => ['auth']], function () { # Dashboard Route::get('dashboard', ['as' => 'member.user.dashboard', 'uses' => 'Member\UserController@dashboard']); # Snippets Route::get('snippets/{slug}', ['as' => 'member.snippet.getShow', 'uses' => 'Member\SnippetController@getShow']); Route::get('snippets/{slug}/edit', ['as' => 'member.snippet.getEdit', 'uses' => 'Member\SnippetController@getEdit']); Route::post('snippets/{slug}/update', ['before' => 'csrf', 'as' => 'member.snippet.postUpdate', 'uses' => 'Member\SnippetController@postUpdate']); Route::get('submit/snippet', ['as' => 'member.snippet.getCreate', 'uses' => 'Member\SnippetController@getCreate']); Route::post('submit/snippet', ['before' => 'csrf', 'as' => 'member.snippet.postStore', 'uses' => 'Member\SnippetController@postStore']); }); /** * Admin Routes */ Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function () { Route::get('/', ['as' => 'admin.index', 'uses' => 'IndexController@getIndex']); }); ================================================ FILE: app/start/artisan.php ================================================ prepareForTests(); } /** * Creates the application. * * @return \Symfony\Component\HttpKernel\HttpKernelInterface */ public function createApplication() { $unitTesting = true; $testEnvironment = 'testing'; return require __DIR__.'/../../bootstrap/start.php'; } /** * Migrates the database. * */ private function prepareForTests() { Artisan::call('migrate:reset'); Artisan::call('migrate'); Eloquent::unguard(); // create roles $this->generateRoles(); Eloquent::reguard(); // reset redis db App::make('redis')->flushAll(); } public function generateRoles() { Role::truncate(); Role::create(array( 'name' => 'admin' )); Role::create(array( 'name' => 'member' )); } /** * NOTE: this only works on PHP version 5.3.2 and above * * Call protected/private method of a class. * * @param object &$object Instantiated object that we will run method on. * @param string $methodName Method name to call * @param array $parameters Array of parameters to pass into method. * * @return mixed Method return. */ public function invokeMethod(&$object, $methodName, array $parameters = array()) { $reflection = new \ReflectionClass(get_class($object)); $method = $reflection->getMethod($methodName); $method->setAccessible(true); return $method->invokeArgs($object, $parameters); } } ================================================ FILE: app/tests/functional/Controller/AuthControllerTest.php ================================================ client->request('GET', route('auth.getSignup')); $this->assertTrue($this->client->getResponse()->isOk()); } public function testSuccessfulSignup() { $inputs = array( 'username' => 'johndoe25', 'password' => 'dummypassword', 'password_confirmation' => 'dummypassword', 'email' => 'johndoe@gmail.com', 'first_name' => 'John', 'last_name' => 'Doe', ); $response = $this->call('POST', route('auth.postSignup', $inputs)); $this->assertRedirectedToRoute('auth.getSignup'); $this->assertSessionHas('message', 'Successfully registered. Please check your email and activate your account.'); $user = User::where('email', '=', $inputs['email'])->first(); $this->assertNotNull($user); $this->assertTrue((Hash::check($inputs['password'], $user->password))); $this->assertEquals('member', $user->role->name); } public function testInvalidSignup() { $response = $this->call('POST', route('auth.postSignup')); $this->assertRedirectedToRoute('auth.getSignup'); $this->assertSessionHas('errors'); } public function testSuccessfulAccountActivation() { // NOTE: for some reason, Ways generator doesn't respect the fillable // attribute of Eloquent model so active column is being filled with // data so I needed to specify active = 0 // @TODO: find a better solution $user = Factory::create('User', array('active' => 0)); $this->call('GET', route('auth.getActivateAccount', array($user->slug, $user->activation_key))); $this->assertRedirectedToRoute('home'); $this->assertSessionHas('message', 'Your account is now activated.'); } public function testInvalidAccountActivationUsingWrongKey() { // NOTE: for some reason, Ways generator doesn't respect the fillable // attribute of Eloquent model so active column is being filled with // data so I needed to specify active = 0 // @TODO: find a better solution $user = Factory::create('User', array('active' => 0)); $this->call('GET', route('auth.getActivateAccount', array($user->slug, 'wrong activation key'))); $this->assertRedirectedToRoute('home'); $this->assertSessionHas('message', 'Invalid activation key.'); } public function testGetLogin() { $crawler = $this->client->request('GET', route('auth.getLogin')); $this->assertTrue($this->client->getResponse()->isOk()); } public function testSuccessfulLogin() { $rawPassword = 'admin'; $user = Factory::create('User', array('password' => $rawPassword, 'active' => 1)); $inputs = array( 'username' => $user->username, 'password' => $rawPassword ); $crawler = $this->client->request('POST', route('auth.postLogin', $inputs)); $this->assertRedirectedToRoute('home'); } public function testInvalidLoginUsingUnregisteredUser() { $inputs = array( 'username' => 'unregistered username', 'password' => 'password' ); $crawler = $this->client->request('POST', route('auth.postLogin', $inputs)); $this->assertRedirectedToRoute('auth.getLogin'); $this->assertSessionHas('message', 'Wrong username or password'); } public function testInvalidLoginUsingInactiveUser() { $rawPassword = 'admin'; $user = Factory::create('User', array('password' => $rawPassword, 'active' => 0)); $inputs = array( 'username' => $user->username, 'password' => $rawPassword ); $crawler = $this->client->request('POST', route('auth.postLogin', $inputs)); $this->assertRedirectedToRoute('auth.getLogin'); $this->assertSessionHas('message', 'Wrong username or password'); } public function testInvalidLoginUsingWrongCredentials() { $user = Factory::create('User', array('password' => 'admin', 'active' => 1)); $inputs = array( 'username' => $user->username, 'password' => 'wrong password' ); $crawler = $this->client->request('POST', route('auth.postLogin', $inputs)); $this->assertRedirectedToRoute('auth.getLogin'); $this->assertSessionHas('message', 'Wrong username or password'); } } ================================================ FILE: app/tests/functional/Controller/HomeControllerTest.php ================================================ be($user); $snippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 1, 'deleted_at' => null)); $notYetApprovedSnippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 0, 'deleted_at' => null)); $response = $this->call('GET', '/'); $view = $response->original; $this->assertEquals(count($view['snippets']), 1); $this->assertEquals($snippet->title, $view['snippets'][0]->title); } public function testHomePageTopSnippetContributors() { // with 2 approved and 1 not yet approved snippet $user = Factory::create('User', array('active' => 1)); $this->be($user); Factory::create('Snippet', array('author_id' => $user->id, 'approved' => 1, 'deleted_at' => null)); Factory::create('Snippet', array('author_id' => $user->id, 'approved' => 1, 'deleted_at' => null)); Factory::create('Snippet', array('author_id' => $user->id, 'approved' => 0, 'deleted_at' => null)); // with 1 not yet approved snippet $secondUser = Factory::create('User', array('active' => 1)); $this->be($secondUser); Factory::create('Snippet', array('author_id' => $secondUser->id, 'approved' => 0, 'deleted_at' => null)); // with 1 approved and 3 not yet approved snippets $thirdUser = Factory::create('User', array('active' => 1)); $this->be($thirdUser); Factory::create('Snippet', array('author_id' => $thirdUser->id, 'approved' => 1, 'deleted_at' => null)); Factory::create('Snippet', array('author_id' => $thirdUser->id, 'approved' => 0, 'deleted_at' => null)); Factory::create('Snippet', array('author_id' => $thirdUser->id, 'approved' => 0, 'deleted_at' => null)); Factory::create('Snippet', array('author_id' => $thirdUser->id, 'approved' => 0, 'deleted_at' => null)); $response = $this->call('GET', '/'); $view = $response->original; // only 2 is expected since we are only rendering contributors w/ approved snippets $this->assertEquals(count($view['topSnippetContributors']), 2); # rank 1 should be $user $this->assertEquals($view['topSnippetContributors'][0]->full_name, $user->full_name); $this->assertEquals($view['topSnippetContributors'][0]->snippets_count, 2); # rank 2 should be $thirdUser $this->assertEquals($view['topSnippetContributors'][1]->full_name, $thirdUser->full_name); $this->assertEquals($view['topSnippetContributors'][1]->snippets_count, 1); } } ================================================ FILE: app/tests/functional/Controller/Member/SnippetControllerTest.php ================================================ be($user); $snippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 0, 'deleted_at' => null)); $response = $this->call('GET', route('member.snippet.getShow', $snippet->slug)); $this->assertResponseOk(); $view = $response->original; $this->assertEquals($view['snippet']->title, $snippet->title); } public function testGetShowRendersApprovedSnippets() { $user = Factory::create('User'); $this->be($user); $snippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 1, 'deleted_at' => null)); $response = $this->call('GET', route('member.snippet.getShow', $snippet->slug)); $this->assertResponseOk(); $view = $response->original; $this->assertEquals($view['snippet']->title, $snippet->title); } public function testGetCreate() { $response = $this->call('GET', route('member.snippet.getCreate')); $this->assertResponseOk(); $this->assertViewHas('tags'); } public function testPostStoreThrowsErrorOnBlankInput() { $user = Factory::create('User'); $this->be($user); $input = array(); $response = $this->call('POST', route('member.snippet.postStore', $input)); $this->assertRedirectedToRoute('member.snippet.getCreate'); $this->assertSessionHas('errors'); } public function testPostStoreThrowsErrorOnInvalidResourceFormat() { $user = Factory::create('User'); $this->be($user); $input = array( 'title' => 'dummy title', 'body' => 'dummy body', 'resource' => 'invalid resource url format' ); $response = $this->call('POST', route('member.snippet.postStore', $input)); $this->assertRedirectedToRoute('member.snippet.getCreate'); $this->assertSessionHas('errors'); } /** * @expectedException Symfony\Component\HttpKernel\Exception\NotFoundHttpException */ public function testPostStoreThrowsExceptionOnInvalidTags() { $user = Factory::create('User'); $this->be($user); # invalid tags $inputs = array( 'title' => 'dummy title', 'body' => 'dummy body', 'tags' => array('12345') // <-- invalid tag id since no tags are on the db yet ); $response = $this->call('POST', route('member.snippet.postStore'), $inputs); } public function testPostStoreSavesSnippetOnValidInput() { $user = Factory::create('User'); $this->be($user); $tag = Factory::create('Tag'); $secondTag = Factory::create('Tag'); $input = array( 'title' => 'dummy title', 'body' => 'dummy body', 'resource' => Config::get('site.url'), 'tags' => array($tag->id, $secondTag->id) ); $response = $this->call('POST', route('member.snippet.postStore'), $input); $this->assertRedirectedToRoute('member.snippet.getCreate'); $this->assertSessionHas('message', "Your snippet is now submitted and waiting for admin's approval"); } public function testGetEdit() { $user = Factory::create('User'); $user->id = (string) $user->id; $this->be($user); $snippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 1, 'deleted_at' => null)); $response = $this->call('GET', route('member.snippet.getEdit', $snippet->slug)); $this->assertResponseOk(); $view = $response->original; $this->assertEquals($view['snippet']->title, $snippet->title); $this->assertViewHas('tags'); } public function testPostUpdateUpdatesSnippetOnValidInput() { $user = Factory::create('User'); $user->id = (string) $user->id; $this->be($user); $tag = Factory::create('Tag'); $secondTag = Factory::create('Tag'); $snippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 1, 'deleted_at' => null)); $input = array( 'title' => 'dummy title', 'body' => 'dummy body', 'resource' => Config::get('site.url'), 'tags' => array($tag->id, $secondTag->id) ); $uri = route('member.snippet.postUpdate', $snippet->slug); $response = $this->call('POST', $uri, $input); $snippetFromDB = Snippet::where('slug', $snippet->slug)->first(); $this->assertEquals($input['title'], $snippetFromDB->title); $this->assertRedirectedToRoute('member.snippet.getShow', $snippet->slug); $this->assertSessionHas('message', 'Update successful'); } // public function testPostUpdateDoesntUpdateOnInvalidResourceFormat() // { // $user = Factory::create('User'); // $this->be($user); // $snippet = Factory::create('Snippet', array( // 'author_id' => $user->id, 'approved' => 1, // 'deleted_at' => null)); // $input = array( // 'title' => 'dummy title', // 'body' => 'dummy body', // 'resource' => 'invalid-resource-format' // ); // $uri = route('member.snippet.postUpdate', $snippet->slug); // $response = $this->call('POST', $uri, $input); // // $snippetFromDB = Snippet::where('slug', $snippet->slug)->first(); // // $this->assertNull($snippetFromDB); // // $this->assertRedirectedToRoute('member.snippet.getEdit', $snippet->slug); // // $this->assertSessionHas('errors'); // } } ================================================ FILE: app/tests/functional/Controller/Member/UserControllerTest.php ================================================ be($user); $notYetApprovedSnippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 0, 'deleted_at' => null)); $approvedSnippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 1, 'deleted_at' => null)); $response = $this->call('GET', route('member.user.dashboard')); $view = $response->original; $this->assertEquals(count($view['my_snippets']), 2); } } ================================================ FILE: app/tests/functional/Controller/SnippetControllerTest.php ================================================ be($user); $snippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 1, 'deleted_at' => null)); $notYetApprovedSnippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 0, 'deleted_at' => null)); $response = $this->call('GET', route('snippet.getIndex')); $view = $response->original; $this->assertEquals(1, count($view['snippets'])); $this->assertEquals($snippet->title, $view['snippets'][0]->title); } /** * @expectedException Symfony\Component\HttpKernel\Exception\NotFoundHttpException */ public function testGetShowDoesNotRenderNotYetApprovedSnippets() { $user = Factory::create('User'); $this->be($user); $snippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 0, 'deleted_at' => null)); $response = $this->call('GET', route('snippet.getShow', $snippet->slug)); } public function testGetShowRendersApprovedSnippets() { $user = Factory::create('User'); $this->be($user); $snippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 1, 'deleted_at' => null)); $response = $this->call('GET', route('snippet.getShow', $snippet->slug)); $this->assertResponseOk(); $view = $response->original; $this->assertEquals($view['snippet']->title, $snippet->title); } } ================================================ FILE: app/tests/functional/Controller/TagControllerTest.php ================================================ be($user); $notYetApprovedSnippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 0, 'deleted_at' => null)); $approvedSnippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 1, 'deleted_at' => null)); $response = $this->call('GET', route('snippet.getIndex')); $view = $response->original; $this->assertEquals(count($view['snippets']), 1); $this->assertEquals($approvedSnippet->title, $view['snippets'][0]->title); } } ================================================ FILE: app/tests/functional/Controller/UserControllerTest.php ================================================ 1)); $secondUser = Factory::create('User', array('active' => 0)); $this->be($user); $notYetApprovedSnippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 0, 'deleted_at' => null)); $approvedSnippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 1, 'deleted_at' => null)); $response = $this->call('GET', route('user.getIndex')); $view = $response->original; $this->assertResponseOk(); # should be 1 because only 1 user is active, the 2nd user is not yet active $this->assertEquals(1, count($view['users'])); # should be 1 because only 1 submitted snippet of $user is approved $this->assertEquals(1, $view['users'][0]->snippets_count); } public function testGetProfile() { $user = Factory::create('User', array('active' => 1)); $response = $this->call('GET', route('user.getProfile', $user->slug)); $view = $response->original; $this->assertResponseOk(); $this->assertViewHas('user'); } public function testGetSnippets() { $user = Factory::create('User', array('active' => 1)); $this->be($user); $notYetApprovedSnippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 0, 'deleted_at' => null)); $approvedSnippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 1, 'deleted_at' => null)); $response = $this->call('GET', route('user.getSnippets', $user->slug)); $this->assertResponseOk(); $view = $response->original; # should be 1 because only 1 submitted snippet of $user is approved $this->assertEquals(1, count($view['snippets'])); $this->assertViewHas('user'); } } ================================================ FILE: app/tests/integration/Model/UserModelTest.php ================================================ first_name = 'John'; $user->last_name = 'Doe'; $this->assertEquals('John Doe', $user->full_name); } public function testSetPasswordAttribute() { $user = new User; $user->password = 'myawesomepassword'; $this->assertTrue((Hash::check('myawesomepassword', $user->password))); } public function testGetAbsPhotoUrlAttribute() { $user = new User; $user->email = 'johndoe@gmail.com'; $this->assertNotEquals(asset('photo.png'), $user->abs_photo_url); $user->photo_url = 'photo.png'; $this->assertEquals(asset('photo.png'), $user->abs_photo_url); } } ================================================ FILE: app/tests/integration/Repo/EloquentSnippetRepositoryTest.php ================================================ be($user); $expectedTotalItems = 4; $snippets = array(); for ($i=0; $i < $expectedTotalItems; $i++) { $snippets[] = Factory::create('Snippet', array('author_id' => $user->id, 'approved' => 1, 'deleted_at' => null)); } $snippetRepo = new EloquentSnippetRepository( new Snippet, $this->app->make('LaraSnipp\Repo\Tag\TagRepositoryInterface'), $this->app->make('LaraSnipp\Repo\User\UserRepositoryInterface') ); $result = $snippetRepo->byPage($page=1, $limit=3, $all=false); $this->assertEquals($result->totalItems, $expectedTotalItems); $this->assertEquals(count($result->items), $limit); } public function testTotalSnippets() { $user = Factory::create('User'); $this->be($user); // create 3 approved snippets for ($i=0; $i < 3; $i++) { $snippets[] = Factory::create('Snippet', array('author_id' => $user->id, 'approved' => 1, 'deleted_at' => null)); } // create 1 not yet approved snippet Factory::create('Snippet', array('author_id' => $user->id, 'approved' => 0, 'deleted_at' => null)); $snippetRepo = new EloquentSnippetRepository( new Snippet, $this->app->make('LaraSnipp\Repo\Tag\TagRepositoryInterface'), $this->app->make('LaraSnipp\Repo\User\UserRepositoryInterface') ); // test totalSnippets only returns the count of approved snippets if $all = false $totalSnippets = $this->invokeMethod($snippetRepo, 'totalSnippets', array($all = false)); $this->assertEquals($totalSnippets, 3); // test totalSnippets returns the count of all snippets (approved & not yet approved) $totalSnippets = $this->invokeMethod($snippetRepo, 'totalSnippets', array($all = true)); $this->assertEquals($totalSnippets, 4); } public function testByTag() { $user = Factory::create('User'); $this->be($user); $snippets = array(); $tag = Factory::create('Tag'); # create 4 approved snippets that is linked to $tag for ($i=0; $i < 4; $i++) { $snippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 1, 'deleted_at' => null )); $snippet->tags()->attach($tag->id); $snippets[] = $snippet; } # snippet w/ same tag as above but is not yet approved $snippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 0, 'deleted_at' => null )); $snippet->tags()->attach($tag->id); # snippet w/o a tag Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 1, 'deleted_at' => null )); # snippet w/ a different tag $snippet = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 1, 'deleted_at' => null )); $secondTag = Factory::create('Tag'); $snippet->tags()->attach($secondTag->id); $snippetRepo = new EloquentSnippetRepository( new Snippet, $this->app->make('LaraSnipp\Repo\Tag\TagRepositoryInterface'), $this->app->make('LaraSnipp\Repo\User\UserRepositoryInterface') ); $result = $snippetRepo->byTag($tag->slug, $page = 1, $limit = 3); // should only have 4 total snippets for $tag because even if it really // has 5, only 4 snippets are approved $this->assertEquals(4, $result->totalItems); // should be 3 because we set $limit = 3 in the // $snippetRepo->byTag($tag->slug, $page = 1, $limit = 3); call above $this->assertEquals(3 , count($result->items)); } public function testGetMostViewed() { $user = Factory::create('User'); $this->be($user); $snippets = array(); $tag = Factory::create('Tag'); // create 3 approved snippets for ($i=0; $i < 3; $i++) { $snippets[] = Factory::create('Snippet', array( 'author_id' => $user->id, 'approved' => 1, 'deleted_at' => null )); } $redis = App::make('redis'); // add 10 hits in snippet[1] $redis->zIncrBy('hits', 10, $snippets[1]->id); // add 5 hits in snippet[2] $redis->zIncrBy('hits', 5, $snippets[2]->id); // add 1 hit in snippet[0] $redis->zIncrBy('hits', 1, $snippets[0]->id); // expected ranking: // 1. $snippets[1] // 2. $snippets[2] // 3. $snippets[0] $snippetRepo = new EloquentSnippetRepository( new Snippet, $this->app->make('LaraSnipp\Repo\Tag\TagRepositoryInterface'), $this->app->make('LaraSnipp\Repo\User\UserRepositoryInterface') ); $snippetsResult = $snippetRepo->getMostViewed(); $this->assertEquals($snippets[1], $snippetsResult[0]); } } ================================================ FILE: app/tests/integration/Repo/EloquentUserRepositoryTest.php ================================================ 1)); $secondUser = Factory::create('User', array('active' => 1)); $thirdUser = Factory::create('User', array('active' => 1)); // 1 snippet for $user $this->be($user); Factory::create('Snippet', array('author_id' => $user->id, 'approved' => 1, 'deleted_at' => null)); // 2 snippets for $secondUser $this->be($secondUser); Factory::create('Snippet', array('author_id' => $secondUser->id, 'approved' => 1, 'deleted_at' => null)); Factory::create('Snippet', array('author_id' => $secondUser->id, 'approved' => 1, 'deleted_at' => null)); // 3 not yet approved snippets for $thirdUser $this->be($thirdUser); Factory::create('Snippet', array('author_id' => $thirdUser->id, 'approved' => 0, 'deleted_at' => null)); Factory::create('Snippet', array('author_id' => $thirdUser->id, 'approved' => 0, 'deleted_at' => null)); Factory::create('Snippet', array('author_id' => $thirdUser->id, 'approved' => 0, 'deleted_at' => null)); $userRepo = new EloquentUserRepository(new User); $results = $userRepo->getTopSnippetContributors($limit = 3); // check if the top snippet contributor is $secondUser $this->assertEquals($results[0]->first_name, $secondUser->first_name); // check that there are only 2 snippet contributors since the snippets // submitted by $thirdUser is not yet approved $this->assertCount(2, $results); } } ================================================ FILE: app/tests/unit/Model/UserModelTest.php ================================================ active = 1; $this->assertTrue($user->isActive()); $user->active = 0; $this->assertFalse($user->isActive()); } } ================================================ FILE: app/views/admin/index.blade.php ================================================ @extends('admin.layouts.master') @section('content')

Dashboard

12
Snippets!
124
Unapproved snippets!
26
Users!
13
Inactive users!
@stop ================================================ FILE: app/views/admin/layouts/master.blade.php ================================================ LaravelSnippets - Admin {{ HTML::style('//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css') }} {{ HTML::style('//cdnjs.cloudflare.com/ajax/libs/metisMenu/2.0.0/metisMenu.min.css') }} {{ HTML::style('//cdnjs.cloudflare.com/ajax/libs/metisMenu/2.0.0/metisMenu.min.css') }} {{ HTML::style('//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css') }}
@include('admin.partials.navbar')
@yield('content')
{{ HTML::script( asset('assets/js/vendors/jquery.min.js') ) }} {{ HTML::script('//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js') }} {{ HTML::script('//cdnjs.cloudflare.com/ajax/libs/metisMenu/2.0.0/metisMenu.min.js') }} {{ HTML::script('/administration/js/sb-admin-2.js') }} ================================================ FILE: app/views/admin/partials/navbar.blade.php ================================================ ================================================ FILE: app/views/auth/login.blade.php ================================================ @extends('layouts.master') @section('content')
@if( $errors->has() )

We encountered the following errors:

@endif

Sign in to your account

{{ Form::open(array('route' => 'auth.postLogin', 'class'=>'form-signin')) }} {{ Form::field(['name' => 'username', 'error' => $errors, 'no_label' => true, 'placeholder' => 'Username', 'parameters' => ['required', 'autofocus']]) }} {{ Form::field(['name' => 'password', 'error' => $errors, 'no_label' => true, 'placeholder' => 'Password', 'type' => 'password', 'parameters' => ['required']]) }}

{{ HTML::submit('Sign in', array('class' => 'btn btn-lg btn-primary btn-block')) }}

@if ( isset( $next ) ) {{ Form::hidden('next', $value = 'snippets/create') }} @endif {{ Form::close() }}
@stop ================================================ FILE: app/views/auth/signup.blade.php ================================================ @extends('layouts.master') @section('content')
@if ($errors->has())

We encountered the following errors:

@endif

Fill in the fields to register

{{ Form::open(array('route' => 'auth.postSignup', 'class'=>'form-signin form-register')) }} {{ Form::field(['name' => 'username', 'error' => $errors, 'no_label' => true, 'placeholder' => 'Username', 'parameters' => ['required', 'autofocus']]) }} {{ Form::field(['name' => 'password', 'error' => $errors, 'no_label' => true, 'placeholder' => 'Password', 'parameters' => ['required'], 'type' => 'password']) }} {{ Form::field(['name' => 'password_confirmation', 'error' => $errors, 'no_label' => true, 'placeholder' => 'Password confirmation', 'parameters' => ['required'], 'type' => 'password']) }} {{ Form::field(['name' => 'first_name', 'error' => $errors, 'no_label' => true, 'placeholder' => 'First name', 'parameters' => ['required']]) }} {{ Form::field(['name' => 'last_name', 'error' => $errors, 'no_label' => true, 'placeholder' => 'Last name', 'parameters' => ['required']]) }} {{ Form::field(['name' => 'email', 'error' => $errors, 'no_label' => true, 'placeholder' => 'Email Address', 'parameters' => ['required']]) }}

{{ HTML::submit('Register', array('class' => 'btn btn-lg btn-primary btn-block')) }}

{{ Form::close() }}

@stop ================================================ FILE: app/views/emails/auth/activate.blade.php ================================================ Activate your account by clicking this link {{ $activationUrl }} ================================================ FILE: app/views/emails/auth/reminder.blade.php ================================================

Password Reset

To reset your password, complete this form: {{ URL::to('password/reset', array($token)) }}.
================================================ FILE: app/views/layouts/master.blade.php ================================================ @section('title') {{ Config::get('site.title') }} @show @section('meta_description') @show @section('meta_author') @show {{ HTML::style('//fonts.googleapis.com/css?family=Source+Sans+Pro:400,600,700') }} {{ HTML::style('//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css') }} {{ HTML::style('//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css') }} {{ HTML::style( asset('packages/codemirror-3.19/lib/codemirror.css') ) }} {{ HTML::style( asset('packages/codemirror-3.19/theme/monokai.css') ) }} {{ HTML::style( asset('packages/google-code-prettify/prettify.css') ) }} {{ HTML::style( asset('packages/chosen_v1.0.0/chosen.min.css') ) }} {{ HTML::style( asset('assets/css/styles.css') ) }} @if ( App::environment() === 'production' ) @endif @include('partials/header')
@include('partials/notifications') @yield('content')
@include('partials/footer') {{ HTML::script( asset('assets/js/vendors/jquery.min.js') ) }} {{ HTML::script('//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js') }} {{ HTML::script( asset('packages/codemirror-3.19/lib/codemirror.js') ) }} {{ HTML::script( asset('packages/codemirror-3.19/mode/clike/clike.js') ) }} {{ HTML::script( asset('packages/codemirror-3.19/mode/php/php.js') ) }} {{ HTML::script( asset('packages/google-code-prettify/prettify.js') ) }} {{ HTML::script( asset('packages/chosen_v1.0.0/chosen.jquery.min.js') ) }} {{ HTML::script( asset('assets/js/common.js') ) }} {{ HTML::script( asset('assets/js/snippet.js') ) }} {{ HTML::script('//w.sharethis.com/button/buttons.js') }} @section('scripts') @show ================================================ FILE: app/views/member/snippets/create.blade.php ================================================ @extends('layouts.master') @section('content')
@if($errors->has())

We encountered the following errors:

@endif

Submit a snippet

@stop ================================================ FILE: app/views/member/snippets/edit.blade.php ================================================ @extends('layouts.master') @section('content')
@if($errors->has())

We encountered the following errors:

@endif

Editing snippet "{{ e($snippet->title) }}"

@stop ================================================ FILE: app/views/member/users/dashboard.blade.php ================================================ @extends('layouts.master') @section('content')

Starred Snippets

@if (count($starred_snippets) > 0) @else

No starred snippets yet. Why not add one?

@endif

My Snippets

@if (count($my_snippets) > 0) {{ $my_snippets->links() }} @else

No snippets yet. Why not add one?

@endif
@stop ================================================ FILE: app/views/partials/footer.blade.php ================================================

Want to help with the site? We accept pull requests! Find us on Github

================================================ FILE: app/views/partials/header.blade.php ================================================ @if ( Request::is('/') ) @include('partials/search') @else @include('partials/search-narrow') {{ SiteHelpers::breadcrumbs() }} @endif ================================================ FILE: app/views/partials/notifications.blade.php ================================================ @if (Session::has('message'))
{{ Session::get('message') }}
@endif ================================================ FILE: app/views/partials/pagination.blade.php ================================================
getLastPage() > 1): ?>
================================================ FILE: app/views/partials/search-narrow.blade.php ================================================
================================================ FILE: app/views/partials/search.blade.php ================================================
{{ Config::get('site.welcome_message') }}

@include('partials.searchForm', ['formClass' => 'form-horizontal'])
================================================ FILE: app/views/partials/searchForm.blade.php ================================================ {{Form::open(['route' => 'snippet.getIndex', 'method' => 'GET', 'class' => $formClass])}}
{{Form::text('q', Request::get('q') ?: '', ['class' => 'input-lg form-control', 'placeholder' => 'Looking for a snippet?'])}} {{Form::submit('search', ['class' => 'search-button-homepage'])}}
{{Form::close()}} ================================================ FILE: app/views/partials/sidebars/default.blade.php ================================================ ================================================ FILE: app/views/partials/sidebars/snippet.blade.php ================================================ ================================================ FILE: app/views/partials/sidebars/widgets/author.blade.php ================================================ ================================================ FILE: app/views/partials/sidebars/widgets/categories.blade.php ================================================ @if ( count( $tags ) > 0 ) @endif ================================================ FILE: app/views/partials/sidebars/widgets/social.blade.php ================================================ ================================================ FILE: app/views/partials/sidebars/widgets/top-contributors.blade.php ================================================ @if ( count( $topSnippetContributors ) > 0 ) @endif ================================================ FILE: app/views/partials/snippets.php ================================================ 0 ): ?>
Snippet Posted
title); ?> humanCreatedAt; ?> hasHits() ? $snippet->hits : '0'; ?> comments ? $snippet->comments : '0'; ?> starred->count(); ?>

No snippets available.

================================================ FILE: app/views/password/remind.blade.php ================================================ @extends('layouts.master') @section('content')
@if ($errors->has())

We encountered the following errors:

@endif

Reset Your Password

{{ Form::open() }} {{ Form::field(['name' => 'email', 'error' => $errors, 'no_label' => true, 'placeholder' => 'Email Address', 'parameters' => ['required', 'autofocus']]) }}

{{ HTML::submit('RESET PASSWORD', array('class' => 'btn-lg btn-primary btn-block')) }}

{{ Form::close() }}
@stop ================================================ FILE: app/views/password/reset.blade.php ================================================ @extends('layouts.master') @section('content')
@if($errors->has())

We encountered the following errors:

@endif

Fill in the fields below to set your new password

@stop ================================================ FILE: app/views/snippets/index.blade.php ================================================ @extends('layouts.master') @section('content')

All Snippets

@if(Request::has('q') && Request::get('q') !== '')

You searched for:

@include('partials.searchForm', ['formClass' => 'form-horizontal'])
@endif {{ HTML::snippets($snippets) }}
@include('partials/sidebars/default')
@stop ================================================ FILE: app/views/snippets/show.blade.php ================================================ @extends('layouts.master') @if ($snippet->description) @section('meta_description') @stop @endif @if ($snippet->author) @section('meta_author') @stop @endif @section('title') {{ e($snippet->title) }} | {{ Config::get('site.title') }} @stop @section('content')
Glee Help Desk

{{ e($snippet->title) }}

{{ $snippet->hasHits() ? $snippet->hits : '0' }} views
@if ($has_starred) Unstar @else Star @endif
{{ $snippet->starred->count() }}

@if($snippet->description)

Description:

{{ Purifier::clean( Parsedown::instance()->parse( $snippet->description ), array('HTML.Nofollow' => true) ) }}

@endif @if($snippet->credits_to) @if ( $snippet->creditsToLink )

Credits to: {{ e($snippet->credits_to) }}

@else

Credits to: {{ e($snippet->credits_to) }}

@endif @endif @if($snippet->resource)

Resource: {{ e($snippet->resource) }}

@endif
{{ e($snippet->body) }}
@if ( count( $snippet->tags ) > 0 ) @endif

Submitted {{ $snippet->humanCreatedAt }}.
Updated {{ $snippet->humanUpdatedAt }}.

@if ( App::environment() === 'production' )
comments powered by Disqus
@endif
@include('partials/sidebars/snippet')
@stop @section('scripts') @if ( App::environment() === 'production' ) @endif @stop ================================================ FILE: app/views/tags/snippets.blade.php ================================================ @extends('layouts.master') @section('content')

{{ substr( $tag->name, -1 ) === 's' ? e( substr( $tag->name, 0, -1 ) ) : e( $tag->name ) }} Snippets

{{ HTML::snippets($snippets) }}
@include('partials/sidebars/default')
@stop ================================================ FILE: app/views/users/index.blade.php ================================================ @extends('layouts.master') @section('content')

Members

@if ($users->count()) @foreach($users->chunk(4) as $usersChunked) @endforeach {{ $users->links() }} @else

No site members yet.

@endif
@stop ================================================ FILE: app/views/users/profile.blade.php ================================================ @extends('layouts.master') @section('content')

{{ e($user->full_name) }}

About Me:

@if($user->about_me)

{{ e($user->about_me) }}

@else

No data available.

@endif

Links:


View submitted snippets
@stop ================================================ FILE: app/views/users/settings.blade.php ================================================ @extends('layouts.master') @section('content') {{ Form::model($user,['route' => ['user.putSettings',$user->slug], 'method' =>'PUT', 'class'=>'form', 'role'=>'form']) }}
{{ Form::label('username', 'Username') }} {{ Form::text('username', @$user->username, ['class'=>'form-control', 'readonly' => true]) }} @if($errors->has('username')){{$errors->first('username')}}@endif
{{ Form::label('email', 'Email') }} {{ Form::email('email', @$user->email, ['class'=>'form-control', 'readonly' => true]) }} @if($errors->has('email')){{$errors->first('email')}}@endif
{{ Form::label('first_name', 'First name') }} {{ Form::text('first_name', @$user->first_name, ['class'=>'form-control', 'placeholder' => 'Your first name']) }} @if($errors->has('first_name')){{$errors->first('first_name')}}@endif
{{ Form::label('last_name', 'Last name') }} {{ Form::text('last_name', @$user->last_name, ['class'=>'form-control', 'placeholder' => 'Your last name']) }} @if($errors->has('last_name')){{$errors->first('last_name')}}@endif
{{ Form::label('twitter_url', 'Twitter url') }} {{ Form::text('twitter_url', @$user->twitter_url, ['class'=>'form-control', 'placeholder' => 'Twitter URL']) }} @if($errors->has('twitter_url')){{$errors->first('twitter_url')}}@endif
{{ Form::label('facebook_url', 'Facebook url') }} {{ Form::text('facebook_url', @$user->facebook_url, ['class'=>'form-control', 'placeholder' => 'Facebook URL']) }} @if($errors->has('facebook_url')){{$errors->first('facebook_url')}}@endif
{{ Form::label('github_url', 'Github url') }} {{ Form::text('github_url', @$user->github_url, ['class'=>'form-control', 'placeholder' => 'Github URL']) }} @if($errors->has('github_url')){{$errors->first('github_url')}}@endif
{{ Form::label('website_url', 'Website url') }} {{ Form::text('website_url', @$user->website_url, ['class'=>'form-control', 'placeholder' => 'Website URL']) }} @if($errors->has('website_url')){{$errors->first('website_url')}}@endif
{{ Form::label('about_me', 'About me') }} {{ Form::textarea('about_me', @$user->about_me, ['class'=>'form-control', 'placeholder' => 'Write something interesting about yourself...']) }}

Reset your password

{{Form::input('password', 'password', null, ['class' => 'form-control', 'placeholder' => 'New password'])}} @if($errors->has('password')){{$errors->first('password')}}@endif
{{Form::input('password', 'password_confirmation', null, ['class' => 'form-control', 'placeholder' => 'Confirm new password'])}} @if($errors->has('password_confirmation')){{$errors->first('password_confirmation')}}@endif
{{ Form::close() }} @stop ================================================ FILE: app/views/users/snippets.blade.php ================================================ @extends('layouts.master') @section('content')

{{ e($user->full_name) }}'s Snippets

{{ HTML::snippets($snippets) }} @stop ================================================ FILE: app/views/website/pages/404.blade.php ================================================ @extends('layouts.master') @section('content')

404

We lost your page or maybe it didn't ever exist

Care to go home?

@stop ================================================ FILE: app/views/website/pages/index.blade.php ================================================ @extends('layouts.master') @section('content')
Glee Help Desk

Most Recent Snippets

{{ HTML::snippets($snippets) }}

Most Popular Snippets

{{ HTML::snippets($mostViewedSnippets, false) }}
@include('partials/sidebars/default')
@stop ================================================ FILE: app/views/website/pages/roadmap.blade.php ================================================ @extends('layouts.master') @section('content')

Roadmap

OK, you're right, you've found a placeholder page. Dull right?

Actually, this page is an addition to resolve GitHub issue Roadmap, because we have plans to do bigger and better with {{{ Config::get('site.name') }}}, in part to serve as an example app and also to provide the web with a home for useful Laravel code snippets to speed up your development and help you to improve your code. We'll update this page soon with super interesting insight (for geeks) to see where we're going with this site and also for you to get involved, if you're geek enough of course. ;)

If you'd like to get involved, check out the {{{ Config::get('site.name') }}} GitHub repo and feel free to improve and submit pull requests!

@stop ================================================ FILE: artisan ================================================ #!/usr/bin/env php setRequestForConsoleEnvironment(); $artisan = Illuminate\Console\Application::start($app); /* |-------------------------------------------------------------------------- | Run The Artisan Application |-------------------------------------------------------------------------- | | When we run the console application, the current CLI command will be | executed in this console and the response sent back to a terminal | or another output device for the developers. Here goes nothing! | */ $status = $artisan->run(); /* |-------------------------------------------------------------------------- | Shutdown The Application |-------------------------------------------------------------------------- | | Once Artisan has finished running. We will fire off the shutdown events | so that any final work may be done by the application before we shut | down the process. This is the last thing to happen to the request. | */ $app->shutdown(); exit($status); ================================================ FILE: bootstrap/autoload.php ================================================ __DIR__.'/../app', /* |-------------------------------------------------------------------------- | Public Path |-------------------------------------------------------------------------- | | The public path contains the assets for your web application, such as | your JavaScript and CSS files, and also contains the primary entry | point for web requests into these applications from the outside. | */ 'public' => __DIR__.'/../public', /* |-------------------------------------------------------------------------- | Base Path |-------------------------------------------------------------------------- | | The base path is the root of the Laravel installation. Most likely you | will not need to change this value. But, if for some wild reason it | is necessary you will do so here, just proceed with some caution. | */ 'base' => __DIR__.'/..', /* |-------------------------------------------------------------------------- | Storage Path |-------------------------------------------------------------------------- | | The storage path is used by Laravel to store cached Blade views, logs | and other pieces of information. You may modify the path here when | you want to change the location of this directory for your apps. | */ 'storage' => __DIR__.'/../app/storage', ); ================================================ FILE: bootstrap/start.php ================================================ detectEnvironment(function() { if (!empty($_SERVER["APPLICATION_ENVIRONMENT"])) { return $_SERVER["APPLICATION_ENVIRONMENT"]; } return "production"; }); /* |-------------------------------------------------------------------------- | Bind Paths |-------------------------------------------------------------------------- | | Here we are binding the paths configured in paths.php to the app. You | should not be changing these here. If you need to change these you | may do so within the paths.php file and they will be bound here. | */ $app->bindInstallPaths(require __DIR__.'/paths.php'); /* |-------------------------------------------------------------------------- | Load The Application |-------------------------------------------------------------------------- | | Here we will load this Illuminate application. We will keep this in a | separate location so we can isolate the creation of an application | from the actual running of the application with a given request. | */ $framework = $app['path.base'].'/vendor/laravel/framework/src'; require $framework.'/Illuminate/Foundation/start.php'; /* |-------------------------------------------------------------------------- | Return The Application |-------------------------------------------------------------------------- | | This script returns the application instance. The instance is given to | the calling script so we can separate the building of the instances | from the actual running of the application and sending responses. | */ return $app; ================================================ FILE: composer.json ================================================ { "name" : "laravel/laravel", "description" : "The Laravel Framework.", "keywords" : ["framework", "laravel"], "license" : "MIT", "require" : { "laravel/framework" : "4.2.*", "cviebrock/eloquent-sluggable" : "1.0.*", "erusev/parsedown" : "1.5.*", "raven/raven" : "0.11.*", "mews/purifier" : "1.0.*", "doctrine/dbal" : "2.5.*", "bugsnag/bugsnag-laravel" : "1.*" }, "require-dev" : { "phpunit/phpunit" : "3.7.*", "mockery/mockery" : "dev-master", "way/laravel-test-helpers" : "dev-master" }, "autoload" : { "classmap" : [ "app/commands", "app/controllers", "app/models", "app/database/migrations", "app/database/seeds", "app/tests/TestCase.php" ], "psr-0" : { "LaraSnipp": "app" } }, "scripts" : { "post-install-cmd" : [ "php artisan optimize" ], "post-update-cmd" : [ "php artisan clear-compiled", "php artisan optimize" ], "post-create-project-cmd" : [ "php artisan key:generate" ] }, "config" : { "preferred-install" : "dist" }, "minimum-stability" : "stable" } ================================================ FILE: gulpfile.js ================================================ // Require plugins. var gulp = require('gulp'), gutil = require('gulp-util'), notify = require('gulp-notify'), scss = require('gulp-ruby-sass'), autoprefix = require('gulp-autoprefixer'), coffee = require('gulp-coffee'), jshint = require('gulp-jshint'); // Config var scssDir = 'public/assets/scss', // Where do you store your SCSS files? targetCSSDir = 'public/assets/css', // Which directory should SCSS compile to? coffeeDir = 'public/assets/coffee', // Where do you store your coffee files? targetJSDir = 'public/assets/js', // Which directory should CoffeeScript compile to? scss_options = { style: 'compressed', compass: true }; // Compile SCSS, autoprefix CSS, // and save to target CSS directory gulp.task('css', function () { return gulp.src(scssDir + '/**/*.scss') .pipe(scss(scss_options).on('error', gutil.log)) .pipe(autoprefix('last 10 version')) .pipe(gulp.dest(targetCSSDir)) .pipe(notify('CSS minified')) }); // Handle CoffeeScript compilation gulp.task('js', function () { return gulp.src(coffeeDir + '/**/*.coffee') .pipe(coffee().on('error', gutil.log)) .pipe(jshint()) .pipe(jshint.reporter('default')) .pipe(gulp.dest(targetJSDir)) }); // Keep an eye on Scss, Coffee, and PHP files for changes... gulp.task('watch', function () { gulp.watch(scssDir + '/**/**/*.scss', ['css']); gulp.watch(coffeeDir + '/**/*.coffee', ['js']); }); // What tasks does running gulp trigger? gulp.task('default', ['css', 'js', 'watch']); ================================================ FILE: package.json ================================================ { "devDependencies": { "gulp": "~3.5.6", "gulp-ruby-sass": "~0.4.0", "gulp-util": "~2.2.14", "gulp-coffee": "~1.4.1", "gulp-autoprefixer": "0.0.6", "gulp-notify": "~1.2.0", "gulp-jshint": "~1.5.0" } } ================================================ FILE: phpunit.xml ================================================ ./app/tests/ ./app/tests/integration ./app/tests/unit ./app/tests/functional ================================================ FILE: public/.htaccess ================================================ Options -MultiViews RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] ================================================ FILE: public/administration/css/sb-admin-2.css ================================================ /*! * Start Bootstrap - SB Admin 2 Bootstrap Admin Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ body { background-color: #f8f8f8; } #wrapper { width: 100%; } #page-wrapper { padding: 0 15px; min-height: 568px; background-color: #fff; } @media(min-width:768px) { #page-wrapper { position: inherit; margin: 0 0 0 250px; padding: 0 30px; border-left: 1px solid #e7e7e7; } } .navbar-top-links { margin-right: 0; } .navbar-top-links li { display: inline-block; } .navbar-top-links li:last-child { margin-right: 15px; } .navbar-top-links li a { padding: 15px; min-height: 50px; } .navbar-top-links .dropdown-menu li { display: block; } .navbar-top-links .dropdown-menu li:last-child { margin-right: 0; } .navbar-top-links .dropdown-menu li a { padding: 3px 20px; min-height: 0; } .navbar-top-links .dropdown-menu li a div { white-space: normal; } .navbar-top-links .dropdown-messages, .navbar-top-links .dropdown-tasks, .navbar-top-links .dropdown-alerts { width: 310px; min-width: 0; } .navbar-top-links .dropdown-messages { margin-left: 5px; } .navbar-top-links .dropdown-tasks { margin-left: -59px; } .navbar-top-links .dropdown-alerts { margin-left: -123px; } .navbar-top-links .dropdown-user { right: 0; left: auto; } .sidebar .sidebar-nav.navbar-collapse { padding-right: 0; padding-left: 0; } .sidebar .sidebar-search { padding: 15px; } .sidebar ul li { border-bottom: 1px solid #e7e7e7; } .sidebar ul li a.active { background-color: #eee; } .sidebar .arrow { float: right; } .sidebar .fa.arrow:before { content: "\f104"; } .sidebar .active>a>.fa.arrow:before { content: "\f107"; } .sidebar .nav-second-level li, .sidebar .nav-third-level li { border-bottom: 0!important; } .sidebar .nav-second-level li a { padding-left: 37px; } .sidebar .nav-third-level li a { padding-left: 52px; } @media(min-width:768px) { .sidebar { z-index: 1; position: absolute; width: 250px; margin-top: 51px; } .navbar-top-links .dropdown-messages, .navbar-top-links .dropdown-tasks, .navbar-top-links .dropdown-alerts { margin-left: auto; } } .btn-outline { color: inherit; background-color: transparent; transition: all .5s; } .btn-primary.btn-outline { color: #428bca; } .btn-success.btn-outline { color: #5cb85c; } .btn-info.btn-outline { color: #5bc0de; } .btn-warning.btn-outline { color: #f0ad4e; } .btn-danger.btn-outline { color: #d9534f; } .btn-primary.btn-outline:hover, .btn-success.btn-outline:hover, .btn-info.btn-outline:hover, .btn-warning.btn-outline:hover, .btn-danger.btn-outline:hover { color: #fff; } .chat { margin: 0; padding: 0; list-style: none; } .chat li { margin-bottom: 10px; padding-bottom: 5px; border-bottom: 1px dotted #999; } .chat li.left .chat-body { margin-left: 60px; } .chat li.right .chat-body { margin-right: 60px; } .chat li .chat-body p { margin: 0; } .panel .slidedown .glyphicon, .chat .glyphicon { margin-right: 5px; } .chat-panel .panel-body { height: 350px; overflow-y: scroll; } .login-panel { margin-top: 25%; } .flot-chart { display: block; height: 400px; } .flot-chart-content { width: 100%; height: 100%; } .dataTables_wrapper { position: relative; clear: both; } table.dataTable thead .sorting, table.dataTable thead .sorting_asc, table.dataTable thead .sorting_desc, table.dataTable thead .sorting_asc_disabled, table.dataTable thead .sorting_desc_disabled { background: 0 0; } table.dataTable thead .sorting_asc:after { content: "\f0de"; float: right; font-family: fontawesome; } table.dataTable thead .sorting_desc:after { content: "\f0dd"; float: right; font-family: fontawesome; } table.dataTable thead .sorting:after { content: "\f0dc"; float: right; font-family: fontawesome; color: rgba(50,50,50,.5); } .btn-circle { width: 30px; height: 30px; padding: 6px 0; border-radius: 15px; text-align: center; font-size: 12px; line-height: 1.428571429; } .btn-circle.btn-lg { width: 50px; height: 50px; padding: 10px 16px; border-radius: 25px; font-size: 18px; line-height: 1.33; } .btn-circle.btn-xl { width: 70px; height: 70px; padding: 10px 16px; border-radius: 35px; font-size: 24px; line-height: 1.33; } .show-grid [class^=col-] { padding-top: 10px; padding-bottom: 10px; border: 1px solid #ddd; background-color: #eee!important; } .show-grid { margin: 15px 0; } .huge { font-size: 40px; } .panel-green { border-color: #5cb85c; } .panel-green .panel-heading { border-color: #5cb85c; color: #fff; background-color: #5cb85c; } .panel-green a { color: #5cb85c; } .panel-green a:hover { color: #3d8b3d; } .panel-red { border-color: #d9534f; } .panel-red .panel-heading { border-color: #d9534f; color: #fff; background-color: #d9534f; } .panel-red a { color: #d9534f; } .panel-red a:hover { color: #b52b27; } .panel-yellow { border-color: #f0ad4e; } .panel-yellow .panel-heading { border-color: #f0ad4e; color: #fff; background-color: #f0ad4e; } .panel-yellow a { color: #f0ad4e; } .panel-yellow a:hover { color: #df8a13; } ================================================ FILE: public/administration/css/timeline.css ================================================ .timeline { position: relative; padding: 20px 0 20px; list-style: none; } .timeline:before { content: " "; position: absolute; top: 0; bottom: 0; left: 50%; width: 3px; margin-left: -1.5px; background-color: #eeeeee; } .timeline > li { position: relative; margin-bottom: 20px; } .timeline > li:before, .timeline > li:after { content: " "; display: table; } .timeline > li:after { clear: both; } .timeline > li:before, .timeline > li:after { content: " "; display: table; } .timeline > li:after { clear: both; } .timeline > li > .timeline-panel { float: left; position: relative; width: 46%; padding: 20px; border: 1px solid #d4d4d4; border-radius: 2px; -webkit-box-shadow: 0 1px 6px rgba(0,0,0,0.175); box-shadow: 0 1px 6px rgba(0,0,0,0.175); } .timeline > li > .timeline-panel:before { content: " "; display: inline-block; position: absolute; top: 26px; right: -15px; border-top: 15px solid transparent; border-right: 0 solid #ccc; border-bottom: 15px solid transparent; border-left: 15px solid #ccc; } .timeline > li > .timeline-panel:after { content: " "; display: inline-block; position: absolute; top: 27px; right: -14px; border-top: 14px solid transparent; border-right: 0 solid #fff; border-bottom: 14px solid transparent; border-left: 14px solid #fff; } .timeline > li > .timeline-badge { z-index: 100; position: absolute; top: 16px; left: 50%; width: 50px; height: 50px; margin-left: -25px; border-radius: 50% 50% 50% 50%; text-align: center; font-size: 1.4em; line-height: 50px; color: #fff; background-color: #999999; } .timeline > li.timeline-inverted > .timeline-panel { float: right; } .timeline > li.timeline-inverted > .timeline-panel:before { right: auto; left: -15px; border-right-width: 15px; border-left-width: 0; } .timeline > li.timeline-inverted > .timeline-panel:after { right: auto; left: -14px; border-right-width: 14px; border-left-width: 0; } .timeline-badge.primary { background-color: #2e6da4 !important; } .timeline-badge.success { background-color: #3f903f !important; } .timeline-badge.warning { background-color: #f0ad4e !important; } .timeline-badge.danger { background-color: #d9534f !important; } .timeline-badge.info { background-color: #5bc0de !important; } .timeline-title { margin-top: 0; color: inherit; } .timeline-body > p, .timeline-body > ul { margin-bottom: 0; } .timeline-body > p + p { margin-top: 5px; } @media(max-width:767px) { ul.timeline:before { left: 40px; } ul.timeline > li > .timeline-panel { width: calc(100% - 90px); width: -moz-calc(100% - 90px); width: -webkit-calc(100% - 90px); } ul.timeline > li > .timeline-badge { top: 16px; left: 15px; margin-left: 0; } ul.timeline > li > .timeline-panel { float: right; } ul.timeline > li > .timeline-panel:before { right: auto; left: -15px; border-right-width: 15px; border-left-width: 0; } ul.timeline > li > .timeline-panel:after { right: auto; left: -14px; border-right-width: 14px; border-left-width: 0; } } ================================================ FILE: public/administration/js/sb-admin-2.js ================================================ $(function() { $('#side-menu').metisMenu(); }); //Loads the correct sidebar on window load, //collapses the sidebar on window resize. // Sets the min-height of #page-wrapper to window size $(function() { $(window).bind("load resize", function() { topOffset = 50; width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width; if (width < 768) { $('div.navbar-collapse').addClass('collapse'); topOffset = 100; // 2-row-menu } else { $('div.navbar-collapse').removeClass('collapse'); } height = ((this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height) - 1; height = height - topOffset; if (height < 1) height = 1; if (height > topOffset) { $("#page-wrapper").css("min-height", (height) + "px"); } }); var url = window.location; var element = $('ul.nav a').filter(function() { return this.href == url || url.href.indexOf(this.href) == 0; }).addClass('active').parent().parent().addClass('in').parent(); if (element.is('li')) { element.addClass('active'); } }); ================================================ FILE: public/assets/coffee/common.coffee ================================================ root = (exports ? window) root.LaraSnipp = {} ================================================ FILE: public/assets/coffee/snippet.coffee ================================================ $ -> "use strict" if $('.js-submit-snippet-form').length > 0 editor = CodeMirror.fromTextArea(document.getElementById("code"), mode: "text/x-php" theme: "monokai" lineNumbers: true matchBrackets: true indentUnit: 4 indentWithTabs: true enterMode: "keep" tabMode: "shift" ) if $('.js-prettyprint').length > 0 $(window).load -> prettyPrint() if $('.js-submit-snippet-form').length > 0 $('select').chosen no_results_text: "Oops, nothing found!" ================================================ FILE: public/assets/css/styles.css ================================================ *{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box;-webkit-font-smoothing:antialiased;text-rendering:optimizelegibility}html{overflow-x:hidden;background-color:#333}body{color:#656565;font-family:"Source Sans Pro",sans-serif;font-size:14px;line-height:1.5em}h1,h2,h3,h4,h5,h6,ul,ol,dl,p,address,figure,pre,fieldset,table{margin-bottom:20px}code{background-color:#f7f7f7;color:#6d9fbf}strong{font-weight:600}::-moz-selection{background-color:rgba(0,0,0,0.3);color:#FFF}::selection{background-color:rgba(0,0,0,0.3);color:#FFF}a{-webkit-transition:all 0.25s;-o-transition:all 0.25s;transition:all 0.25s;color:#6d9fbf;text-decoration:none}a:hover{color:#4c87ad;text-decoration:none}h1,h2,h3,h4,h5,h6{color:#6e6e6e;font-family:"Source Sans Pro",Arial,Helvetica,sans-serif;font-weight:300;line-height:1.3em;margin-top:0}h1,.h1{font-size:36px}h2,.h2{font-size:30px}h3,.h3{font-size:24px}h4,.h4{font-size:20px}h5,.h5{font-size:16px}h6,.h6{font-size:14px}.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;content:"";line-height:0}.clearfix:after{clear:both}.textleft{text-align:left}.textright{text-align:right}.textcenter{text-align:center}.alignnone{margin:4px 0 20px 0}.alignleft{float:left;margin:4px 20px 20px 0}.alignright{float:right;margin:4px 0 20px 20px}.aligncenter{display:block;margin:4px auto 20px auto}.hidden{display:none;visibility:hidden}.hide-text{font:0/0 a;text-shadow:none;color:transparent}.widget{margin-bottom:30px;clear:both}hr{height:0;max-height:0;background:none;border:none;border-top:2px solid rgba(0,0,0,0.05);margin:30px 0;clear:both}.notice{-webkit-border-radius:5px;border-radius:5px;margin-bottom:20px;padding:10px;border-width:2px;border-style:solid;background:#f2f2f2;color:#8c8c8c;border-color:#d8d8d8}.notice.error{background:#f5dbda;color:#ca3f39;border-color:#eab4b2}.notice.success{background:#d9f098;color:#7fa418;border-color:#c9ea6b}.notice.warning{background:#fdefbe;color:#e8b607;border-color:#fbe38d}.table{width:100%}.table td,.table th{border-bottom:1px solid #F2F2F2;padding:10px;text-align:left}.table th{font-weight:700;color:#6e6e6e}.table thead td,.table thead th{border-bottom:3px solid #F2F2F2}.table tbody>tr>td{background-color:#FFF;padding:15px}.table tbody>tr:nth-child(odd)>td{background-color:#FCFCFC}.band{*zoom:1;padding:20px 0 0}.band:before,.band:after{display:table;content:"";line-height:0}.band:after{clear:both}@media only screen and (min-width: 768px){.band{padding:45px 0 25px}}.band.band-alt{background-color:#FAFAFA}.navbar{-webkit-box-shadow:0 2px 0 rgba(0,0,0,0.1);box-shadow:0 2px 0 rgba(0,0,0,0.1);background-color:#FFF;border:none;font-size:15px;margin:0;padding:25px 0}.navbar-default .navbar-nav>li.active a{color:#6d9fbf}.navbar-default .navbar-nav>li>a{color:#AAAAAA;display:block;font-weight:600;height:50px}.navbar-default .navbar-nav>li>a:hover{color:#666}.navbar-default .navbar-nav>li>a.btn{-webkit-border-radius:5px;border-radius:5px;background-clip:padding-box;background-color:#6d9fbf;border:none;color:#FFF;margin:0 15px}@media only screen and (min-width: 768px){.navbar-default .navbar-nav>li>a.btn{margin-left:15px}}.navbar-default .navbar-nav>li>a.btn:hover{background-color:#4c87ad}.navbar-brand{padding:5px 0 0 15px}.search-band{-webkit-box-shadow:0 2px 0 rgba(0,0,0,0.1);box-shadow:0 2px 0 rgba(0,0,0,0.1);background-color:#6d9fbf;color:#39515F;font-size:14px;padding:45px 0}.search-band.narrow{height:5px;padding:0}.search-band h1{color:#fff;font-size:27px}.search-band p{margin:0}.search-band a{color:#FFF}.search-band .btn{background-color:#577D97;color:#FFF}.breadcrumbs{font-size:13px;margin:45px 0 15px}.breadcrumbs .fa-chevron-right{color:#BABABA;font-size:10px;margin:0 10px}.pagination-container{text-align:center}.pagination>li>a,.pagination>li>span{border:none;color:#6d9fbf;font-size:18px}.pagination>li.active span,.pagination>li:hover a,.pagination>li:hover span{background-color:#FFF}.pagination>li.active span{color:#434343}#sidebar .sidebar-widget{margin-bottom:30px}#sidebar .widget-categories ul{border-top:1px solid #F5F5F5;list-style:none;margin:0;padding:0}#sidebar .widget-categories ul li{border-bottom:1px solid #F5F5F5}#sidebar .widget-categories ul a{display:block;padding:5px 0}#sidebar .widget-contributors ul{list-style:none;margin:0;padding:0}#sidebar .widget-contributors ul li{padding:0 30px 0 0;position:relative}#sidebar .widget-contributors ul li .snippet-count{position:absolute;right:0;text-align:center;top:0;width:20px}#sidebar .widget-author{background-color:#FCFCFC;font-size:13px;padding:30px 30px 20px}#sidebar .widget-author hr{border-top:1px solid #EDEDED;margin:20px 0}#sidebar .widget-author .widget-author-avatar{-webkit-border-radius:5px;border-radius:5px;float:left;margin:5px 15px 5px 0}#sidebar .widget-author .widget-author-stats{list-style:none;margin:0;padding:0}#sidebar .widget-author .widget-author-stats li{font-weight:600;padding:0 30px 0 0;position:relative}#sidebar .widget-author .widget-author-stats li a,#sidebar .widget-author .widget-author-stats li span{font-weight:normal;position:absolute;right:0;text-align:center;top:0;width:20px}#sidebar .widget-social-icons{*zoom:1;list-style:none;margin:0;padding:0}#sidebar .widget-social-icons:before,#sidebar .widget-social-icons:after{display:table;content:"";line-height:0}#sidebar .widget-social-icons:after{clear:both}#sidebar .widget-social-icons li{float:left;margin:0 10px 10px 0}#sidebar .widget-social-icons a{background-image:url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4gPHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJncmFkIiBncmFkaWVudFVuaXRzPSJvYmplY3RCb3VuZGluZ0JveCIgeDE9IjAuNSIgeTE9IjEuMCIgeDI9IjAuNSIgeTI9IjAuMCI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2ZmZmZmZiIgc3RvcC1vcGFjaXR5PSIwLjAiLz48c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNmZmZmZmYiIHN0b3Atb3BhY2l0eT0iMC4zIi8+PC9saW5lYXJHcmFkaWVudD48L2RlZnM+PHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0idXJsKCNncmFkKSIgLz48L3N2Zz4g');background-size:100%;background-image:-webkit-linear-gradient(bottom, rgba(255,255,255,0) 0%,rgba(255,255,255,0.3) 100%);background-image:-webkit-gradient(linear, left bottom, left top, from(rgba(255,255,255,0)), to(rgba(255,255,255,0.3)));background-image:-webkit-linear-gradient(bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.3) 100%);background-image:-o-linear-gradient(bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.3) 100%);background-image:linear-gradient(to top, rgba(255,255,255,0) 0%,rgba(255,255,255,0.3) 100%);-webkit-border-radius:32px;border-radius:32px;-webkit-box-shadow:inset 0 -1px 1px rgba(0,0,1,0.3),inset 0 0 0 1px rgba(0,0,0,0.06);box-shadow:inset 0 -1px 1px rgba(0,0,1,0.3),inset 0 0 0 1px rgba(0,0,0,0.06);background-color:#6d9fbf;color:#FFF;display:block;font-size:16px;height:32px;line-height:32px;text-align:center;width:32px}#sidebar .widget-social-icons a i{text-shadow:0 1px 2px rgba(0,0,1,0.2)}#sidebar .widget-social-icons a:hover{background-image:url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4gPHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJncmFkIiBncmFkaWVudFVuaXRzPSJvYmplY3RCb3VuZGluZ0JveCIgeDE9IjAuNSIgeTE9IjEuMCIgeDI9IjAuNSIgeTI9IjAuMCI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2ZmZmZmZiIgc3RvcC1vcGFjaXR5PSIwLjAiLz48c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNmZmZmZmYiIHN0b3Atb3BhY2l0eT0iMC4xIi8+PC9saW5lYXJHcmFkaWVudD48L2RlZnM+PHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0idXJsKCNncmFkKSIgLz48L3N2Zz4g');background-size:100%;background-image:-webkit-linear-gradient(bottom, rgba(255,255,255,0) 0%,rgba(255,255,255,0.1) 100%);background-image:-webkit-gradient(linear, left bottom, left top, from(rgba(255,255,255,0)), to(rgba(255,255,255,0.1)));background-image:-webkit-linear-gradient(bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.1) 100%);background-image:-o-linear-gradient(bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.1) 100%);background-image:linear-gradient(to top, rgba(255,255,255,0) 0%,rgba(255,255,255,0.1) 100%)}#sidebar .widget-social-icons a.behance:hover{background-color:#1769FF}#sidebar .widget-social-icons a.deviantart:hover{background-color:#B3C432}#sidebar .widget-social-icons a.dribbble:hover{background-color:#ea4c89}#sidebar .widget-social-icons a.facebook:hover{background-color:#3664A2}#sidebar .widget-social-icons a.flickr:hover{background-color:#ff0084}#sidebar .widget-social-icons a.github:hover{background-color:#444444}#sidebar .widget-social-icons a.googleplus:hover{background-color:#dd4b39}#sidebar .widget-social-icons a.instagram:hover{background-color:#3f729b}#sidebar .widget-social-icons a.lastfm:hover{background-color:#D51007}#sidebar .widget-social-icons a.linkedin:hover{background-color:#007bb6}#sidebar .widget-social-icons a.pinterest:hover{background-color:#cb2027}#sidebar .widget-social-icons a.rss:hover{background-color:#FB9E3A}#sidebar .widget-social-icons a.soundcloud:hover{background-color:#ff6600}#sidebar .widget-social-icons a.tumblr:hover{background-color:#2c4762}#sidebar .widget-social-icons a.twitter:hover{background-color:#00aced}#sidebar .widget-social-icons a.vimeo:hover{background-color:#44bbff}#sidebar .widget-social-icons a.vk:hover{background-color:#4E729A}#sidebar .widget-social-icons a.yelp:hover{background-color:#C41200}#sidebar .widget-social-icons a.youtube:hover{background-color:#cc181e}.contribute-band{background-color:#fbfbfb;border-top:2px solid #E2E2E2;color:#656565;font-size:30px;line-height:1.3;padding:45px 0;overflow:hidden;position:relative;text-align:center}.contribute-band:after{color:#EFEFEF;content:"\f09b";font-family:"FontAwesome";font-size:192px;height:176px;left:50%;line-height:176px;margin:-88px 0 0 -88px;position:absolute;top:50%;width:176px;z-index:0}.contribute-band p{margin:0;position:relative;z-index:1}.contribute-band a:after{content:"\f09b";font-family:"FontAwesome";margin-left:5px}.footer{background-color:#333;color:#c4c4c4;font-size:14px;padding:20px 0;text-align:center}.footer a{color:#c4c4c4;font-weight:bold}.footer a:hover{color:#FFF}.footer .digitalocean{margin-bottom:25px}.footer .digitalocean a{display:block}.footer .digitalocean img{max-width:140px}.footer-links{margin:0 auto 20px}.footer-copyright{font-size:12px;margin:0}.snippets-table th,.snippets-table td{text-align:center}.snippets-table th.textleft,.snippets-table td.textleft{text-align:left}body.single-snippet h1{margin:0 0 10px}@media only screen and (min-width: 768px){body.single-snippet h1{margin:0}}@media only screen and (min-width: 768px){body.single-snippet .snippet-stats{float:right}}body.single-snippet .snippet-stats .snippet-stats-views,body.single-snippet .snippet-stats .snippet-stats-stars{float:left;font-size:13px;line-height:32px;margin:7px 0 0 15px}body.single-snippet .snippet-stats .snippet-stats-views{color:#999}body.single-snippet .snippet-stats .snippet-stats-stars .btn{color:#F4AC5F;font-size:13px}body.single-snippet .snippet-stats .snippet-stats-stars .btn:hover{background-color:#FCFCFC}body.single-snippet .snippet-stats .snippet-stats-stars .btn-default{border-color:#F2F2F2}body.single-snippet .snippet-stats .snippet-stats-stars-count{color:#656565 !important;font-weight:600}body.single-snippet .snippet-stats .snippet-stats-stars-count:hover{background-color:#FFF;border-color:#F2F2F2;cursor:default}body.single-snippet .snippet-stats .snippet-stats-stars-active .btn-default{color:#656565}body.single-snippet .snippet-description{margin-bottom:45px}body.single-snippet pre{background-color:#333;border:0;border-bottom:1px solid #eee;border-top:1px solid #eee;color:#e9e4e5;font-family:Monaco, Consolas, "Lucida Console", monospace;font-size:12px;line-height:1.9em;margin:0 0 45px;padding:4px 0 2px}body.single-snippet pre .pln{color:#e9e4e5}body.single-snippet pre .str{color:#bcd42a}body.single-snippet pre .kwd{color:#4bb1b1}body.single-snippet pre .com{color:#888888}body.single-snippet pre .typ{color:#ef7c61}body.single-snippet pre .lit{color:#bcd42a}body.single-snippet pre .pun,body.single-snippet pre .opn,body.single-snippet pre .clo{color:#ffffff}body.single-snippet pre .tag{color:#4bb1b1}body.single-snippet pre .atn{color:#ef7c61}body.single-snippet pre .atv{color:#bcd42a}body.single-snippet pre .dec,body.single-snippet pre .var{color:#660066}body.single-snippet pre .fun{color:#ff0000}body.single-snippet pre code{font-family:Monaco, Consolas, "Lucida Console", monospace}body.single-snippet li.L1,body.single-snippet li.L3,body.single-snippet li.L5,body.single-snippet li.L7,body.single-snippet li.L9{background-color:inherit}body.single-snippet li.L0,body.single-snippet li.L1,body.single-snippet li.L2,body.single-snippet li.L3,body.single-snippet li.L5,body.single-snippet li.L6,body.single-snippet li.L7,body.single-snippet li.L8{list-style-type:decimal}body.single-snippet .snippet-share-links{margin-bottom:20px}body.single-snippet .snippet-categories ul{margin-bottom:20px}body.single-snippet .disqus{margin-bottom:20px}body.profiles .profile{margin-bottom:30px}.stButton .stFb,.stButton .stTwbutton,.stButton .stMainServices,.stButton .stButton_gradient{height:22px !important}.btn-info{background-color:#6d9fbf;border-color:#6d9fbf}.btn-info:hover{background-color:#4c87ad;border-color:#4c87ad} ================================================ FILE: public/assets/js/common.js ================================================ (function() { var root; root = typeof exports !== "undefined" && exports !== null ? exports : window; root.LaraSnipp = {}; }).call(this); ================================================ FILE: public/assets/js/snippet.js ================================================ (function() { $(function() { "use strict"; var editor; if ($('.js-submit-snippet-form').length > 0) { editor = CodeMirror.fromTextArea(document.getElementById("code"), { mode: "text/x-php", theme: "monokai", lineNumbers: true, matchBrackets: true, indentUnit: 4, indentWithTabs: true, enterMode: "keep", tabMode: "shift" }); } if ($('.js-prettyprint').length > 0) { $(window).load(function() { return prettyPrint(); }); } if ($('.js-submit-snippet-form').length > 0) { return $('select').chosen({ no_results_text: "Oops, nothing found!" }); } }); }).call(this); ================================================ FILE: public/assets/js/vendors/json2/json2.js ================================================ /* json2.js 2013-05-26 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or ' '), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (typeof JSON !== 'object') { JSON = {}; } (function () { 'use strict'; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function () { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function () { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); ================================================ FILE: public/assets/scss/core/_band.scss ================================================ .band { @include clearfix; padding: 20px 0 0; @include min-screen-width(tablet-portrait) { padding: 45px 0 25px; } &.band-alt { background-color: #FAFAFA; } } ================================================ FILE: public/assets/scss/core/_global.scss ================================================ /**************************************************** * Global Tags ****************************************************/ * { @include box-sizing( border-box ); -webkit-font-smoothing: antialiased; text-rendering: optimizelegibility; } html { overflow-x: hidden; background-color: #333; } body { color: $site-text-colour; font: { family: $copy-font, sans-serif; size: $site-text-size; } line-height: $global-line-height; } h1, h2, h3, h4, h5, h6, ul, ol, dl, p, address, figure, pre, fieldset, table { margin-bottom: $margin; } code { background-color: darken( #FCFCFC, 2% ); color: $accent; } strong { font-weight: 600; } ::selection { background-color: rgba( 0, 0, 0, .3 ); color: #FFF; } /**************************************************** * Anchors ****************************************************/ a { @include transition( all .25s ); color: $accent; text-decoration: none; &:hover { color: darken( $accent, 10% ); text-decoration: none; } } /**************************************************** * Headings ****************************************************/ h1, h2, h3, h4, h5, h6 { color: #6e6e6e; font: { family: $detail-font, Arial, Helvetica, sans-serif; weight: 300; } line-height: 1.3em; margin-top: 0; } h1, .h1 { font-size: 36px; } h2, .h2 { font-size: 30px; } h3, .h3 { font-size: 24px; } h4, .h4 { font-size: 20px; } h5, .h5 { font-size: 16px; } h6, .h6 { font-size: 14px; } /**************************************************** * Global Classes ****************************************************/ .clearfix { @include clearfix; } .textleft { text-align: left; } .textright { text-align: right; } .textcenter { text-align: center; } .alignnone { margin: 4px 0 $margin 0; } .alignleft { float: left; margin: 4px $margin $margin 0; } .alignright { float: right; margin: 4px 0 $margin $margin; } .aligncenter { display: block; margin: 4px auto $margin auto; } .hidden { display: none; visibility: hidden; } .hide-text { @include hide-text; } .widget { margin-bottom: $gutter; clear: both; } /**************************************************** * Horizontal Rules ****************************************************/ hr { height: 0; max-height: 0; background: none; border: none; border-top: 2px solid rgba( black, .05 ); margin: $gutter 0; clear: both; } /**************************************************** * Notices ****************************************************/ $notice-default-swatch: #F2F2F2; $notice-error-swatch: #F5DBDA; $notice-success-swatch: #D9F098; $notice-warning-swatch: #FDEFBE; .notice { @include border-radius(5px); margin-bottom: $margin; padding: 10px; border-width: 2px; border-style: solid; background: $notice-default-swatch; color: darken( $notice-default-swatch, 40% ); border-color: darken( $notice-default-swatch, 10% ); &.error { background: $notice-error-swatch; color: darken( $notice-error-swatch, 40% ); border-color: darken( $notice-error-swatch, 10% ); } &.success { background: $notice-success-swatch; color: darken($notice-success-swatch, 40%); border-color: darken($notice-success-swatch, 10% ); } &.warning { background: $notice-warning-swatch; color: darken( $notice-warning-swatch, 40% ); border-color: darken( $notice-warning-swatch, 10% ); } } /**************************************************** * Tables ****************************************************/ .table { width: 100%; td, th { border-bottom: 1px solid #F2F2F2; padding: 10px; text-align: left; } th { font-weight: 700; color: #6e6e6e; } thead td, thead th { border-bottom: 3px solid #F2F2F2; } tbody > tr { > td { background-color: #FFF; padding: 15px; } &:nth-child(odd) > td { background-color: #FCFCFC; } } } ================================================ FILE: public/assets/scss/core/_mixins.scss ================================================ @mixin min-screen-width( $media ) { @if $media == mobile-landscape { @media only screen and (min-width:480px) { @content; } } @else if $media == tablet-portrait { @media only screen and (min-width:768px) { @content; } } @else if $media == tablet-landscape { @media only screen and (min-width:1024px) { @content; } } @else if $media == large-desktop { @media only screen and (min-width:1200px) { @content; } } } @mixin clearfix { *zoom: 1; &:before, &:after { display: table; content: ""; line-height: 0; } &:after { clear: both; } } @mixin hide-text { font: 0/0 a; text-shadow: none; color: transparent; } @mixin inline-block { display: inline-block; vertical-align: baseline; zoom: 1; *display: inline; *vertical-align: auto; } @mixin iconify( $width, $height: $width, $radius: 0 ) { @if $radius != 0 { @include border-radius( $radius ) } display: block; text-align: center; width: $width; line-height: $height; min-height: 0; } ================================================ FILE: public/assets/scss/core/_variables.scss ================================================ $gutter: 30px; $margin: 20px; $accent: #6D9FBF; $site-text-colour: #656565; $copy-font: 'Source Sans Pro'; $detail-font: 'Source Sans Pro'; $site-text-size: 14px; $global-line-height: 1.5em; ================================================ FILE: public/assets/scss/pages/_profiles.scss ================================================ body.profiles { .profile { margin-bottom: 30px; } } ================================================ FILE: public/assets/scss/pages/_snippet.scss ================================================ body.single-snippet { h1 { margin: 0 0 10px; @include min-screen-width(tablet-portrait) { margin: 0; } } .snippet-stats { @include min-screen-width(tablet-portrait) { float: right; } .snippet-stats-views, .snippet-stats-stars { float: left; font-size: 13px; line-height: 32px; margin: 7px 0 0 15px; } .snippet-stats-views { color: #999; } .snippet-stats-stars { .btn { color: #F4AC5F; font-size: 13px; &:hover { background-color: #FCFCFC; } } .btn-default { border-color: #F2F2F2; } } .snippet-stats-stars-count { color: #656565 !important; font-weight: 600; &:hover { background-color: #FFF; border-color: #F2F2F2; cursor: default; } } .snippet-stats-stars-active .btn-default { color: #656565; } } .snippet-description { margin-bottom: 45px; } /* Laravel syntax highlighting */ pre { background-color: #333; border: 0; border: { bottom: 1px solid #eee; top: 1px solid #eee; } color: #e9e4e5; font: { family: Monaco, Consolas, "Lucida Console", monospace; size: 12px; } line-height: 1.9em; margin: 0 0 45px; padding: 4px 0 2px; .pln { color: #e9e4e5; } .str { color: #bcd42a; } .kwd { color: #4bb1b1; } .com { color: #888888; } .typ { color: #ef7c61; } .lit { color: #bcd42a; } .pun, .opn, .clo { color: #ffffff; } .tag { color: #4bb1b1; } .atn { color: #ef7c61; } .atv { color: #bcd42a; } .dec, .var { color: #660066; } .fun { color: #ff0000; } code { font-family: Monaco, Consolas, "Lucida Console", monospace; } } /* Prettify CSS Overrides */ li.L1, li.L3, li.L5, li.L7, li.L9 { background-color: inherit; // force inherit background color } li.L0, li.L1, li.L2, li.L3, li.L5, li.L6, li.L7, li.L8 { list-style-type: decimal; // show all line numbers } .snippet-share-links { margin-bottom: 20px; } .snippet-categories ul { margin-bottom: 20px; } .disqus { margin-bottom: 20px; } } ================================================ FILE: public/assets/scss/partials/_breadcrumbs.scss ================================================ .breadcrumbs { font-size: 13px; margin: 45px 0 15px; .fa-chevron-right { color: #BABABA; font-size: 10px; margin: 0 10px; } } ================================================ FILE: public/assets/scss/partials/_footer.scss ================================================ .contribute-band { background-color: #fbfbfb; border-top: 2px solid #E2E2E2; color: #656565; font-size: 30px; line-height: 1.3; padding: 45px 0; overflow: hidden; position: relative; text-align: center; &:after { color: #EFEFEF; content: "\f09b"; font: { family: "FontAwesome"; size: 192px; } height: 176px; left: 50%; line-height: 176px; margin: -88px 0 0 -88px; position: absolute; top: 50%; width: 176px; z-index: 0; } p { margin: 0; position: relative; z-index: 1; } a:after { content: "\f09b"; font-family: "FontAwesome"; margin-left: 5px; } } .footer { background-color: #333; color: #c4c4c4; font-size: 14px; padding: 20px 0; text-align: center; a { color: #c4c4c4; font-weight: bold; &:hover { color: #FFF; } } .digitalocean { margin-bottom: 25px; a { display: block; } img { max-width: 140px; } } } .footer-links { margin: 0 auto 20px; } .footer-copyright { font-size: 12px; margin: 0; } ================================================ FILE: public/assets/scss/partials/_nav-bar.scss ================================================ .navbar { @include box-shadow(0 2px 0 rgba(0,0,0,.1)); background-color: #FFF; border: none; font-size: 15px; margin: 0; padding: 25px 0; } .navbar-default .navbar-nav > li { &.active a { color: $accent; } > a { color: #AAAAAA; display: block; font-weight: 600; height: 50px; &:hover { color: #666; } &.btn { @include border-radius(5px); @include background-clip(padding-box); background-color: $accent; border: none; color: #FFF; margin: 0 15px; @include min-screen-width(tablet-portrait) { margin-left: 15px; } &:hover { background-color: darken( $accent, 10% ); } } } } .navbar-brand { padding: 5px 0 0 15px; } ================================================ FILE: public/assets/scss/partials/_pagination.scss ================================================ .pagination-container { text-align: center; } .pagination { > li { > a, > span { border: none; color: #6d9fbf; font-size: 18px; } &.active span, &:hover a, &:hover span { background-color: #FFF; } &.active span { color: #434343; } } } ================================================ FILE: public/assets/scss/partials/_search-band.scss ================================================ .search-band { @include box-shadow(0 2px 0 rgba(0,0,0,.1)); background-color: #6d9fbf; color: #39515F; font-size: 14px; padding: 45px 0; &.narrow { height: 5px; padding: 0; } h1 { color: #fff; font-size: 27px; } p { margin: 0; } a { color: #FFF; } .btn { background-color: #577D97; color: #FFF; } } ================================================ FILE: public/assets/scss/partials/_sidebar.scss ================================================ #sidebar { .sidebar-widget { margin-bottom: 30px; } .widget-categories ul { border-top: 1px solid #F5F5F5; list-style: none; margin: 0; padding: 0; li { border-bottom: 1px solid #F5F5F5; } a { display: block; padding: 5px 0; } } .widget-contributors ul { list-style: none; margin: 0; padding: 0; li { padding: 0 30px 0 0; position: relative; .snippet-count { position: absolute; right: 0; text-align: center; top: 0; width: 20px; } } } .widget-author { background-color: #FCFCFC; font-size: 13px; padding: 30px 30px 20px; hr { border-top: 1px solid #EDEDED; margin: 20px 0; } .widget-author-avatar { @include border-radius(5px); float: left; margin: 5px 15px 5px 0; } .widget-author-stats { list-style: none; margin: 0; padding: 0; li { font-weight: 600; padding: 0 30px 0 0; position: relative; a, span { font-weight: normal; position: absolute; right: 0; text-align: center; top: 0; width: 20px; } } } } .widget-social-icons { @include clearfix; list-style: none; margin: 0; padding: 0; li { float: left; margin: 0 10px 10px 0; } a { @include background-image(linear-gradient(bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,.3) 100%)); @include border-radius(32px); @include box-shadow(inset 0 -1px 1px rgba(0,0,1,.3), inset 0 0 0 1px rgba(0,0,0,.06)); background-color: $accent; color: #FFF; display: block; font-size: 16px; height: 32px; line-height: 32px; text-align: center; width: 32px; i { @include text-shadow(0 1px 2px rgba(0,0,1,.2)); } &:hover { @include background-image(linear-gradient(bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,.1) 100%)); } &.behance:hover { background-color: #1769FF; } &.deviantart:hover { background-color: #B3C432; } &.dribbble:hover { background-color: #ea4c89; } &.facebook:hover { background-color: #3664A2; } &.flickr:hover { background-color: #ff0084; } &.github:hover { background-color: #444444; } &.googleplus:hover { background-color: #dd4b39; } &.instagram:hover { background-color: #3f729b; } &.lastfm:hover { background-color: #D51007; } &.linkedin:hover { background-color: #007bb6; } &.pinterest:hover { background-color: #cb2027; } &.rss:hover { background-color: #FB9E3A; } &.soundcloud:hover { background-color: #ff6600; } &.tumblr:hover { background-color: #2c4762; } &.twitter:hover { background-color: #00aced; } &.vimeo:hover { background-color: #44bbff; } &.vk:hover { background-color: #4E729A; } &.yelp:hover { background-color: #C41200; } &.youtube:hover { background-color: #cc181e; } } } } ================================================ FILE: public/assets/scss/partials/_snippets.scss ================================================ .snippets-table { th, td { text-align: center; &.textleft { text-align: left; } } } ================================================ FILE: public/assets/scss/styles.scss ================================================ @charset "utf-8"; @import "compass/css3"; // Setup @import "core/variables"; @import "core/mixins"; // Core @import "core/global"; @import "core/band"; // Partials @import "partials/nav-bar"; @import "partials/search-band"; @import "partials/breadcrumbs"; @import "partials/pagination"; @import "partials/sidebar"; @import "partials/footer"; @import "partials/snippets"; // Pages @import "pages/snippet"; @import "pages/profiles"; // Snippet Share button overrides (Will be removed later when share buttons are replaced) ^davidnknight .stButton .stFb, .stButton .stTwbutton, .stButton .stMainServices, .stButton .stButton_gradient { height: 22px !important; } // Will spend more time on buttons at some point ^davidnknight .btn-info { background-color: $accent; border-color: $accent; &:hover { background-color: darken( $accent, 10% ); border-color: darken( $accent, 10% ); } } ================================================ FILE: public/index.php ================================================ */ /* |-------------------------------------------------------------------------- | Register The Auto Loader |-------------------------------------------------------------------------- | | Composer provides a convenient, automatically generated class loader | for our application. We just need to utilize it! We'll require it | into the script here so that we do not have to worry about the | loading of any our classes "manually". Feels great to relax. | */ require __DIR__.'/../bootstrap/autoload.php'; /* |-------------------------------------------------------------------------- | Turn On The Lights |-------------------------------------------------------------------------- | | We need to illuminate PHP development, so let's turn on the lights. | This bootstraps the framework and gets it ready for use, then it | will load up this application so that we can run it and send | the responses back to the browser and delight these users. | */ $app = require_once __DIR__.'/../bootstrap/start.php'; /* |-------------------------------------------------------------------------- | Run The Application |-------------------------------------------------------------------------- | | Once we have the application, we can simply call the run method, | which will execute the request and send the response back to | the client's browser allowing them to enjoy the creative | and wonderful application we have whipped up for them. | */ $app->run(); ================================================ FILE: public/packages/.gitkeep ================================================ ================================================ FILE: public/packages/chosen_v1.0.0/chosen.css ================================================ /* @group Base */ .chosen-container { position: relative; display: inline-block; vertical-align: middle; font-size: 13px; zoom: 1; *display: inline; -webkit-user-select: none; -moz-user-select: none; user-select: none; } .chosen-container .chosen-drop { position: absolute; top: 100%; left: -9999px; z-index: 1010; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; width: 100%; border: 1px solid #aaa; border-top: 0; background: #fff; box-shadow: 0 4px 5px rgba(0, 0, 0, 0.15); } .chosen-container.chosen-with-drop .chosen-drop { left: 0; } .chosen-container a { cursor: pointer; } /* @end */ /* @group Single Chosen */ .chosen-container-single .chosen-single { position: relative; display: block; overflow: hidden; padding: 0 0 0 8px; height: 23px; border: 1px solid #aaa; border-radius: 5px; background-color: #fff; background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #ffffff), color-stop(50%, #f6f6f6), color-stop(52%, #eeeeee), color-stop(100%, #f4f4f4)); background: -webkit-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%); background: -moz-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%); background: -o-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%); background: linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%); background-clip: padding-box; box-shadow: 0 0 3px white inset, 0 1px 1px rgba(0, 0, 0, 0.1); color: #444; text-decoration: none; white-space: nowrap; line-height: 24px; } .chosen-container-single .chosen-default { color: #999; } .chosen-container-single .chosen-single span { display: block; overflow: hidden; margin-right: 26px; text-overflow: ellipsis; white-space: nowrap; } .chosen-container-single .chosen-single-with-deselect span { margin-right: 38px; } .chosen-container-single .chosen-single abbr { position: absolute; top: 6px; right: 26px; display: block; width: 12px; height: 12px; background: url('chosen-sprite.png') -42px 1px no-repeat; font-size: 1px; } .chosen-container-single .chosen-single abbr:hover { background-position: -42px -10px; } .chosen-container-single.chosen-disabled .chosen-single abbr:hover { background-position: -42px -10px; } .chosen-container-single .chosen-single div { position: absolute; top: 0; right: 0; display: block; width: 18px; height: 100%; } .chosen-container-single .chosen-single div b { display: block; width: 100%; height: 100%; background: url('chosen-sprite.png') no-repeat 0px 2px; } .chosen-container-single .chosen-search { position: relative; z-index: 1010; margin: 0; padding: 3px 4px; white-space: nowrap; } .chosen-container-single .chosen-search input[type="text"] { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; margin: 1px 0; padding: 4px 20px 4px 5px; width: 100%; height: auto; outline: 0; border: 1px solid #aaa; background: white url('chosen-sprite.png') no-repeat 100% -20px; background: url('chosen-sprite.png') no-repeat 100% -20px, -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(1%, #eeeeee), color-stop(15%, #ffffff)); background: url('chosen-sprite.png') no-repeat 100% -20px, -webkit-linear-gradient(#eeeeee 1%, #ffffff 15%); background: url('chosen-sprite.png') no-repeat 100% -20px, -moz-linear-gradient(#eeeeee 1%, #ffffff 15%); background: url('chosen-sprite.png') no-repeat 100% -20px, -o-linear-gradient(#eeeeee 1%, #ffffff 15%); background: url('chosen-sprite.png') no-repeat 100% -20px, linear-gradient(#eeeeee 1%, #ffffff 15%); font-size: 1em; font-family: sans-serif; line-height: normal; border-radius: 0; } .chosen-container-single .chosen-drop { margin-top: -1px; border-radius: 0 0 4px 4px; background-clip: padding-box; } .chosen-container-single.chosen-container-single-nosearch .chosen-search { position: absolute; left: -9999px; } /* @end */ /* @group Results */ .chosen-container .chosen-results { position: relative; overflow-x: hidden; overflow-y: auto; margin: 0 4px 4px 0; padding: 0 0 0 4px; max-height: 240px; -webkit-overflow-scrolling: touch; } .chosen-container .chosen-results li { display: none; margin: 0; padding: 5px 6px; list-style: none; line-height: 15px; } .chosen-container .chosen-results li.active-result { display: list-item; cursor: pointer; } .chosen-container .chosen-results li.disabled-result { display: list-item; color: #ccc; cursor: default; } .chosen-container .chosen-results li.highlighted { background-color: #3875d7; background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #3875d7), color-stop(90%, #2a62bc)); background-image: -webkit-linear-gradient(#3875d7 20%, #2a62bc 90%); background-image: -moz-linear-gradient(#3875d7 20%, #2a62bc 90%); background-image: -o-linear-gradient(#3875d7 20%, #2a62bc 90%); background-image: linear-gradient(#3875d7 20%, #2a62bc 90%); color: #fff; } .chosen-container .chosen-results li.no-results { display: list-item; background: #f4f4f4; } .chosen-container .chosen-results li.group-result { display: list-item; font-weight: bold; cursor: default; } .chosen-container .chosen-results li.group-option { padding-left: 15px; } .chosen-container .chosen-results li em { font-style: normal; text-decoration: underline; } /* @end */ /* @group Multi Chosen */ .chosen-container-multi .chosen-choices { position: relative; overflow: hidden; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; margin: 0; padding: 0; width: 100%; height: auto !important; height: 1%; border: 1px solid #aaa; background-color: #fff; background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(1%, #eeeeee), color-stop(15%, #ffffff)); background-image: -webkit-linear-gradient(#eeeeee 1%, #ffffff 15%); background-image: -moz-linear-gradient(#eeeeee 1%, #ffffff 15%); background-image: -o-linear-gradient(#eeeeee 1%, #ffffff 15%); background-image: linear-gradient(#eeeeee 1%, #ffffff 15%); cursor: text; } .chosen-container-multi .chosen-choices li { float: left; list-style: none; } .chosen-container-multi .chosen-choices li.search-field { margin: 0; padding: 0; white-space: nowrap; } .chosen-container-multi .chosen-choices li.search-field input[type="text"] { margin: 1px 0; padding: 5px; height: 15px; outline: 0; border: 0 !important; background: transparent !important; box-shadow: none; color: #666; font-size: 100%; font-family: sans-serif; line-height: normal; border-radius: 0; } .chosen-container-multi .chosen-choices li.search-field .default { color: #999; } .chosen-container-multi .chosen-choices li.search-choice { position: relative; margin: 3px 0 3px 5px; padding: 3px 20px 3px 5px; border: 1px solid #aaa; border-radius: 3px; background-color: #e4e4e4; background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #f4f4f4), color-stop(50%, #f0f0f0), color-stop(52%, #e8e8e8), color-stop(100%, #eeeeee)); background-image: -webkit-linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); background-image: -moz-linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); background-image: -o-linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); background-image: linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); background-clip: padding-box; box-shadow: 0 0 2px white inset, 0 1px 0 rgba(0, 0, 0, 0.05); color: #333; line-height: 13px; cursor: default; } .chosen-container-multi .chosen-choices li.search-choice .search-choice-close { position: absolute; top: 4px; right: 3px; display: block; width: 12px; height: 12px; background: url('chosen-sprite.png') -42px 1px no-repeat; font-size: 1px; } .chosen-container-multi .chosen-choices li.search-choice .search-choice-close:hover { background-position: -42px -10px; } .chosen-container-multi .chosen-choices li.search-choice-disabled { padding-right: 5px; border: 1px solid #ccc; background-color: #e4e4e4; background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #f4f4f4), color-stop(50%, #f0f0f0), color-stop(52%, #e8e8e8), color-stop(100%, #eeeeee)); background-image: -webkit-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); background-image: -moz-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); background-image: -o-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); background-image: linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); color: #666; } .chosen-container-multi .chosen-choices li.search-choice-focus { background: #d4d4d4; } .chosen-container-multi .chosen-choices li.search-choice-focus .search-choice-close { background-position: -42px -10px; } .chosen-container-multi .chosen-results { margin: 0; padding: 0; } .chosen-container-multi .chosen-drop .result-selected { display: list-item; color: #ccc; cursor: default; } /* @end */ /* @group Active */ .chosen-container-active .chosen-single { border: 1px solid #5897fb; box-shadow: 0 0 5px rgba(0, 0, 0, 0.3); } .chosen-container-active.chosen-with-drop .chosen-single { border: 1px solid #aaa; -moz-border-radius-bottomright: 0; border-bottom-right-radius: 0; -moz-border-radius-bottomleft: 0; border-bottom-left-radius: 0; background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #eeeeee), color-stop(80%, #ffffff)); background-image: -webkit-linear-gradient(#eeeeee 20%, #ffffff 80%); background-image: -moz-linear-gradient(#eeeeee 20%, #ffffff 80%); background-image: -o-linear-gradient(#eeeeee 20%, #ffffff 80%); background-image: linear-gradient(#eeeeee 20%, #ffffff 80%); box-shadow: 0 1px 0 #fff inset; } .chosen-container-active.chosen-with-drop .chosen-single div { border-left: none; background: transparent; } .chosen-container-active.chosen-with-drop .chosen-single div b { background-position: -18px 2px; } .chosen-container-active .chosen-choices { border: 1px solid #5897fb; box-shadow: 0 0 5px rgba(0, 0, 0, 0.3); } .chosen-container-active .chosen-choices li.search-field input[type="text"] { color: #111 !important; } /* @end */ /* @group Disabled Support */ .chosen-disabled { opacity: 0.5 !important; cursor: default; } .chosen-disabled .chosen-single { cursor: default; } .chosen-disabled .chosen-choices .search-choice .search-choice-close { cursor: default; } /* @end */ /* @group Right to Left */ .chosen-rtl { text-align: right; } .chosen-rtl .chosen-single { overflow: visible; padding: 0 8px 0 0; } .chosen-rtl .chosen-single span { margin-right: 0; margin-left: 26px; direction: rtl; } .chosen-rtl .chosen-single-with-deselect span { margin-left: 38px; } .chosen-rtl .chosen-single div { right: auto; left: 3px; } .chosen-rtl .chosen-single abbr { right: auto; left: 26px; } .chosen-rtl .chosen-choices li { float: right; } .chosen-rtl .chosen-choices li.search-field input[type="text"] { direction: rtl; } .chosen-rtl .chosen-choices li.search-choice { margin: 3px 5px 3px 0; padding: 3px 5px 3px 19px; } .chosen-rtl .chosen-choices li.search-choice .search-choice-close { right: auto; left: 4px; } .chosen-rtl.chosen-container-single-nosearch .chosen-search, .chosen-rtl .chosen-drop { left: 9999px; } .chosen-rtl.chosen-container-single .chosen-results { margin: 0 0 4px 4px; padding: 0 4px 0 0; } .chosen-rtl .chosen-results li.group-option { padding-right: 15px; padding-left: 0; } .chosen-rtl.chosen-container-active.chosen-with-drop .chosen-single div { border-right: none; } .chosen-rtl .chosen-search input[type="text"] { padding: 4px 5px 4px 20px; background: white url('chosen-sprite.png') no-repeat -30px -20px; background: url('chosen-sprite.png') no-repeat -30px -20px, -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(1%, #eeeeee), color-stop(15%, #ffffff)); background: url('chosen-sprite.png') no-repeat -30px -20px, -webkit-linear-gradient(#eeeeee 1%, #ffffff 15%); background: url('chosen-sprite.png') no-repeat -30px -20px, -moz-linear-gradient(#eeeeee 1%, #ffffff 15%); background: url('chosen-sprite.png') no-repeat -30px -20px, -o-linear-gradient(#eeeeee 1%, #ffffff 15%); background: url('chosen-sprite.png') no-repeat -30px -20px, linear-gradient(#eeeeee 1%, #ffffff 15%); direction: rtl; } .chosen-rtl.chosen-container-single .chosen-single div b { background-position: 6px 2px; } .chosen-rtl.chosen-container-single.chosen-with-drop .chosen-single div b { background-position: -12px 2px; } /* @end */ /* @group Retina compatibility */ @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-resolution: 144dpi) { .chosen-rtl .chosen-search input[type="text"], .chosen-container-single .chosen-single abbr, .chosen-container-single .chosen-single div b, .chosen-container-single .chosen-search input[type="text"], .chosen-container-multi .chosen-choices .search-choice .search-choice-close, .chosen-container .chosen-results-scroll-down span, .chosen-container .chosen-results-scroll-up span { background-image: url('chosen-sprite@2x.png') !important; background-size: 52px 37px !important; background-repeat: no-repeat !important; } } /* @end */ ================================================ FILE: public/packages/chosen_v1.0.0/chosen.jquery.js ================================================ // Chosen, a Select Box Enhancer for jQuery and Prototype // by Patrick Filler for Harvest, http://getharvest.com // // Version 1.0.0 // Full source at https://github.com/harvesthq/chosen // Copyright (c) 2011 Harvest http://getharvest.com // MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md // This file is generated by `grunt build`, do not edit it by hand. (function() { var $, AbstractChosen, Chosen, SelectParser, _ref, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; SelectParser = (function() { function SelectParser() { this.options_index = 0; this.parsed = []; } SelectParser.prototype.add_node = function(child) { if (child.nodeName.toUpperCase() === "OPTGROUP") { return this.add_group(child); } else { return this.add_option(child); } }; SelectParser.prototype.add_group = function(group) { var group_position, option, _i, _len, _ref, _results; group_position = this.parsed.length; this.parsed.push({ array_index: group_position, group: true, label: this.escapeExpression(group.label), children: 0, disabled: group.disabled }); _ref = group.childNodes; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; _results.push(this.add_option(option, group_position, group.disabled)); } return _results; }; SelectParser.prototype.add_option = function(option, group_position, group_disabled) { if (option.nodeName.toUpperCase() === "OPTION") { if (option.text !== "") { if (group_position != null) { this.parsed[group_position].children += 1; } this.parsed.push({ array_index: this.parsed.length, options_index: this.options_index, value: option.value, text: option.text, html: option.innerHTML, selected: option.selected, disabled: group_disabled === true ? group_disabled : option.disabled, group_array_index: group_position, classes: option.className, style: option.style.cssText }); } else { this.parsed.push({ array_index: this.parsed.length, options_index: this.options_index, empty: true }); } return this.options_index += 1; } }; SelectParser.prototype.escapeExpression = function(text) { var map, unsafe_chars; if ((text == null) || text === false) { return ""; } if (!/[\&\<\>\"\'\`]/.test(text)) { return text; } map = { "<": "<", ">": ">", '"': """, "'": "'", "`": "`" }; unsafe_chars = /&(?!\w+;)|[\<\>\"\'\`]/g; return text.replace(unsafe_chars, function(chr) { return map[chr] || "&"; }); }; return SelectParser; })(); SelectParser.select_to_array = function(select) { var child, parser, _i, _len, _ref; parser = new SelectParser(); _ref = select.childNodes; for (_i = 0, _len = _ref.length; _i < _len; _i++) { child = _ref[_i]; parser.add_node(child); } return parser.parsed; }; AbstractChosen = (function() { function AbstractChosen(form_field, options) { this.form_field = form_field; this.options = options != null ? options : {}; if (!AbstractChosen.browser_is_supported()) { return; } this.is_multiple = this.form_field.multiple; this.set_default_text(); this.set_default_values(); this.setup(); this.set_up_html(); this.register_observers(); } AbstractChosen.prototype.set_default_values = function() { var _this = this; this.click_test_action = function(evt) { return _this.test_active_click(evt); }; this.activate_action = function(evt) { return _this.activate_field(evt); }; this.active_field = false; this.mouse_on_container = false; this.results_showing = false; this.result_highlighted = null; this.result_single_selected = null; this.allow_single_deselect = (this.options.allow_single_deselect != null) && (this.form_field.options[0] != null) && this.form_field.options[0].text === "" ? this.options.allow_single_deselect : false; this.disable_search_threshold = this.options.disable_search_threshold || 0; this.disable_search = this.options.disable_search || false; this.enable_split_word_search = this.options.enable_split_word_search != null ? this.options.enable_split_word_search : true; this.group_search = this.options.group_search != null ? this.options.group_search : true; this.search_contains = this.options.search_contains || false; this.single_backstroke_delete = this.options.single_backstroke_delete != null ? this.options.single_backstroke_delete : true; this.max_selected_options = this.options.max_selected_options || Infinity; this.inherit_select_classes = this.options.inherit_select_classes || false; this.display_selected_options = this.options.display_selected_options != null ? this.options.display_selected_options : true; return this.display_disabled_options = this.options.display_disabled_options != null ? this.options.display_disabled_options : true; }; AbstractChosen.prototype.set_default_text = function() { if (this.form_field.getAttribute("data-placeholder")) { this.default_text = this.form_field.getAttribute("data-placeholder"); } else if (this.is_multiple) { this.default_text = this.options.placeholder_text_multiple || this.options.placeholder_text || AbstractChosen.default_multiple_text; } else { this.default_text = this.options.placeholder_text_single || this.options.placeholder_text || AbstractChosen.default_single_text; } return this.results_none_found = this.form_field.getAttribute("data-no_results_text") || this.options.no_results_text || AbstractChosen.default_no_result_text; }; AbstractChosen.prototype.mouse_enter = function() { return this.mouse_on_container = true; }; AbstractChosen.prototype.mouse_leave = function() { return this.mouse_on_container = false; }; AbstractChosen.prototype.input_focus = function(evt) { var _this = this; if (this.is_multiple) { if (!this.active_field) { return setTimeout((function() { return _this.container_mousedown(); }), 50); } } else { if (!this.active_field) { return this.activate_field(); } } }; AbstractChosen.prototype.input_blur = function(evt) { var _this = this; if (!this.mouse_on_container) { this.active_field = false; return setTimeout((function() { return _this.blur_test(); }), 100); } }; AbstractChosen.prototype.results_option_build = function(options) { var content, data, _i, _len, _ref; content = ''; _ref = this.results_data; for (_i = 0, _len = _ref.length; _i < _len; _i++) { data = _ref[_i]; if (data.group) { content += this.result_add_group(data); } else { content += this.result_add_option(data); } if (options != null ? options.first : void 0) { if (data.selected && this.is_multiple) { this.choice_build(data); } else if (data.selected && !this.is_multiple) { this.single_set_selected_text(data.text); } } } return content; }; AbstractChosen.prototype.result_add_option = function(option) { var classes, style; if (!option.search_match) { return ''; } if (!this.include_option_in_results(option)) { return ''; } classes = []; if (!option.disabled && !(option.selected && this.is_multiple)) { classes.push("active-result"); } if (option.disabled && !(option.selected && this.is_multiple)) { classes.push("disabled-result"); } if (option.selected) { classes.push("result-selected"); } if (option.group_array_index != null) { classes.push("group-option"); } if (option.classes !== "") { classes.push(option.classes); } style = option.style.cssText !== "" ? " style=\"" + option.style + "\"" : ""; return "
  • " + option.search_text + "
  • "; }; AbstractChosen.prototype.result_add_group = function(group) { if (!(group.search_match || group.group_match)) { return ''; } if (!(group.active_options > 0)) { return ''; } return "
  • " + group.search_text + "
  • "; }; AbstractChosen.prototype.results_update_field = function() { this.set_default_text(); if (!this.is_multiple) { this.results_reset_cleanup(); } this.result_clear_highlight(); this.result_single_selected = null; this.results_build(); if (this.results_showing) { return this.winnow_results(); } }; AbstractChosen.prototype.results_toggle = function() { if (this.results_showing) { return this.results_hide(); } else { return this.results_show(); } }; AbstractChosen.prototype.results_search = function(evt) { if (this.results_showing) { return this.winnow_results(); } else { return this.results_show(); } }; AbstractChosen.prototype.winnow_results = function() { var escapedSearchText, option, regex, regexAnchor, results, results_group, searchText, startpos, text, zregex, _i, _len, _ref; this.no_results_clear(); results = 0; searchText = this.get_search_text(); escapedSearchText = searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); regexAnchor = this.search_contains ? "" : "^"; regex = new RegExp(regexAnchor + escapedSearchText, 'i'); zregex = new RegExp(escapedSearchText, 'i'); _ref = this.results_data; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; option.search_match = false; results_group = null; if (this.include_option_in_results(option)) { if (option.group) { option.group_match = false; option.active_options = 0; } if ((option.group_array_index != null) && this.results_data[option.group_array_index]) { results_group = this.results_data[option.group_array_index]; if (results_group.active_options === 0 && results_group.search_match) { results += 1; } results_group.active_options += 1; } if (!(option.group && !this.group_search)) { option.search_text = option.group ? option.label : option.html; option.search_match = this.search_string_match(option.search_text, regex); if (option.search_match && !option.group) { results += 1; } if (option.search_match) { if (searchText.length) { startpos = option.search_text.search(zregex); text = option.search_text.substr(0, startpos + searchText.length) + '' + option.search_text.substr(startpos + searchText.length); option.search_text = text.substr(0, startpos) + '' + text.substr(startpos); } if (results_group != null) { results_group.group_match = true; } } else if ((option.group_array_index != null) && this.results_data[option.group_array_index].search_match) { option.search_match = true; } } } } this.result_clear_highlight(); if (results < 1 && searchText.length) { this.update_results_content(""); return this.no_results(searchText); } else { this.update_results_content(this.results_option_build()); return this.winnow_results_set_highlight(); } }; AbstractChosen.prototype.search_string_match = function(search_string, regex) { var part, parts, _i, _len; if (regex.test(search_string)) { return true; } else if (this.enable_split_word_search && (search_string.indexOf(" ") >= 0 || search_string.indexOf("[") === 0)) { parts = search_string.replace(/\[|\]/g, "").split(" "); if (parts.length) { for (_i = 0, _len = parts.length; _i < _len; _i++) { part = parts[_i]; if (regex.test(part)) { return true; } } } } }; AbstractChosen.prototype.choices_count = function() { var option, _i, _len, _ref; if (this.selected_option_count != null) { return this.selected_option_count; } this.selected_option_count = 0; _ref = this.form_field.options; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; if (option.selected) { this.selected_option_count += 1; } } return this.selected_option_count; }; AbstractChosen.prototype.choices_click = function(evt) { evt.preventDefault(); if (!(this.results_showing || this.is_disabled)) { return this.results_show(); } }; AbstractChosen.prototype.keyup_checker = function(evt) { var stroke, _ref; stroke = (_ref = evt.which) != null ? _ref : evt.keyCode; this.search_field_scale(); switch (stroke) { case 8: if (this.is_multiple && this.backstroke_length < 1 && this.choices_count() > 0) { return this.keydown_backstroke(); } else if (!this.pending_backstroke) { this.result_clear_highlight(); return this.results_search(); } break; case 13: evt.preventDefault(); if (this.results_showing) { return this.result_select(evt); } break; case 27: if (this.results_showing) { this.results_hide(); } return true; case 9: case 38: case 40: case 16: case 91: case 17: break; default: return this.results_search(); } }; AbstractChosen.prototype.container_width = function() { if (this.options.width != null) { return this.options.width; } else { return "" + this.form_field.offsetWidth + "px"; } }; AbstractChosen.prototype.include_option_in_results = function(option) { if (this.is_multiple && (!this.display_selected_options && option.selected)) { return false; } if (!this.display_disabled_options && option.disabled) { return false; } if (option.empty) { return false; } return true; }; AbstractChosen.browser_is_supported = function() { if (window.navigator.appName === "Microsoft Internet Explorer") { return document.documentMode >= 8; } if (/iP(od|hone)/i.test(window.navigator.userAgent)) { return false; } if (/Android/i.test(window.navigator.userAgent)) { if (/Mobile/i.test(window.navigator.userAgent)) { return false; } } return true; }; AbstractChosen.default_multiple_text = "Select Some Options"; AbstractChosen.default_single_text = "Select an Option"; AbstractChosen.default_no_result_text = "No results match"; return AbstractChosen; })(); $ = jQuery; $.fn.extend({ chosen: function(options) { if (!AbstractChosen.browser_is_supported()) { return this; } return this.each(function(input_field) { var $this, chosen; $this = $(this); chosen = $this.data('chosen'); if (options === 'destroy' && chosen) { chosen.destroy(); } else if (!chosen) { $this.data('chosen', new Chosen(this, options)); } }); } }); Chosen = (function(_super) { __extends(Chosen, _super); function Chosen() { _ref = Chosen.__super__.constructor.apply(this, arguments); return _ref; } Chosen.prototype.setup = function() { this.form_field_jq = $(this.form_field); this.current_selectedIndex = this.form_field.selectedIndex; return this.is_rtl = this.form_field_jq.hasClass("chosen-rtl"); }; Chosen.prototype.set_up_html = function() { var container_classes, container_props; container_classes = ["chosen-container"]; container_classes.push("chosen-container-" + (this.is_multiple ? "multi" : "single")); if (this.inherit_select_classes && this.form_field.className) { container_classes.push(this.form_field.className); } if (this.is_rtl) { container_classes.push("chosen-rtl"); } container_props = { 'class': container_classes.join(' '), 'style': "width: " + (this.container_width()) + ";", 'title': this.form_field.title }; if (this.form_field.id.length) { container_props.id = this.form_field.id.replace(/[^\w]/g, '_') + "_chosen"; } this.container = $("
    ", container_props); if (this.is_multiple) { this.container.html('
      '); } else { this.container.html('' + this.default_text + '
        '); } this.form_field_jq.hide().after(this.container); this.dropdown = this.container.find('div.chosen-drop').first(); this.search_field = this.container.find('input').first(); this.search_results = this.container.find('ul.chosen-results').first(); this.search_field_scale(); this.search_no_results = this.container.find('li.no-results').first(); if (this.is_multiple) { this.search_choices = this.container.find('ul.chosen-choices').first(); this.search_container = this.container.find('li.search-field').first(); } else { this.search_container = this.container.find('div.chosen-search').first(); this.selected_item = this.container.find('.chosen-single').first(); } this.results_build(); this.set_tab_index(); this.set_label_behavior(); return this.form_field_jq.trigger("chosen:ready", { chosen: this }); }; Chosen.prototype.register_observers = function() { var _this = this; this.container.bind('mousedown.chosen', function(evt) { _this.container_mousedown(evt); }); this.container.bind('mouseup.chosen', function(evt) { _this.container_mouseup(evt); }); this.container.bind('mouseenter.chosen', function(evt) { _this.mouse_enter(evt); }); this.container.bind('mouseleave.chosen', function(evt) { _this.mouse_leave(evt); }); this.search_results.bind('mouseup.chosen', function(evt) { _this.search_results_mouseup(evt); }); this.search_results.bind('mouseover.chosen', function(evt) { _this.search_results_mouseover(evt); }); this.search_results.bind('mouseout.chosen', function(evt) { _this.search_results_mouseout(evt); }); this.search_results.bind('mousewheel.chosen DOMMouseScroll.chosen', function(evt) { _this.search_results_mousewheel(evt); }); this.form_field_jq.bind("chosen:updated.chosen", function(evt) { _this.results_update_field(evt); }); this.form_field_jq.bind("chosen:activate.chosen", function(evt) { _this.activate_field(evt); }); this.form_field_jq.bind("chosen:open.chosen", function(evt) { _this.container_mousedown(evt); }); this.search_field.bind('blur.chosen', function(evt) { _this.input_blur(evt); }); this.search_field.bind('keyup.chosen', function(evt) { _this.keyup_checker(evt); }); this.search_field.bind('keydown.chosen', function(evt) { _this.keydown_checker(evt); }); this.search_field.bind('focus.chosen', function(evt) { _this.input_focus(evt); }); if (this.is_multiple) { return this.search_choices.bind('click.chosen', function(evt) { _this.choices_click(evt); }); } else { return this.container.bind('click.chosen', function(evt) { evt.preventDefault(); }); } }; Chosen.prototype.destroy = function() { $(document).unbind("click.chosen", this.click_test_action); if (this.search_field[0].tabIndex) { this.form_field_jq[0].tabIndex = this.search_field[0].tabIndex; } this.container.remove(); this.form_field_jq.removeData('chosen'); return this.form_field_jq.show(); }; Chosen.prototype.search_field_disabled = function() { this.is_disabled = this.form_field_jq[0].disabled; if (this.is_disabled) { this.container.addClass('chosen-disabled'); this.search_field[0].disabled = true; if (!this.is_multiple) { this.selected_item.unbind("focus.chosen", this.activate_action); } return this.close_field(); } else { this.container.removeClass('chosen-disabled'); this.search_field[0].disabled = false; if (!this.is_multiple) { return this.selected_item.bind("focus.chosen", this.activate_action); } } }; Chosen.prototype.container_mousedown = function(evt) { if (!this.is_disabled) { if (evt && evt.type === "mousedown" && !this.results_showing) { evt.preventDefault(); } if (!((evt != null) && ($(evt.target)).hasClass("search-choice-close"))) { if (!this.active_field) { if (this.is_multiple) { this.search_field.val(""); } $(document).bind('click.chosen', this.click_test_action); this.results_show(); } else if (!this.is_multiple && evt && (($(evt.target)[0] === this.selected_item[0]) || $(evt.target).parents("a.chosen-single").length)) { evt.preventDefault(); this.results_toggle(); } return this.activate_field(); } } }; Chosen.prototype.container_mouseup = function(evt) { if (evt.target.nodeName === "ABBR" && !this.is_disabled) { return this.results_reset(evt); } }; Chosen.prototype.search_results_mousewheel = function(evt) { var delta, _ref1, _ref2; delta = -((_ref1 = evt.originalEvent) != null ? _ref1.wheelDelta : void 0) || ((_ref2 = evt.originialEvent) != null ? _ref2.detail : void 0); if (delta != null) { evt.preventDefault(); if (evt.type === 'DOMMouseScroll') { delta = delta * 40; } return this.search_results.scrollTop(delta + this.search_results.scrollTop()); } }; Chosen.prototype.blur_test = function(evt) { if (!this.active_field && this.container.hasClass("chosen-container-active")) { return this.close_field(); } }; Chosen.prototype.close_field = function() { $(document).unbind("click.chosen", this.click_test_action); this.active_field = false; this.results_hide(); this.container.removeClass("chosen-container-active"); this.clear_backstroke(); this.show_search_field_default(); return this.search_field_scale(); }; Chosen.prototype.activate_field = function() { this.container.addClass("chosen-container-active"); this.active_field = true; this.search_field.val(this.search_field.val()); return this.search_field.focus(); }; Chosen.prototype.test_active_click = function(evt) { if (this.container.is($(evt.target).closest('.chosen-container'))) { return this.active_field = true; } else { return this.close_field(); } }; Chosen.prototype.results_build = function() { this.parsing = true; this.selected_option_count = null; this.results_data = SelectParser.select_to_array(this.form_field); if (this.is_multiple) { this.search_choices.find("li.search-choice").remove(); } else if (!this.is_multiple) { this.single_set_selected_text(); if (this.disable_search || this.form_field.options.length <= this.disable_search_threshold) { this.search_field[0].readOnly = true; this.container.addClass("chosen-container-single-nosearch"); } else { this.search_field[0].readOnly = false; this.container.removeClass("chosen-container-single-nosearch"); } } this.update_results_content(this.results_option_build({ first: true })); this.search_field_disabled(); this.show_search_field_default(); this.search_field_scale(); return this.parsing = false; }; Chosen.prototype.result_do_highlight = function(el) { var high_bottom, high_top, maxHeight, visible_bottom, visible_top; if (el.length) { this.result_clear_highlight(); this.result_highlight = el; this.result_highlight.addClass("highlighted"); maxHeight = parseInt(this.search_results.css("maxHeight"), 10); visible_top = this.search_results.scrollTop(); visible_bottom = maxHeight + visible_top; high_top = this.result_highlight.position().top + this.search_results.scrollTop(); high_bottom = high_top + this.result_highlight.outerHeight(); if (high_bottom >= visible_bottom) { return this.search_results.scrollTop((high_bottom - maxHeight) > 0 ? high_bottom - maxHeight : 0); } else if (high_top < visible_top) { return this.search_results.scrollTop(high_top); } } }; Chosen.prototype.result_clear_highlight = function() { if (this.result_highlight) { this.result_highlight.removeClass("highlighted"); } return this.result_highlight = null; }; Chosen.prototype.results_show = function() { if (this.is_multiple && this.max_selected_options <= this.choices_count()) { this.form_field_jq.trigger("chosen:maxselected", { chosen: this }); return false; } this.container.addClass("chosen-with-drop"); this.form_field_jq.trigger("chosen:showing_dropdown", { chosen: this }); this.results_showing = true; this.search_field.focus(); this.search_field.val(this.search_field.val()); return this.winnow_results(); }; Chosen.prototype.update_results_content = function(content) { return this.search_results.html(content); }; Chosen.prototype.results_hide = function() { if (this.results_showing) { this.result_clear_highlight(); this.container.removeClass("chosen-with-drop"); this.form_field_jq.trigger("chosen:hiding_dropdown", { chosen: this }); } return this.results_showing = false; }; Chosen.prototype.set_tab_index = function(el) { var ti; if (this.form_field.tabIndex) { ti = this.form_field.tabIndex; this.form_field.tabIndex = -1; return this.search_field[0].tabIndex = ti; } }; Chosen.prototype.set_label_behavior = function() { var _this = this; this.form_field_label = this.form_field_jq.parents("label"); if (!this.form_field_label.length && this.form_field.id.length) { this.form_field_label = $("label[for='" + this.form_field.id + "']"); } if (this.form_field_label.length > 0) { return this.form_field_label.bind('click.chosen', function(evt) { if (_this.is_multiple) { return _this.container_mousedown(evt); } else { return _this.activate_field(); } }); } }; Chosen.prototype.show_search_field_default = function() { if (this.is_multiple && this.choices_count() < 1 && !this.active_field) { this.search_field.val(this.default_text); return this.search_field.addClass("default"); } else { this.search_field.val(""); return this.search_field.removeClass("default"); } }; Chosen.prototype.search_results_mouseup = function(evt) { var target; target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first(); if (target.length) { this.result_highlight = target; this.result_select(evt); return this.search_field.focus(); } }; Chosen.prototype.search_results_mouseover = function(evt) { var target; target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first(); if (target) { return this.result_do_highlight(target); } }; Chosen.prototype.search_results_mouseout = function(evt) { if ($(evt.target).hasClass("active-result" || $(evt.target).parents('.active-result').first())) { return this.result_clear_highlight(); } }; Chosen.prototype.choice_build = function(item) { var choice, close_link, _this = this; choice = $('
      • ', { "class": "search-choice" }).html("" + item.html + ""); if (item.disabled) { choice.addClass('search-choice-disabled'); } else { close_link = $('', { "class": 'search-choice-close', 'data-option-array-index': item.array_index }); close_link.bind('click.chosen', function(evt) { return _this.choice_destroy_link_click(evt); }); choice.append(close_link); } return this.search_container.before(choice); }; Chosen.prototype.choice_destroy_link_click = function(evt) { evt.preventDefault(); evt.stopPropagation(); if (!this.is_disabled) { return this.choice_destroy($(evt.target)); } }; Chosen.prototype.choice_destroy = function(link) { if (this.result_deselect(link[0].getAttribute("data-option-array-index"))) { this.show_search_field_default(); if (this.is_multiple && this.choices_count() > 0 && this.search_field.val().length < 1) { this.results_hide(); } link.parents('li').first().remove(); return this.search_field_scale(); } }; Chosen.prototype.results_reset = function() { this.form_field.options[0].selected = true; this.selected_option_count = null; this.single_set_selected_text(); this.show_search_field_default(); this.results_reset_cleanup(); this.form_field_jq.trigger("change"); if (this.active_field) { return this.results_hide(); } }; Chosen.prototype.results_reset_cleanup = function() { this.current_selectedIndex = this.form_field.selectedIndex; return this.selected_item.find("abbr").remove(); }; Chosen.prototype.result_select = function(evt) { var high, item, selected_index; if (this.result_highlight) { high = this.result_highlight; this.result_clear_highlight(); if (this.is_multiple && this.max_selected_options <= this.choices_count()) { this.form_field_jq.trigger("chosen:maxselected", { chosen: this }); return false; } if (this.is_multiple) { high.removeClass("active-result"); } else { if (this.result_single_selected) { this.result_single_selected.removeClass("result-selected"); selected_index = this.result_single_selected[0].getAttribute('data-option-array-index'); this.results_data[selected_index].selected = false; } this.result_single_selected = high; } high.addClass("result-selected"); item = this.results_data[high[0].getAttribute("data-option-array-index")]; item.selected = true; this.form_field.options[item.options_index].selected = true; this.selected_option_count = null; if (this.is_multiple) { this.choice_build(item); } else { this.single_set_selected_text(item.text); } if (!((evt.metaKey || evt.ctrlKey) && this.is_multiple)) { this.results_hide(); } this.search_field.val(""); if (this.is_multiple || this.form_field.selectedIndex !== this.current_selectedIndex) { this.form_field_jq.trigger("change", { 'selected': this.form_field.options[item.options_index].value }); } this.current_selectedIndex = this.form_field.selectedIndex; return this.search_field_scale(); } }; Chosen.prototype.single_set_selected_text = function(text) { if (text == null) { text = this.default_text; } if (text === this.default_text) { this.selected_item.addClass("chosen-default"); } else { this.single_deselect_control_build(); this.selected_item.removeClass("chosen-default"); } return this.selected_item.find("span").text(text); }; Chosen.prototype.result_deselect = function(pos) { var result_data; result_data = this.results_data[pos]; if (!this.form_field.options[result_data.options_index].disabled) { result_data.selected = false; this.form_field.options[result_data.options_index].selected = false; this.selected_option_count = null; this.result_clear_highlight(); if (this.results_showing) { this.winnow_results(); } this.form_field_jq.trigger("change", { deselected: this.form_field.options[result_data.options_index].value }); this.search_field_scale(); return true; } else { return false; } }; Chosen.prototype.single_deselect_control_build = function() { if (!this.allow_single_deselect) { return; } if (!this.selected_item.find("abbr").length) { this.selected_item.find("span").first().after(""); } return this.selected_item.addClass("chosen-single-with-deselect"); }; Chosen.prototype.get_search_text = function() { if (this.search_field.val() === this.default_text) { return ""; } else { return $('
        ').text($.trim(this.search_field.val())).html(); } }; Chosen.prototype.winnow_results_set_highlight = function() { var do_high, selected_results; selected_results = !this.is_multiple ? this.search_results.find(".result-selected.active-result") : []; do_high = selected_results.length ? selected_results.first() : this.search_results.find(".active-result").first(); if (do_high != null) { return this.result_do_highlight(do_high); } }; Chosen.prototype.no_results = function(terms) { var no_results_html; no_results_html = $('
      • ' + this.results_none_found + ' ""
      • '); no_results_html.find("span").first().html(terms); return this.search_results.append(no_results_html); }; Chosen.prototype.no_results_clear = function() { return this.search_results.find(".no-results").remove(); }; Chosen.prototype.keydown_arrow = function() { var next_sib; if (this.results_showing && this.result_highlight) { next_sib = this.result_highlight.nextAll("li.active-result").first(); if (next_sib) { return this.result_do_highlight(next_sib); } } else { return this.results_show(); } }; Chosen.prototype.keyup_arrow = function() { var prev_sibs; if (!this.results_showing && !this.is_multiple) { return this.results_show(); } else if (this.result_highlight) { prev_sibs = this.result_highlight.prevAll("li.active-result"); if (prev_sibs.length) { return this.result_do_highlight(prev_sibs.first()); } else { if (this.choices_count() > 0) { this.results_hide(); } return this.result_clear_highlight(); } } }; Chosen.prototype.keydown_backstroke = function() { var next_available_destroy; if (this.pending_backstroke) { this.choice_destroy(this.pending_backstroke.find("a").first()); return this.clear_backstroke(); } else { next_available_destroy = this.search_container.siblings("li.search-choice").last(); if (next_available_destroy.length && !next_available_destroy.hasClass("search-choice-disabled")) { this.pending_backstroke = next_available_destroy; if (this.single_backstroke_delete) { return this.keydown_backstroke(); } else { return this.pending_backstroke.addClass("search-choice-focus"); } } } }; Chosen.prototype.clear_backstroke = function() { if (this.pending_backstroke) { this.pending_backstroke.removeClass("search-choice-focus"); } return this.pending_backstroke = null; }; Chosen.prototype.keydown_checker = function(evt) { var stroke, _ref1; stroke = (_ref1 = evt.which) != null ? _ref1 : evt.keyCode; this.search_field_scale(); if (stroke !== 8 && this.pending_backstroke) { this.clear_backstroke(); } switch (stroke) { case 8: this.backstroke_length = this.search_field.val().length; break; case 9: if (this.results_showing && !this.is_multiple) { this.result_select(evt); } this.mouse_on_container = false; break; case 13: evt.preventDefault(); break; case 38: evt.preventDefault(); this.keyup_arrow(); break; case 40: evt.preventDefault(); this.keydown_arrow(); break; } }; Chosen.prototype.search_field_scale = function() { var div, f_width, h, style, style_block, styles, w, _i, _len; if (this.is_multiple) { h = 0; w = 0; style_block = "position:absolute; left: -1000px; top: -1000px; display:none;"; styles = ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height', 'text-transform', 'letter-spacing']; for (_i = 0, _len = styles.length; _i < _len; _i++) { style = styles[_i]; style_block += style + ":" + this.search_field.css(style) + ";"; } div = $('
        ', { 'style': style_block }); div.text(this.search_field.val()); $('body').append(div); w = div.width() + 25; div.remove(); f_width = this.container.outerWidth(); if (w > f_width - 10) { w = f_width - 10; } return this.search_field.css({ 'width': w + 'px' }); } }; return Chosen; })(AbstractChosen); }).call(this); ================================================ FILE: public/packages/chosen_v1.0.0/chosen.proto.js ================================================ // Chosen, a Select Box Enhancer for jQuery and Prototype // by Patrick Filler for Harvest, http://getharvest.com // // Version 1.0.0 // Full source at https://github.com/harvesthq/chosen // Copyright (c) 2011 Harvest http://getharvest.com // MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md // This file is generated by `grunt build`, do not edit it by hand. (function() { var AbstractChosen, SelectParser, _ref, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; SelectParser = (function() { function SelectParser() { this.options_index = 0; this.parsed = []; } SelectParser.prototype.add_node = function(child) { if (child.nodeName.toUpperCase() === "OPTGROUP") { return this.add_group(child); } else { return this.add_option(child); } }; SelectParser.prototype.add_group = function(group) { var group_position, option, _i, _len, _ref, _results; group_position = this.parsed.length; this.parsed.push({ array_index: group_position, group: true, label: this.escapeExpression(group.label), children: 0, disabled: group.disabled }); _ref = group.childNodes; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; _results.push(this.add_option(option, group_position, group.disabled)); } return _results; }; SelectParser.prototype.add_option = function(option, group_position, group_disabled) { if (option.nodeName.toUpperCase() === "OPTION") { if (option.text !== "") { if (group_position != null) { this.parsed[group_position].children += 1; } this.parsed.push({ array_index: this.parsed.length, options_index: this.options_index, value: option.value, text: option.text, html: option.innerHTML, selected: option.selected, disabled: group_disabled === true ? group_disabled : option.disabled, group_array_index: group_position, classes: option.className, style: option.style.cssText }); } else { this.parsed.push({ array_index: this.parsed.length, options_index: this.options_index, empty: true }); } return this.options_index += 1; } }; SelectParser.prototype.escapeExpression = function(text) { var map, unsafe_chars; if ((text == null) || text === false) { return ""; } if (!/[\&\<\>\"\'\`]/.test(text)) { return text; } map = { "<": "<", ">": ">", '"': """, "'": "'", "`": "`" }; unsafe_chars = /&(?!\w+;)|[\<\>\"\'\`]/g; return text.replace(unsafe_chars, function(chr) { return map[chr] || "&"; }); }; return SelectParser; })(); SelectParser.select_to_array = function(select) { var child, parser, _i, _len, _ref; parser = new SelectParser(); _ref = select.childNodes; for (_i = 0, _len = _ref.length; _i < _len; _i++) { child = _ref[_i]; parser.add_node(child); } return parser.parsed; }; AbstractChosen = (function() { function AbstractChosen(form_field, options) { this.form_field = form_field; this.options = options != null ? options : {}; if (!AbstractChosen.browser_is_supported()) { return; } this.is_multiple = this.form_field.multiple; this.set_default_text(); this.set_default_values(); this.setup(); this.set_up_html(); this.register_observers(); } AbstractChosen.prototype.set_default_values = function() { var _this = this; this.click_test_action = function(evt) { return _this.test_active_click(evt); }; this.activate_action = function(evt) { return _this.activate_field(evt); }; this.active_field = false; this.mouse_on_container = false; this.results_showing = false; this.result_highlighted = null; this.result_single_selected = null; this.allow_single_deselect = (this.options.allow_single_deselect != null) && (this.form_field.options[0] != null) && this.form_field.options[0].text === "" ? this.options.allow_single_deselect : false; this.disable_search_threshold = this.options.disable_search_threshold || 0; this.disable_search = this.options.disable_search || false; this.enable_split_word_search = this.options.enable_split_word_search != null ? this.options.enable_split_word_search : true; this.group_search = this.options.group_search != null ? this.options.group_search : true; this.search_contains = this.options.search_contains || false; this.single_backstroke_delete = this.options.single_backstroke_delete != null ? this.options.single_backstroke_delete : true; this.max_selected_options = this.options.max_selected_options || Infinity; this.inherit_select_classes = this.options.inherit_select_classes || false; this.display_selected_options = this.options.display_selected_options != null ? this.options.display_selected_options : true; return this.display_disabled_options = this.options.display_disabled_options != null ? this.options.display_disabled_options : true; }; AbstractChosen.prototype.set_default_text = function() { if (this.form_field.getAttribute("data-placeholder")) { this.default_text = this.form_field.getAttribute("data-placeholder"); } else if (this.is_multiple) { this.default_text = this.options.placeholder_text_multiple || this.options.placeholder_text || AbstractChosen.default_multiple_text; } else { this.default_text = this.options.placeholder_text_single || this.options.placeholder_text || AbstractChosen.default_single_text; } return this.results_none_found = this.form_field.getAttribute("data-no_results_text") || this.options.no_results_text || AbstractChosen.default_no_result_text; }; AbstractChosen.prototype.mouse_enter = function() { return this.mouse_on_container = true; }; AbstractChosen.prototype.mouse_leave = function() { return this.mouse_on_container = false; }; AbstractChosen.prototype.input_focus = function(evt) { var _this = this; if (this.is_multiple) { if (!this.active_field) { return setTimeout((function() { return _this.container_mousedown(); }), 50); } } else { if (!this.active_field) { return this.activate_field(); } } }; AbstractChosen.prototype.input_blur = function(evt) { var _this = this; if (!this.mouse_on_container) { this.active_field = false; return setTimeout((function() { return _this.blur_test(); }), 100); } }; AbstractChosen.prototype.results_option_build = function(options) { var content, data, _i, _len, _ref; content = ''; _ref = this.results_data; for (_i = 0, _len = _ref.length; _i < _len; _i++) { data = _ref[_i]; if (data.group) { content += this.result_add_group(data); } else { content += this.result_add_option(data); } if (options != null ? options.first : void 0) { if (data.selected && this.is_multiple) { this.choice_build(data); } else if (data.selected && !this.is_multiple) { this.single_set_selected_text(data.text); } } } return content; }; AbstractChosen.prototype.result_add_option = function(option) { var classes, style; if (!option.search_match) { return ''; } if (!this.include_option_in_results(option)) { return ''; } classes = []; if (!option.disabled && !(option.selected && this.is_multiple)) { classes.push("active-result"); } if (option.disabled && !(option.selected && this.is_multiple)) { classes.push("disabled-result"); } if (option.selected) { classes.push("result-selected"); } if (option.group_array_index != null) { classes.push("group-option"); } if (option.classes !== "") { classes.push(option.classes); } style = option.style.cssText !== "" ? " style=\"" + option.style + "\"" : ""; return "
      • " + option.search_text + "
      • "; }; AbstractChosen.prototype.result_add_group = function(group) { if (!(group.search_match || group.group_match)) { return ''; } if (!(group.active_options > 0)) { return ''; } return "
      • " + group.search_text + "
      • "; }; AbstractChosen.prototype.results_update_field = function() { this.set_default_text(); if (!this.is_multiple) { this.results_reset_cleanup(); } this.result_clear_highlight(); this.result_single_selected = null; this.results_build(); if (this.results_showing) { return this.winnow_results(); } }; AbstractChosen.prototype.results_toggle = function() { if (this.results_showing) { return this.results_hide(); } else { return this.results_show(); } }; AbstractChosen.prototype.results_search = function(evt) { if (this.results_showing) { return this.winnow_results(); } else { return this.results_show(); } }; AbstractChosen.prototype.winnow_results = function() { var escapedSearchText, option, regex, regexAnchor, results, results_group, searchText, startpos, text, zregex, _i, _len, _ref; this.no_results_clear(); results = 0; searchText = this.get_search_text(); escapedSearchText = searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); regexAnchor = this.search_contains ? "" : "^"; regex = new RegExp(regexAnchor + escapedSearchText, 'i'); zregex = new RegExp(escapedSearchText, 'i'); _ref = this.results_data; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; option.search_match = false; results_group = null; if (this.include_option_in_results(option)) { if (option.group) { option.group_match = false; option.active_options = 0; } if ((option.group_array_index != null) && this.results_data[option.group_array_index]) { results_group = this.results_data[option.group_array_index]; if (results_group.active_options === 0 && results_group.search_match) { results += 1; } results_group.active_options += 1; } if (!(option.group && !this.group_search)) { option.search_text = option.group ? option.label : option.html; option.search_match = this.search_string_match(option.search_text, regex); if (option.search_match && !option.group) { results += 1; } if (option.search_match) { if (searchText.length) { startpos = option.search_text.search(zregex); text = option.search_text.substr(0, startpos + searchText.length) + '
        ' + option.search_text.substr(startpos + searchText.length); option.search_text = text.substr(0, startpos) + '' + text.substr(startpos); } if (results_group != null) { results_group.group_match = true; } } else if ((option.group_array_index != null) && this.results_data[option.group_array_index].search_match) { option.search_match = true; } } } } this.result_clear_highlight(); if (results < 1 && searchText.length) { this.update_results_content(""); return this.no_results(searchText); } else { this.update_results_content(this.results_option_build()); return this.winnow_results_set_highlight(); } }; AbstractChosen.prototype.search_string_match = function(search_string, regex) { var part, parts, _i, _len; if (regex.test(search_string)) { return true; } else if (this.enable_split_word_search && (search_string.indexOf(" ") >= 0 || search_string.indexOf("[") === 0)) { parts = search_string.replace(/\[|\]/g, "").split(" "); if (parts.length) { for (_i = 0, _len = parts.length; _i < _len; _i++) { part = parts[_i]; if (regex.test(part)) { return true; } } } } }; AbstractChosen.prototype.choices_count = function() { var option, _i, _len, _ref; if (this.selected_option_count != null) { return this.selected_option_count; } this.selected_option_count = 0; _ref = this.form_field.options; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; if (option.selected) { this.selected_option_count += 1; } } return this.selected_option_count; }; AbstractChosen.prototype.choices_click = function(evt) { evt.preventDefault(); if (!(this.results_showing || this.is_disabled)) { return this.results_show(); } }; AbstractChosen.prototype.keyup_checker = function(evt) { var stroke, _ref; stroke = (_ref = evt.which) != null ? _ref : evt.keyCode; this.search_field_scale(); switch (stroke) { case 8: if (this.is_multiple && this.backstroke_length < 1 && this.choices_count() > 0) { return this.keydown_backstroke(); } else if (!this.pending_backstroke) { this.result_clear_highlight(); return this.results_search(); } break; case 13: evt.preventDefault(); if (this.results_showing) { return this.result_select(evt); } break; case 27: if (this.results_showing) { this.results_hide(); } return true; case 9: case 38: case 40: case 16: case 91: case 17: break; default: return this.results_search(); } }; AbstractChosen.prototype.container_width = function() { if (this.options.width != null) { return this.options.width; } else { return "" + this.form_field.offsetWidth + "px"; } }; AbstractChosen.prototype.include_option_in_results = function(option) { if (this.is_multiple && (!this.display_selected_options && option.selected)) { return false; } if (!this.display_disabled_options && option.disabled) { return false; } if (option.empty) { return false; } return true; }; AbstractChosen.browser_is_supported = function() { if (window.navigator.appName === "Microsoft Internet Explorer") { return document.documentMode >= 8; } if (/iP(od|hone)/i.test(window.navigator.userAgent)) { return false; } if (/Android/i.test(window.navigator.userAgent)) { if (/Mobile/i.test(window.navigator.userAgent)) { return false; } } return true; }; AbstractChosen.default_multiple_text = "Select Some Options"; AbstractChosen.default_single_text = "Select an Option"; AbstractChosen.default_no_result_text = "No results match"; return AbstractChosen; })(); this.Chosen = (function(_super) { __extends(Chosen, _super); function Chosen() { _ref = Chosen.__super__.constructor.apply(this, arguments); return _ref; } Chosen.prototype.setup = function() { this.current_selectedIndex = this.form_field.selectedIndex; return this.is_rtl = this.form_field.hasClassName("chosen-rtl"); }; Chosen.prototype.set_default_values = function() { Chosen.__super__.set_default_values.call(this); this.single_temp = new Template('
        #{default}
          '); this.multi_temp = new Template('
            '); return this.no_results_temp = new Template('
          • ' + this.results_none_found + ' "#{terms}"
          • '); }; Chosen.prototype.set_up_html = function() { var container_classes, container_props; container_classes = ["chosen-container"]; container_classes.push("chosen-container-" + (this.is_multiple ? "multi" : "single")); if (this.inherit_select_classes && this.form_field.className) { container_classes.push(this.form_field.className); } if (this.is_rtl) { container_classes.push("chosen-rtl"); } container_props = { 'class': container_classes.join(' '), 'style': "width: " + (this.container_width()) + ";", 'title': this.form_field.title }; if (this.form_field.id.length) { container_props.id = this.form_field.id.replace(/[^\w]/g, '_') + "_chosen"; } this.container = this.is_multiple ? new Element('div', container_props).update(this.multi_temp.evaluate({ "default": this.default_text })) : new Element('div', container_props).update(this.single_temp.evaluate({ "default": this.default_text })); this.form_field.hide().insert({ after: this.container }); this.dropdown = this.container.down('div.chosen-drop'); this.search_field = this.container.down('input'); this.search_results = this.container.down('ul.chosen-results'); this.search_field_scale(); this.search_no_results = this.container.down('li.no-results'); if (this.is_multiple) { this.search_choices = this.container.down('ul.chosen-choices'); this.search_container = this.container.down('li.search-field'); } else { this.search_container = this.container.down('div.chosen-search'); this.selected_item = this.container.down('.chosen-single'); } this.results_build(); this.set_tab_index(); this.set_label_behavior(); return this.form_field.fire("chosen:ready", { chosen: this }); }; Chosen.prototype.register_observers = function() { var _this = this; this.container.observe("mousedown", function(evt) { return _this.container_mousedown(evt); }); this.container.observe("mouseup", function(evt) { return _this.container_mouseup(evt); }); this.container.observe("mouseenter", function(evt) { return _this.mouse_enter(evt); }); this.container.observe("mouseleave", function(evt) { return _this.mouse_leave(evt); }); this.search_results.observe("mouseup", function(evt) { return _this.search_results_mouseup(evt); }); this.search_results.observe("mouseover", function(evt) { return _this.search_results_mouseover(evt); }); this.search_results.observe("mouseout", function(evt) { return _this.search_results_mouseout(evt); }); this.search_results.observe("mousewheel", function(evt) { return _this.search_results_mousewheel(evt); }); this.search_results.observe("DOMMouseScroll", function(evt) { return _this.search_results_mousewheel(evt); }); this.form_field.observe("chosen:updated", function(evt) { return _this.results_update_field(evt); }); this.form_field.observe("chosen:activate", function(evt) { return _this.activate_field(evt); }); this.form_field.observe("chosen:open", function(evt) { return _this.container_mousedown(evt); }); this.search_field.observe("blur", function(evt) { return _this.input_blur(evt); }); this.search_field.observe("keyup", function(evt) { return _this.keyup_checker(evt); }); this.search_field.observe("keydown", function(evt) { return _this.keydown_checker(evt); }); this.search_field.observe("focus", function(evt) { return _this.input_focus(evt); }); if (this.is_multiple) { return this.search_choices.observe("click", function(evt) { return _this.choices_click(evt); }); } else { return this.container.observe("click", function(evt) { return evt.preventDefault(); }); } }; Chosen.prototype.destroy = function() { document.stopObserving("click", this.click_test_action); this.form_field.stopObserving(); this.container.stopObserving(); this.search_results.stopObserving(); this.search_field.stopObserving(); if (this.form_field_label != null) { this.form_field_label.stopObserving(); } if (this.is_multiple) { this.search_choices.stopObserving(); this.container.select(".search-choice-close").each(function(choice) { return choice.stopObserving(); }); } else { this.selected_item.stopObserving(); } if (this.search_field.tabIndex) { this.form_field.tabIndex = this.search_field.tabIndex; } this.container.remove(); return this.form_field.show(); }; Chosen.prototype.search_field_disabled = function() { this.is_disabled = this.form_field.disabled; if (this.is_disabled) { this.container.addClassName('chosen-disabled'); this.search_field.disabled = true; if (!this.is_multiple) { this.selected_item.stopObserving("focus", this.activate_action); } return this.close_field(); } else { this.container.removeClassName('chosen-disabled'); this.search_field.disabled = false; if (!this.is_multiple) { return this.selected_item.observe("focus", this.activate_action); } } }; Chosen.prototype.container_mousedown = function(evt) { if (!this.is_disabled) { if (evt && evt.type === "mousedown" && !this.results_showing) { evt.stop(); } if (!((evt != null) && evt.target.hasClassName("search-choice-close"))) { if (!this.active_field) { if (this.is_multiple) { this.search_field.clear(); } document.observe("click", this.click_test_action); this.results_show(); } else if (!this.is_multiple && evt && (evt.target === this.selected_item || evt.target.up("a.chosen-single"))) { this.results_toggle(); } return this.activate_field(); } } }; Chosen.prototype.container_mouseup = function(evt) { if (evt.target.nodeName === "ABBR" && !this.is_disabled) { return this.results_reset(evt); } }; Chosen.prototype.search_results_mousewheel = function(evt) { var delta; delta = -evt.wheelDelta || evt.detail; if (delta != null) { evt.preventDefault(); if (evt.type === 'DOMMouseScroll') { delta = delta * 40; } return this.search_results.scrollTop = delta + this.search_results.scrollTop; } }; Chosen.prototype.blur_test = function(evt) { if (!this.active_field && this.container.hasClassName("chosen-container-active")) { return this.close_field(); } }; Chosen.prototype.close_field = function() { document.stopObserving("click", this.click_test_action); this.active_field = false; this.results_hide(); this.container.removeClassName("chosen-container-active"); this.clear_backstroke(); this.show_search_field_default(); return this.search_field_scale(); }; Chosen.prototype.activate_field = function() { this.container.addClassName("chosen-container-active"); this.active_field = true; this.search_field.value = this.search_field.value; return this.search_field.focus(); }; Chosen.prototype.test_active_click = function(evt) { if (evt.target.up('.chosen-container') === this.container) { return this.active_field = true; } else { return this.close_field(); } }; Chosen.prototype.results_build = function() { this.parsing = true; this.selected_option_count = null; this.results_data = SelectParser.select_to_array(this.form_field); if (this.is_multiple) { this.search_choices.select("li.search-choice").invoke("remove"); } else if (!this.is_multiple) { this.single_set_selected_text(); if (this.disable_search || this.form_field.options.length <= this.disable_search_threshold) { this.search_field.readOnly = true; this.container.addClassName("chosen-container-single-nosearch"); } else { this.search_field.readOnly = false; this.container.removeClassName("chosen-container-single-nosearch"); } } this.update_results_content(this.results_option_build({ first: true })); this.search_field_disabled(); this.show_search_field_default(); this.search_field_scale(); return this.parsing = false; }; Chosen.prototype.result_do_highlight = function(el) { var high_bottom, high_top, maxHeight, visible_bottom, visible_top; this.result_clear_highlight(); this.result_highlight = el; this.result_highlight.addClassName("highlighted"); maxHeight = parseInt(this.search_results.getStyle('maxHeight'), 10); visible_top = this.search_results.scrollTop; visible_bottom = maxHeight + visible_top; high_top = this.result_highlight.positionedOffset().top; high_bottom = high_top + this.result_highlight.getHeight(); if (high_bottom >= visible_bottom) { return this.search_results.scrollTop = (high_bottom - maxHeight) > 0 ? high_bottom - maxHeight : 0; } else if (high_top < visible_top) { return this.search_results.scrollTop = high_top; } }; Chosen.prototype.result_clear_highlight = function() { if (this.result_highlight) { this.result_highlight.removeClassName('highlighted'); } return this.result_highlight = null; }; Chosen.prototype.results_show = function() { if (this.is_multiple && this.max_selected_options <= this.choices_count()) { this.form_field.fire("chosen:maxselected", { chosen: this }); return false; } this.container.addClassName("chosen-with-drop"); this.form_field.fire("chosen:showing_dropdown", { chosen: this }); this.results_showing = true; this.search_field.focus(); this.search_field.value = this.search_field.value; return this.winnow_results(); }; Chosen.prototype.update_results_content = function(content) { return this.search_results.update(content); }; Chosen.prototype.results_hide = function() { if (this.results_showing) { this.result_clear_highlight(); this.container.removeClassName("chosen-with-drop"); this.form_field.fire("chosen:hiding_dropdown", { chosen: this }); } return this.results_showing = false; }; Chosen.prototype.set_tab_index = function(el) { var ti; if (this.form_field.tabIndex) { ti = this.form_field.tabIndex; this.form_field.tabIndex = -1; return this.search_field.tabIndex = ti; } }; Chosen.prototype.set_label_behavior = function() { var _this = this; this.form_field_label = this.form_field.up("label"); if (this.form_field_label == null) { this.form_field_label = $$("label[for='" + this.form_field.id + "']").first(); } if (this.form_field_label != null) { return this.form_field_label.observe("click", function(evt) { if (_this.is_multiple) { return _this.container_mousedown(evt); } else { return _this.activate_field(); } }); } }; Chosen.prototype.show_search_field_default = function() { if (this.is_multiple && this.choices_count() < 1 && !this.active_field) { this.search_field.value = this.default_text; return this.search_field.addClassName("default"); } else { this.search_field.value = ""; return this.search_field.removeClassName("default"); } }; Chosen.prototype.search_results_mouseup = function(evt) { var target; target = evt.target.hasClassName("active-result") ? evt.target : evt.target.up(".active-result"); if (target) { this.result_highlight = target; this.result_select(evt); return this.search_field.focus(); } }; Chosen.prototype.search_results_mouseover = function(evt) { var target; target = evt.target.hasClassName("active-result") ? evt.target : evt.target.up(".active-result"); if (target) { return this.result_do_highlight(target); } }; Chosen.prototype.search_results_mouseout = function(evt) { if (evt.target.hasClassName('active-result') || evt.target.up('.active-result')) { return this.result_clear_highlight(); } }; Chosen.prototype.choice_build = function(item) { var choice, close_link, _this = this; choice = new Element('li', { "class": "search-choice" }).update("" + item.html + ""); if (item.disabled) { choice.addClassName('search-choice-disabled'); } else { close_link = new Element('a', { href: '#', "class": 'search-choice-close', rel: item.array_index }); close_link.observe("click", function(evt) { return _this.choice_destroy_link_click(evt); }); choice.insert(close_link); } return this.search_container.insert({ before: choice }); }; Chosen.prototype.choice_destroy_link_click = function(evt) { evt.preventDefault(); evt.stopPropagation(); if (!this.is_disabled) { return this.choice_destroy(evt.target); } }; Chosen.prototype.choice_destroy = function(link) { if (this.result_deselect(link.readAttribute("rel"))) { this.show_search_field_default(); if (this.is_multiple && this.choices_count() > 0 && this.search_field.value.length < 1) { this.results_hide(); } link.up('li').remove(); return this.search_field_scale(); } }; Chosen.prototype.results_reset = function() { this.form_field.options[0].selected = true; this.selected_option_count = null; this.single_set_selected_text(); this.show_search_field_default(); this.results_reset_cleanup(); if (typeof Event.simulate === 'function') { this.form_field.simulate("change"); } if (this.active_field) { return this.results_hide(); } }; Chosen.prototype.results_reset_cleanup = function() { var deselect_trigger; this.current_selectedIndex = this.form_field.selectedIndex; deselect_trigger = this.selected_item.down("abbr"); if (deselect_trigger) { return deselect_trigger.remove(); } }; Chosen.prototype.result_select = function(evt) { var high, item, selected_index; if (this.result_highlight) { high = this.result_highlight; this.result_clear_highlight(); if (this.is_multiple && this.max_selected_options <= this.choices_count()) { this.form_field.fire("chosen:maxselected", { chosen: this }); return false; } if (this.is_multiple) { high.removeClassName("active-result"); } else { if (this.result_single_selected) { this.result_single_selected.removeClassName("result-selected"); selected_index = this.result_single_selected.getAttribute('data-option-array-index'); this.results_data[selected_index].selected = false; } this.result_single_selected = high; } high.addClassName("result-selected"); item = this.results_data[high.getAttribute("data-option-array-index")]; item.selected = true; this.form_field.options[item.options_index].selected = true; this.selected_option_count = null; if (this.is_multiple) { this.choice_build(item); } else { this.single_set_selected_text(item.text); } if (!((evt.metaKey || evt.ctrlKey) && this.is_multiple)) { this.results_hide(); } this.search_field.value = ""; if (typeof Event.simulate === 'function' && (this.is_multiple || this.form_field.selectedIndex !== this.current_selectedIndex)) { this.form_field.simulate("change"); } this.current_selectedIndex = this.form_field.selectedIndex; return this.search_field_scale(); } }; Chosen.prototype.single_set_selected_text = function(text) { if (text == null) { text = this.default_text; } if (text === this.default_text) { this.selected_item.addClassName("chosen-default"); } else { this.single_deselect_control_build(); this.selected_item.removeClassName("chosen-default"); } return this.selected_item.down("span").update(text); }; Chosen.prototype.result_deselect = function(pos) { var result_data; result_data = this.results_data[pos]; if (!this.form_field.options[result_data.options_index].disabled) { result_data.selected = false; this.form_field.options[result_data.options_index].selected = false; this.selected_option_count = null; this.result_clear_highlight(); if (this.results_showing) { this.winnow_results(); } if (typeof Event.simulate === 'function') { this.form_field.simulate("change"); } this.search_field_scale(); return true; } else { return false; } }; Chosen.prototype.single_deselect_control_build = function() { if (!this.allow_single_deselect) { return; } if (!this.selected_item.down("abbr")) { this.selected_item.down("span").insert({ after: "" }); } return this.selected_item.addClassName("chosen-single-with-deselect"); }; Chosen.prototype.get_search_text = function() { if (this.search_field.value === this.default_text) { return ""; } else { return this.search_field.value.strip().escapeHTML(); } }; Chosen.prototype.winnow_results_set_highlight = function() { var do_high; if (!this.is_multiple) { do_high = this.search_results.down(".result-selected.active-result"); } if (do_high == null) { do_high = this.search_results.down(".active-result"); } if (do_high != null) { return this.result_do_highlight(do_high); } }; Chosen.prototype.no_results = function(terms) { return this.search_results.insert(this.no_results_temp.evaluate({ terms: terms })); }; Chosen.prototype.no_results_clear = function() { var nr, _results; nr = null; _results = []; while (nr = this.search_results.down(".no-results")) { _results.push(nr.remove()); } return _results; }; Chosen.prototype.keydown_arrow = function() { var next_sib; if (this.results_showing && this.result_highlight) { next_sib = this.result_highlight.next('.active-result'); if (next_sib) { return this.result_do_highlight(next_sib); } } else { return this.results_show(); } }; Chosen.prototype.keyup_arrow = function() { var actives, prevs, sibs; if (!this.results_showing && !this.is_multiple) { return this.results_show(); } else if (this.result_highlight) { sibs = this.result_highlight.previousSiblings(); actives = this.search_results.select("li.active-result"); prevs = sibs.intersect(actives); if (prevs.length) { return this.result_do_highlight(prevs.first()); } else { if (this.choices_count() > 0) { this.results_hide(); } return this.result_clear_highlight(); } } }; Chosen.prototype.keydown_backstroke = function() { var next_available_destroy; if (this.pending_backstroke) { this.choice_destroy(this.pending_backstroke.down("a")); return this.clear_backstroke(); } else { next_available_destroy = this.search_container.siblings().last(); if (next_available_destroy && next_available_destroy.hasClassName("search-choice") && !next_available_destroy.hasClassName("search-choice-disabled")) { this.pending_backstroke = next_available_destroy; if (this.pending_backstroke) { this.pending_backstroke.addClassName("search-choice-focus"); } if (this.single_backstroke_delete) { return this.keydown_backstroke(); } else { return this.pending_backstroke.addClassName("search-choice-focus"); } } } }; Chosen.prototype.clear_backstroke = function() { if (this.pending_backstroke) { this.pending_backstroke.removeClassName("search-choice-focus"); } return this.pending_backstroke = null; }; Chosen.prototype.keydown_checker = function(evt) { var stroke, _ref1; stroke = (_ref1 = evt.which) != null ? _ref1 : evt.keyCode; this.search_field_scale(); if (stroke !== 8 && this.pending_backstroke) { this.clear_backstroke(); } switch (stroke) { case 8: this.backstroke_length = this.search_field.value.length; break; case 9: if (this.results_showing && !this.is_multiple) { this.result_select(evt); } this.mouse_on_container = false; break; case 13: evt.preventDefault(); break; case 38: evt.preventDefault(); this.keyup_arrow(); break; case 40: evt.preventDefault(); this.keydown_arrow(); break; } }; Chosen.prototype.search_field_scale = function() { var div, f_width, h, style, style_block, styles, w, _i, _len; if (this.is_multiple) { h = 0; w = 0; style_block = "position:absolute; left: -1000px; top: -1000px; display:none;"; styles = ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height', 'text-transform', 'letter-spacing']; for (_i = 0, _len = styles.length; _i < _len; _i++) { style = styles[_i]; style_block += style + ":" + this.search_field.getStyle(style) + ";"; } div = new Element('div', { 'style': style_block }).update(this.search_field.value.escapeHTML()); document.body.appendChild(div); w = Element.measure(div, 'width') + 25; div.remove(); f_width = this.container.getWidth(); if (w > f_width - 10) { w = f_width - 10; } return this.search_field.setStyle({ 'width': w + 'px' }); } }; return Chosen; })(AbstractChosen); }).call(this); ================================================ FILE: public/packages/chosen_v1.0.0/docsupport/prism.css ================================================ /** * okaidia theme for JavaScript, CSS and HTML * Loosely based on Monokai textmate theme by http://www.monokai.nl/ * @author ocodia */ code[class*="language-"], pre[class*="language-"] { color: #f8f8f2; text-shadow: 0 1px rgba(0,0,0,0.3); font-family: Consolas, Monaco, 'Andale Mono', monospace; direction: ltr; text-align: left; white-space: pre; word-spacing: normal; -moz-tab-size: 4; -o-tab-size: 4; tab-size: 4; -webkit-hyphens: none; -moz-hyphens: none; -ms-hyphens: none; hyphens: none; } /* Code blocks */ pre[class*="language-"] { padding: 1em; margin: .5em 0; overflow: auto; border-radius: 0.3em; } :not(pre) > code[class*="language-"], pre[class*="language-"] { background: #272822; } /* Inline code */ :not(pre) > code[class*="language-"] { padding: .1em; border-radius: .3em; } .token.comment, .token.prolog, .token.doctype, .token.cdata { color: slategray; } .token.punctuation { color: #f8f8f2; } .namespace { opacity: .7; } .token.property, .token.tag { color: #f92672; } .token.boolean, .token.number{ color: #ae81ff; } .token.selector, .token.attr-name, .token.string { color: #a6e22e; } .token.operator, .token.entity, .token.url, .language-css .token.string, .style .token.string { color: #f8f8f2; } .token.atrule, .token.attr-value { color: #e6db74; } .token.keyword{ color: #66d9ef; } .token.regex, .token.important { color: #fd971f; } .token.important { font-weight: bold; } .token.entity { cursor: help; } ================================================ FILE: public/packages/chosen_v1.0.0/docsupport/prism.js ================================================ /** * Prism: Lightweight, robust, elegant syntax highlighting * MIT license http://www.opensource.org/licenses/mit-license.php/ * @author Lea Verou http://lea.verou.me */(function(){var e=/\blang(?:uage)?-(?!\*)(\w+)\b/i,t=self.Prism={util:{type:function(e){return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]},clone:function(e){var n=t.util.type(e);switch(n){case"Object":var r={};for(var i in e)e.hasOwnProperty(i)&&(r[i]=t.util.clone(e[i]));return r;case"Array":return e.slice()}return e}},languages:{extend:function(e,n){var r=t.util.clone(t.languages[e]);for(var i in n)r[i]=n[i];return r},insertBefore:function(e,n,r,i){i=i||t.languages;var s=i[e],o={};for(var u in s)if(s.hasOwnProperty(u)){if(u==n)for(var a in r)r.hasOwnProperty(a)&&(o[a]=r[a]);o[u]=s[u]}return i[e]=o},DFS:function(e,n){for(var r in e){n.call(e,r,e[r]);t.util.type(e)==="Object"&&t.languages.DFS(e[r],n)}}},highlightAll:function(e,n){var r=document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code');for(var i=0,s;s=r[i++];)t.highlightElement(s,e===!0,n)},highlightElement:function(r,i,s){var o,u,a=r;while(a&&!e.test(a.className))a=a.parentNode;if(a){o=(a.className.match(e)||[,""])[1];u=t.languages[o]}if(!u)return;r.className=r.className.replace(e,"").replace(/\s+/g," ")+" language-"+o;a=r.parentNode;/pre/i.test(a.nodeName)&&(a.className=a.className.replace(e,"").replace(/\s+/g," ")+" language-"+o);var f=r.textContent;if(!f)return;f=f.replace(/&/g,"&").replace(/e.length)break e;if(p instanceof i)continue;a.lastIndex=0;var d=a.exec(p);if(d){l&&(c=d[1].length);var v=d.index-1+c,d=d[0].slice(c),m=d.length,g=v+m,y=p.slice(0,v+1),b=p.slice(g+1),w=[h,1];y&&w.push(y);var E=new i(u,f?t.tokenize(d,f):d);w.push(E);b&&w.push(b);Array.prototype.splice.apply(s,w)}}}return s},hooks:{all:{},add:function(e,n){var r=t.hooks.all;r[e]=r[e]||[];r[e].push(n)},run:function(e,n){var r=t.hooks.all[e];if(!r||!r.length)return;for(var i=0,s;s=r[i++];)s(n)}}},n=t.Token=function(e,t){this.type=e;this.content=t};n.stringify=function(e,r,i){if(typeof e=="string")return e;if(Object.prototype.toString.call(e)=="[object Array]")return e.map(function(t){return n.stringify(t,r,e)}).join("");var s={type:e.type,content:n.stringify(e.content,r,i),tag:"span",classes:["token",e.type],attributes:{},language:r,parent:i};s.type=="comment"&&(s.attributes.spellcheck="true");t.hooks.run("wrap",s);var o="";for(var u in s.attributes)o+=u+'="'+(s.attributes[u]||"")+'"';return"<"+s.tag+' class="'+s.classes.join(" ")+'" '+o+">"+s.content+""};if(!self.document){self.addEventListener("message",function(e){var n=JSON.parse(e.data),r=n.language,i=n.code;self.postMessage(JSON.stringify(t.tokenize(i,t.languages[r])));self.close()},!1);return}var r=document.getElementsByTagName("script");r=r[r.length-1];if(r){t.filename=r.src;document.addEventListener&&!r.hasAttribute("data-manual")&&document.addEventListener("DOMContentLoaded",t.highlightAll)}})();; Prism.languages.markup={comment:/<!--[\w\W]*?-->/g,prolog:/<\?.+?\?>/,doctype:/<!DOCTYPE.+?>/,cdata:/<!\[CDATA\[[\w\W]*?]]>/i,tag:{pattern:/<\/?[\w:-]+\s*(?:\s+[\w:-]+(?:=(?:("|')(\\?[\w\W])*?\1|\w+))?\s*)*\/?>/gi,inside:{tag:{pattern:/^<\/?[\w:-]+/i,inside:{punctuation:/^<\/?/,namespace:/^[\w-]+?:/}},"attr-value":{pattern:/=(?:('|")[\w\W]*?(\1)|[^\s>]+)/gi,inside:{punctuation:/=|>|"/g}},punctuation:/\/?>/g,"attr-name":{pattern:/[\w:-]+/g,inside:{namespace:/^[\w-]+?:/}}}},entity:/&#?[\da-z]{1,8};/gi};Prism.hooks.add("wrap",function(e){e.type==="entity"&&(e.attributes.title=e.content.replace(/&/,"&"))});; Prism.languages.css={comment:/\/\*[\w\W]*?\*\//g,atrule:{pattern:/@[\w-]+?.*?(;|(?=\s*{))/gi,inside:{punctuation:/[;:]/g}},url:/url\((["']?).*?\1\)/gi,selector:/[^\{\}\s][^\{\};]*(?=\s*\{)/g,property:/(\b|\B)[\w-]+(?=\s*:)/ig,string:/("|')(\\?.)*?\1/g,important:/\B!important\b/gi,ignore:/&(lt|gt|amp);/gi,punctuation:/[\{\};:]/g};Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{style:{pattern:/(<|<)style[\w\W]*?(>|>)[\w\W]*?(<|<)\/style(>|>)/ig,inside:{tag:{pattern:/(<|<)style[\w\W]*?(>|>)|(<|<)\/style(>|>)/ig,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.css}}});; Prism.languages.clike={comment:{pattern:/(^|[^\\])(\/\*[\w\W]*?\*\/|(^|[^:])\/\/.*?(\r?\n|$))/g,lookbehind:!0},string:/("|')(\\?.)*?\1/g,"class-name":{pattern:/((?:(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/ig,lookbehind:!0,inside:{punctuation:/(\.|\\)/}},keyword:/\b(if|else|while|do|for|return|in|instanceof|function|new|try|catch|finally|null|break|continue)\b/g,"boolean":/\b(true|false)\b/g,"function":{pattern:/[a-z0-9_]+\(/ig,inside:{punctuation:/\(/}}, number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/g,operator:/[-+]{1,2}|!|<=?|>=?|={1,3}|(&){1,2}|\|?\||\?|\*|\/|\~|\^|\%/g,ignore:/&(lt|gt|amp);/gi,punctuation:/[{}[\];(),.:]/g};; Prism.languages.javascript=Prism.languages.extend("clike",{keyword:/\b(var|let|if|else|while|do|for|return|in|instanceof|function|new|with|typeof|try|catch|finally|null|break|continue)\b/g,number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?|NaN|-?Infinity)\b/g});Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/g,lookbehind:!0}});Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{script:{pattern:/(<|<)script[\w\W]*?(>|>)[\w\W]*?(<|<)\/script(>|>)/ig,inside:{tag:{pattern:/(<|<)script[\w\W]*?(>|>)|(<|<)\/script(>|>)/ig,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.javascript}}});; ================================================ FILE: public/packages/chosen_v1.0.0/docsupport/style.css ================================================ /* Reset */ html, body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ""; content: none; } ins { background-color: #ff9; color: #000; text-decoration: none; } mark { background-color: #ff9; color: #000; font-style: italic; font-weight: bold; } del { text-decoration: line-through; } abbr[title], dfn[title] { border-bottom: 1px dotted; cursor: help; } table { border-collapse: collapse; border-spacing: 0; } hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; } input, select { vertical-align: middle; } body { font:13px/1.231 sans-serif; *font-size:small; } /* Hack retained to preserve specificity */ select, input, textarea, button { font:99% sans-serif; } pre, code, kbd, samp { font-family: monospace, sans-serif; } body { background: #EEE; color: #444; line-height: 1.4em; } header h1 { color: black; font-size: 2em; line-height: 1.1em; display: inline-block; height: 27px; margin: 20px 0 25px; } div#content { background: white; border: 1px solid #ccc; border-width: 0 1px 1px; margin: 0 auto; padding: 40px 50px 40px; width: 738px; } footer { color: #999; padding-top: 40px; font-size: 0.8em; text-align: center; } body { font-family: sans-serif; font-size: 1em; } p { margin: 0 0 .7em; max-width: 700px; } h2 { border-bottom: 1px solid #ccc; font-size: 1.2em; margin: 3em 0 1em 0; font-weight: bold;} h3 { font-weight: bold; } h2.intro { border-bottom: none; font-size: 1em; font-weight: normal; margin-top:0; } ul li { list-style: disc; margin-left: 1em; margin-bottom: 1.25em; } ol li { margin-left: 1.25em; } ol ul, ul ul { margin: .25em 0 0; } ol ul li, ul ul li { list-style-type: circle; margin: 0 0 .25em 1em; } li > p { margin-top: .25em; } div.side-by-side { width: 100%; margin-bottom: 1em; } div.side-by-side > div { float: left; width: 49%; } div.side-by-side > div > em { margin-bottom: 10px; display: block; } .faqs em { display: block; } .clearfix:after { content: "\0020"; display: block; height: 0; clear: both; overflow: hidden; visibility: hidden; } a { color: #F36C00; outline: none; text-decoration: none; } a:hover { text-decoration: underline; } ul.credits li { margin-bottom: .25em; } strong { font-weight: bold; } .button { background: #fafafa; background: -webkit-linear-gradient(top, #ffffff, #eeeeee); background: -moz-linear-gradient(top, #ffffff, #eeeeee); background: -o-linear-gradient(top, #ffffff, #eeeeee); background: linear-gradient(to bottom, #ffffff, #eeeeee); border: 1px solid #bbbbbb; border-radius: 4px; box-shadow: inset 0 1px 1px rgba(255, 255, 255, 0.2); color: #555555; cursor: pointer; display: inline-block; font-family: "Helvetica Neue", Arial, Verdana, "Nimbus Sans L", sans-serif; font-size: 13px; font-weight: 500; height: 31px; line-height: 28px; outline: none; padding: 0 13px; text-shadow: 0 1px 0 white; text-decoration: none; vertical-align: middle; white-space: nowrap; -webkit-font-smoothing: antialiased; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .button-blue { background: #1385e5; background: -webkit-linear-gradient(top, #53b2fc, #1385e5); background: -moz-linear-gradient(top, #53b2fc, #1385e5); background: -o-linear-gradient(top, #53b2fc, #1385e5); background: linear-gradient(to bottom, #53b2fc, #1385e5); border-color: #075fa9; color: white; font-weight: bold; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4); } /* Tweak navbar brand link to be super sleek -------------------------------------------------- */ .oss-bar { top: 0; right: 20px; position: fixed; z-index: 1030; } .oss-bar ul { float: right; margin: 0; list-style: none; } .oss-bar ul li { list-style: none; float: left; line-height: 0; margin: 0; } .oss-bar ul li a { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; border: 0; margin-top: -10px; display: block; height: 58px; background: #F36C00 url(oss-credit.png) no-repeat 20px 22px; padding: 22px 20px 12px 20px; text-indent: 120%; /* stupid padding */ white-space: nowrap; overflow: hidden; -webkit-transition: all 0.10s ease-in-out; -moz-transition: all 0.10s ease-in-out; transition: all 0.15s ease-in-out; } .oss-bar ul li a:hover { margin-top: 0px; } .oss-bar a.harvest { width: 196px; background-color: #F36C00; background-position: -142px 22px; padding-right: 22px; /* optical illusion */ } .oss-bar a.fork { width: 162px; background-color: #333333; } .docs-table th, .docs-table td { border: 1px solid #000; padding: 4px 6px; white-space: nowrap; } .docs-table td:last-child { white-space: normal; } .docs-table th { font-weight: bold; text-align: left; } #content pre[class*=language-] { font-size: 14px; margin-bottom: 20px; } #content pre[class*=language-] code { font-size: 14px; padding: 0; } #content code[class*=language-] { font-size: 12px; padding: 2px 4px; } .anchor { color: inherit; position: relative; } .anchor:hover { background: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSI3Ij48ZyBmaWxsPSIjNDE0MDQyIj48cGF0aCBkPSJNOS44IDdoLS45bC0uOS0uMWMtLjctLjMtMS40LS43LTEuOC0xLjMtLjItLjEtLjMtLjMtLjMtLjVsLS4zLS40Yy0uMS0uNC0uMi0uOC0uMi0xLjIgMC0uNC4xLS44LjItMS4yaDEuN2MtLjMuNC0uNC44LS40IDEuMiAwIC40LjEuOC4zIDEuMS4xLjIuMi4zLjQuNC4xLjEuMi4yLjQuMy4zLjIuNy4zIDEgLjNoMy40YzEuMiAwIDIuMi0uOSAyLjItMi4xcy0xLTIuMS0yLjItMi4xaC0xLjRjLS4zLS42LS43LTEtMS4yLTEuNGgyLjZjMiAwIDMuNiAxLjYgMy42IDMuNXMtMS42IDMuNS0zLjYgMy41aC0yLjZ6TTguNCAyYy0uMS0uMS0uMi0uMy0uNC0uMy0uMy0uMi0uNy0uMy0xLS4zaC0zLjRjLTEuMiAwLTIuMi45LTIuMiAyLjEgMCAxLjIgMSAyLjEgMi4yIDIuMWgxLjRjLjMuNS43IDEgMS4yIDEuNGgtMi42Yy0yIDAtMy42LTEuNi0zLjYtMy41czEuNi0zLjUgMy42LTMuNWgzLjUwMDAwMDAwMDAwMDAwMDRsLjkuMWMuNy4yIDEuNC43IDEuOCAxLjMuMS4xLjIuMy4zLjUuMS4xLjIuMy4yLjUuMS40LjIuOC4yIDEuMiAwIC40LS4xLjgtLjIgMS4yaC0xLjZjLjMtLjUuNC0uOS40LTEuM3MtLjEtLjgtLjMtMS4xYy0uMS0uMi0uMi0uMy0uNC0uNHoiLz48L2c+PC9zdmc+) 0 50% no-repeat; background-size: 21px 9px; margin-left: -27px; padding-left: 27px; text-decoration: none; } ================================================ FILE: public/packages/chosen_v1.0.0/index.html ================================================ Chosen: A jQuery Plugin by Harvest to Tame Unwieldy Select Boxes

            Chosen

            Chosen is a jQuery plugin that makes long, unwieldy select boxes much more user-friendly.

            Downloads Project Source Contribute

            Standard Select

            Turns This
            Into This

            Multiple Select

            Turns This
            Into This

            <optgroup> Support

            Single Select with Groups
            Multiple Select with Groups

            Selected and Disabled Support

            Chosen automatically highlights selected options and removes disabled options.

            Single Select
            Multiple Select

            Hide Search on Single Select

            The disable_search_threshold option can be specified to hide the search input on single selects if there are fewer than (n) options.

            $(".chosen-select").chosen({disable_search_threshold: 10});

            Default Text Support

            Chosen automatically sets the default field text ("Choose a country...") by reading the select element's data-placeholder value. If no data-placeholder value is present, it will default to "Select an Option" or "Select Some Options" depending on whether the select is single or multiple. You can change these elements in the plugin js file as you see fit.

            <select data-placeholder="Choose a country..." style="width:350px;" multiple class="chosen-select">

            Note: on single selects, the first element is assumed to be selected by the browser. To take advantage of the default text support, you will need to include a blank option as the first element of your select list.

            No Results Text Support

            Setting the "No results" search text is as easy as passing an option when you create Chosen:

             $(".chosen-select").chosen({no_results_text: "Oops, nothing found!"}); 

            Single Select
            Multiple Select

            Limit Selected Options in Multiselect

            You can easily limit how many options the user can select:

            $(".chosen-select").chosen({max_selected_options: 5});

            If you try to select another option with limit reached chosen:maxselected event is triggered:

             $(".chosen-select").bind("chosen:maxselected", function () { ... }); 

            Allow Deselect on Single Selects

            When a single select box isn't a required field, you can set allow_single_deselect: true and Chosen will add a UI element for option deselection. This will only work if the first option has blank text.

            Right to Left Support

            Chosen supports right to left select boxes too. just add "chosen-rtl" in addition to "chosen-select" to your select tags and you are good to go.

            <select class="chosen-select chosen-rtl">
            Single right to left select
            Multiple right to left select

            Change / Update Events

            • Form Field Change

              When working with form fields, you often want to perform some behavior after a value has been selected or deselected. Whenever a user selects a field in Chosen, it triggers a "change" event* on the original form field. That let's you do something like this:

              $("#form_field").chosen().change( … );
            • Updating Chosen Dynamically

              If you need to update the options in your select field and want Chosen to pick up the changes, you'll need to trigger the "chosen:updated" event on the field. Chosen will re-build itself based on the updated content.

              $("#form_field").trigger("chosen:updated");

            Custom Width Support

            Using a custom width with Chosen is as easy as passing an option when you create Chosen:

             $(".chosen-select").chosen({width: "95%"}); 
            Single Select
            Multiple Select

            Labels work, too

            Use labels just like you would a standard select

            Setup

            Using Chosen is easy as can be.

            1. Download the plugin and copy the chosen files to your app.
            2. Activate the plugin on the select boxes of your choice: $(".chosen-select").chosen()
            3. Disco.

            FAQs

            • Do you have all the available options documented somewhere?

              Yes! You can find them on the options page.

            • Something doesn't work. Can you fix it?

              Yes! Please report all issues using the GitHub issue tracking tool. Please include the plugin version (jQuery or Prototype), browser and OS. The more information provided, the easier it is to fix a problem.

            • What browsers are supported?

              All modern browsers are supported (Firefox, Chrome, Safari and IE9). Legacy support for IE8 is also enabled.

            • Didn't there used to be a Prototype version of Chosen?

              There still is!

            Credits

            ================================================ FILE: public/packages/chosen_v1.0.0/index.proto.html ================================================ Chosen: A Prototype Plugin by Harvest to Tame Unwieldy Select Boxes

            Chosen - Prototype Version

            Chosen is a Prototype plugin that makes long, unwieldy select boxes much more user-friendly.

            Downloads Project Source Contribute

            Looking for the jQuery version?

            Standard Select

            Turns This
            Into This

            Multiple Select

            Turns This
            Into This

            <optgroup> Support

            Single Select with Groups
            Multiple Select with Groups

            Selected and Disabled Support

            Chosen automatically highlights selected options and removes disabled options.

            Single Select
            Multiple Select

            Hide Search on Single Select

            The disable_search_threshold option can be specified to hide the search input on single selects if there are fewer than (n) options.

             new Chosen($("chosen_select_field"),{disable_search_threshold: 10}); 

            Default Text Support

            Chosen automatically sets the default field text ("Choose a country...") by reading the select element's data-placeholder value. If no data-placeholder value is present, it will default to "Select an Option" or "Select Some Options" depending on whether the select is single or multiple. You can change these elements in the plugin js file as you see fit.

            <select data-placeholder="Choose a country..." style="width:350px;" multiple class="chosen-select">

            Note: on single selects, the first element is assumed to be selected by the browser. To take advantage of the default text support, you will need to include a blank option as the first element of your select list.

            No Results Text Support

            Setting the "No results" search text is as easy as passing an option when you create Chosen:

            new Chosen($("chosen_select_field"),{no_results_text: "Oops, nothing found!"}); 
            Single Select
            Multiple Select

            Limit Selected Options in Multiselect

            You can easily limit how many options the user can select:

            new Chosen($("chosen_select_field"),{max_selected_options: 5}); 

            If you try to select another option with limit reached chosen:maxselected event is triggered:

            $("chosen_select_field").observe("chosen:maxselected", function(evt) { ... }); 

            Allow Deselect on Single Selects

            When a single select box isn't a required field, you can set allow_single_deselect: true and Chosen will add a UI element for option deselection. This will only work if the first option has blank text.

            Right to Left Support

            Chosen supports right to left select boxes too. just add "chosen-rtl" in addition to "chosen-select" to your select tags and you are good to go.

            <select class="chosen-select chosen-rtl">
            Single right to left select
            Multiple right to left select

            Change / Update Events

            • Form Field Change

              When working with form fields, you often want to perform some behavior after a value has been selected or deselected. Whenever a user selects a field in Chosen, it triggers a "change" event* on the original form field. That let's you do something like this:

              $("#form_field").chosen().change( … );

              Note: Prototype doesn't offer support for triggering standard browser events. Event.simulate is required to trigger the change event when using the Prototype version.

            • Updating Chosen Dynamically

              If you need to update the options in your select field and want Chosen to pick up the changes, you'll need to trigger the "chosen:updated" event on the field. Chosen will re-build itself based on the updated content.

                Event.fire($("form_field"), "chosen:updated");

            Custom Width Support

            Using a custom width with Chosen is as easy as passing an option when you create Chosen:

            new Chosen($("chosen_select_field"),{width: "95%"}); 
            Single Select
            Multiple Select

            Labels work, too

            Use labels just like you would a standard select

            Setup

            Using Chosen is easy as can be.

            1. Download the plugin and copy the chosen files to your app.
            2. Activate the plugin by creating a new instance of Chosen: New Chosen(some_form_field,some_options);
            3. Disco.

            FAQs

            ================================================ FILE: public/packages/chosen_v1.0.0/options.html ================================================ Chosen: A jQuery Plugin by Harvest to Tame Unwieldy Select Boxes

            Chosen

            Chosen has a number of options and attributes that allow you to have full control of your select boxes.

            Options

            The following options are available to pass into Chosen on instantiation.

            Example:

              $(".my_select_box").chosen(
                disable_search_threshold: 10,
                no_results_text: "Oops, nothing found!",
                width: "95%"
              );
            
            OptionDefaultDescription
            allow_single_deselect false When set to true on a single select, Chosen adds a UI element which selects the first elment (if it is blank).
            disable_search false When set to true, Chosen will not display the search field (single selects only).
            disable_search_threshold 0 Hide the search input on single selects if there are fewer than (n) options.
            enable_split_word_search true By default, searching will match on any word within an option tag. Set this option to false if you want to only match on the entire text of an option tag.
            inherit_select_classes false When set to true, Chosen will grab any classes on the original select field and add them to Chosen's container div.
            max_selected_options Infinity Limits how many options the user can select. When the limit is reached, the chosen:maxselected event is triggered.
            no_results_text "No results match" The text to be displayed when no matching results are found. The current search is shown at the end of the text (e.g. No reults match "Bad Search").
            placeholder_text_multiple "Select Some Options" The text to be displayed as a placeholder when no options are selected for a multiple select.
            placeholder_text_single "Select an Option" The text to be displayed as a placeholder when no options are selected for a single select.
            search_contains false By default, Chosen's search matches starting at the beginning of a word. Setting this option to true allows matches starting from anywhere within a word. This is especially useful for options that include a lot of special characters or phrases in ()'s and []'s.
            single_backstroke_delete true By default, pressing delete/backspace on multiple selects will remove a selected choice. When false, pressing delete/backspace will highlight the last choice, and a second press deselects it.
            width Original select width. The width of the Chosen select box. By default, Chosen attempts to match the width of the select box you are replacing. If your select is hidden when Chosen is instantiated, you must specify a width or the select will show up with a width of 0.
            display_disabled_options true By default, Chosen includes disabled options in search results with a special styling. Setting this option to false will hide disabled results and exclude them from searches.
            display_selected_options true

            By default, Chosen includes selected options in search results with a special styling. Setting this option to false will hide selected results and exclude them from searches.

            Note: this is for multiple selects only. In single selects, the selected result will always be displayed.

            Attributes

            Certain attributes placed on the select tag or its options can be used to configure Chosen.

            Example:

              <select class="my_select_box" data-placeholder="Select Your Options">
                <option value="1">Option 1</option>
                <option value="2" selected>Option 2</option>
                <option value="3" disabled>Option 3</option>
              </select>
            
            AttributeDescription
            data-placeholder

            The text to be displayed as a placeholder when no options are selected for a select. Defaults to "Select an Option" for single selects or "Select Some Options" for multiple selects.

            Note:This attribute overrides anything set in the placeholder_text_multiple or placeholder_text_single options.

            multiple The attribute multiple on your select box dictates whether Chosen will render a multiple or single select.
            selected, disabled Chosen automatically highlights selected options and disables disabled options.

            Classes

            Classes placed on the select tag can be used to configure Chosen.

            Example:

              <select class="my_select_box chosen-rtl">
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Option 3</option>
              </select>
            
            Classname Description
            chosen-rtl

            Chosen supports right-to-left text in select boxes. Add the class chosen-rtl to your select tag to support right-to-left text options.

            Note: The chosen-rtl class will pass through to the Chosen select even when the inherit_select_classes option is set to false.

            Events

            Chosen triggers a number of standard and custom events on the original select field.

            Example:

              $('select').on('change', function(evt, params) {
                do_something(evt, params);
              });
            
            EventDescription
            change

            Chosen triggers the standard DOM event whenever a selection is made (it also sends a selected or deselected parameter that tells you which option was changed).

            Note: in order to use change in the Prototype version, you have to include the Event.simulate class. The selected and deselected parameters are not available for Prototype.

            chosen:ready after Chosen has been fully instantiated (it also sends the chosen object as a parameter).
            chosen:maxselected triggered if max_selected_options is set and that total is broken. (it also sends the chosen object as a parameter)
            chosen:showing_dropdown triggered when Chosen's dropdown is opened (it also sends the chosen object as a parameter).
            chosen:hiding_dropdown triggered when Chosen's dropdown is closed (it also sends the chosen object as a parameter).
            ================================================ FILE: public/packages/codemirror-3.19/.gitattributes ================================================ *.txt text *.js text *.html text *.md text *.json text *.yml text *.css text *.svg text ================================================ FILE: public/packages/codemirror-3.19/.gitignore ================================================ /node_modules /npm-debug.log test.html .tern-* *~ *.swp ================================================ FILE: public/packages/codemirror-3.19/.travis.yml ================================================ language: node_js node_js: - 0.8 ================================================ FILE: public/packages/codemirror-3.19/AUTHORS ================================================ List of CodeMirror contributors. Updated before every release. 4r2r Aaron Brooks Adam King adanlobato Adán Lobato aeroson Ahmad Amireh Ahmad M. Zawawi ahoward Akeksandr Motsjonov Albert Xing Alexander Pavlov Alexander Schepanovski alexey-k Alex Piggott Amy Ananya Sen AndersMad Andre von Houck Andrey Lushnikov Andy Kimball Andy Li angelozerr angelo.zerr@gmail.com Ankit Ahuja Ansel Santosa Anthony Grimes areos Atul Bhouraskar Aurelian Oancea Bastian Müller benbro Benjamin DeCoste Ben Keen boomyjee borawjm Brandon Frohs Brett Zamir Brian Sletten Bruce Mitchener Chandra Sekhar Pydi Charles Skelton Chris Coyier Chris Granger Chris Morgan Christopher Brown ciaranj CodeAnimal ComFreek dagsta Dan Heberden Daniel, Dao Quang Minh Daniel Faust Daniel Huigens Daniel Neel Daniel Parnell Danny Yoo David Mignot David Pathakjee deebugger Deep Thought Dominator008 Domizio Demichelis Drew Bratcher Drew Hintz Drew Khoury Dror BG duralog edsharp ekhaled Eric Allam eustas Fauntleroy fbuchinger feizhang365 Felipe Lalanne Felix Raab Filip Noetzel flack ForbesLindesay Ford_Lawnmower Gabriel Nahmias galambalazs Gautam Mehta Glenn Jorde Glenn Ruehle Golevka Gordon Smith greengiant Guillaume Massé Guillaume Massé Hans Engel Hardest Hasan Karahan Hocdoc Ian Beck Ian Wehrman Ian Wetherbee Ice White ICHIKAWA, Yuji Ingo Richter Irakli Gozalishvili Ivan Kurnosov Jacob Lee Jakub Vrana James Campos James Thorne Jamie Hill Jan Jongboom jankeromnes Jan Keromnes Jan T. Sott Jason Jason Grout Jason Johnston Jason San Jose Jason Siefken Jean Boussier jeffkenton Jeff Pickhardt jem (graphite) Jochen Berger John Connor John Lees-Miller John Snelson jongalloway Joost-Wim Boekesteijn Joseph Pecoraro Joshua Newman jots Juan Benavides Romero Jucovschi Constantin jwallers@gmail.com kaniga Ken Newman Ken Rockot Kevin Sawicki Klaus Silveira Koh Zi Han, Cliff komakino Konstantin Lopuhin koops ks-ifware kubelsmieci Lanny leaf corcoran Leonya Khachaturov Liam Newman LM Lorenzo Stoakes lynschinzer Maksim Lin Maksym Taran Marat Dreizin Marco Aurélio Marijn Haverbeke Mario Pietsch Mark Lentczner Martin Balek Martín Gaitán Mason Malone Mateusz Paprocki mats cronqvist Matthew Beale Matthias BUSSONNIER Matt McDonald Matt Pass Matt Sacks Maximilian Hils Max Kirsch mbarkhau Metatheos Micah Dubinko Michael Lehenbauer Michael Zhou Mighty Guava Miguel Castillo Mike Mike Brevoort Mike Diaz Mike Ivanov Mike Kadin MinRK misfo mps Narciso Jaramillo Nathan Williams nerbert nguillaumin Niels van Groningen Nikita Beloglazov Nikita Vasilyev nlwillia pablo Page Patrick Strawderman Paul Garvin Paul Ivanov Pavel Feldman Paweł Bartkiewicz peteguhl peterkroon Peter Kroon prasanthj Prasanth J Rahul Randy Edmunds Richard Z.H. Wang robertop23 Robert Plummer Ruslan Osmanov sabaca Samuel Ainsworth sandeepshetty santec Sascha Peilicke satchmorun sathyamoorthi SCLINIC\jdecker shaund shaun gilchrist Shmuel Englard sonson spastorelli Stas Kobzar Stefan Borsje Steffen Beyer Steve O'Hara stoskov Tarmil tfjgeorge Thaddee Tyl think Thomas Dvornik Thomas Schmid Tim Baumann Timothy Farrell Timothy Hatcher TobiasBg Tomas-A Tomas Varaneckas Tom Erik Støwer Tom MacWright Tony Jian Vestimir Markov vf Volker Mische William Jamieson Wojtek Ptak Xavier Mendez Yunchi Luo Yuvi Panda Zachary Dremann ================================================ FILE: public/packages/codemirror-3.19/CONTRIBUTING.md ================================================ # How to contribute - [Getting help](#getting-help-) - [Submitting bug reports](#submitting-bug-reports-) - [Contributing code](#contributing-code-) ## Getting help Community discussion, questions, and informal bug reporting is done on the [CodeMirror Google group](http://groups.google.com/group/codemirror). ## Submitting bug reports The preferred way to report bugs is to use the [GitHub issue tracker](http://github.com/marijnh/CodeMirror/issues). Before reporting a bug, read these pointers. **Note:** The issue tracker is for *bugs*, not requests for help. Questions should be asked on the [CodeMirror Google group](http://groups.google.com/group/codemirror) instead. ### Reporting bugs effectively - 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. - 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. - 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. - 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. - 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](http://jsbin.com/ihunin/edit), enter it there, press save, and include the resulting link in your bug report. ## Contributing code - Make sure you have a [GitHub Account](https://github.com/signup/free) - Fork [CodeMirror](https://github.com/marijnh/CodeMirror/) ([how to fork a repo](https://help.github.com/articles/fork-a-repo)) - Make your changes - If your changes are easy to test or likely to regress, add tests. Tests for the core go into `test/test.js`, some modes have their own test suite under `mode/XXX/test.js`. Feel free to add new test suites to modes that don't have one yet (be sure to link the new tests into `test/index.html`). - Follow the general code style of the rest of the project (see below). Run `bin/lint` to verify that the linter is happy. - Make sure all tests pass. Visit `test/index.html` in your browser to run them. - Submit a pull request ([how to create a pull request](https://help.github.com/articles/fork-a-repo)) ### Coding standards - 2 spaces per indentation level, no tabs. - Include semicolons after statements. - Note that the linter (`bin/lint`) which is run after each commit complains about unused variables and functions. Prefix their names with an underscore to muffle it. ================================================ FILE: public/packages/codemirror-3.19/LICENSE ================================================ Copyright (C) 2013 by Marijn Haverbeke and others Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: public/packages/codemirror-3.19/README.md ================================================ # CodeMirror [![Build Status](https://secure.travis-ci.org/marijnh/CodeMirror.png?branch=master)](http://travis-ci.org/marijnh/CodeMirror) [![NPM version](https://badge.fury.io/js/codemirror.png)](http://badge.fury.io/js/codemirror) 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. The project page is http://codemirror.net The manual is at http://codemirror.net/doc/manual.html The contributing guidelines are in [CONTRIBUTING.md](https://github.com/marijnh/CodeMirror/blob/master/CONTRIBUTING.md) ================================================ FILE: public/packages/codemirror-3.19/addon/comment/comment.js ================================================ (function() { "use strict"; var noOptions = {}; var nonWS = /[^\s\u00a0]/; var Pos = CodeMirror.Pos; function firstNonWS(str) { var found = str.search(nonWS); return found == -1 ? 0 : found; } CodeMirror.commands.toggleComment = function(cm) { var from = cm.getCursor("start"), to = cm.getCursor("end"); cm.uncomment(from, to) || cm.lineComment(from, to); }; CodeMirror.defineExtension("lineComment", function(from, to, options) { if (!options) options = noOptions; var self = this, mode = self.getModeAt(from); var commentString = options.lineComment || mode.lineComment; if (!commentString) { if (options.blockCommentStart || mode.blockCommentStart) { options.fullLines = true; self.blockComment(from, to, options); } return; } var firstLine = self.getLine(from.line); if (firstLine == null) return; var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1); var pad = options.padding == null ? " " : options.padding; var blankLines = options.commentBlankLines || from.line == to.line; self.operation(function() { if (options.indent) { var baseString = firstLine.slice(0, firstNonWS(firstLine)); for (var i = from.line; i < end; ++i) { var line = self.getLine(i), cut = baseString.length; if (!blankLines && !nonWS.test(line)) continue; if (line.slice(0, cut) != baseString) cut = firstNonWS(line); self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut)); } } else { for (var i = from.line; i < end; ++i) { if (blankLines || nonWS.test(self.getLine(i))) self.replaceRange(commentString + pad, Pos(i, 0)); } } }); }); CodeMirror.defineExtension("blockComment", function(from, to, options) { if (!options) options = noOptions; var self = this, mode = self.getModeAt(from); var startString = options.blockCommentStart || mode.blockCommentStart; var endString = options.blockCommentEnd || mode.blockCommentEnd; if (!startString || !endString) { if ((options.lineComment || mode.lineComment) && options.fullLines != false) self.lineComment(from, to, options); return; } var end = Math.min(to.line, self.lastLine()); if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end; var pad = options.padding == null ? " " : options.padding; if (from.line > end) return; self.operation(function() { if (options.fullLines != false) { var lastLineHasText = nonWS.test(self.getLine(end)); self.replaceRange(pad + endString, Pos(end)); self.replaceRange(startString + pad, Pos(from.line, 0)); var lead = options.blockCommentLead || mode.blockCommentLead; if (lead != null) for (var i = from.line + 1; i <= end; ++i) if (i != end || lastLineHasText) self.replaceRange(lead + pad, Pos(i, 0)); } else { self.replaceRange(endString, to); self.replaceRange(startString, from); } }); }); CodeMirror.defineExtension("uncomment", function(from, to, options) { if (!options) options = noOptions; var self = this, mode = self.getModeAt(from); var end = Math.min(to.line, self.lastLine()), start = Math.min(from.line, end); // Try finding line comments var lineString = options.lineComment || mode.lineComment, lines = []; var pad = options.padding == null ? " " : options.padding, didSomething; lineComment: { if (!lineString) break lineComment; for (var i = start; i <= end; ++i) { var line = self.getLine(i); var found = line.indexOf(lineString); if (found == -1 && (i != end || i == start) && nonWS.test(line)) break lineComment; if (i != start && found > -1 && nonWS.test(line.slice(0, found))) break lineComment; lines.push(line); } self.operation(function() { for (var i = start; i <= end; ++i) { var line = lines[i - start]; var pos = line.indexOf(lineString), endPos = pos + lineString.length; if (pos < 0) continue; if (line.slice(endPos, endPos + pad.length) == pad) endPos += pad.length; didSomething = true; self.replaceRange("", Pos(i, pos), Pos(i, endPos)); } }); if (didSomething) return true; } // Try block comments var startString = options.blockCommentStart || mode.blockCommentStart; var endString = options.blockCommentEnd || mode.blockCommentEnd; if (!startString || !endString) return false; var lead = options.blockCommentLead || mode.blockCommentLead; var startLine = self.getLine(start), endLine = end == start ? startLine : self.getLine(end); var open = startLine.indexOf(startString), close = endLine.lastIndexOf(endString); if (close == -1 && start != end) { endLine = self.getLine(--end); close = endLine.lastIndexOf(endString); } if (open == -1 || close == -1) return false; self.operation(function() { self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)), Pos(end, close + endString.length)); var openEnd = open + startString.length; if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length; self.replaceRange("", Pos(start, open), Pos(start, openEnd)); if (lead) for (var i = start + 1; i <= end; ++i) { var line = self.getLine(i), found = line.indexOf(lead); if (found == -1 || nonWS.test(line.slice(0, found))) continue; var foundEnd = found + lead.length; if (pad && line.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length; self.replaceRange("", Pos(i, found), Pos(i, foundEnd)); } }); return true; }); })(); ================================================ FILE: public/packages/codemirror-3.19/addon/comment/continuecomment.js ================================================ (function() { var modes = ["clike", "css", "javascript"]; for (var i = 0; i < modes.length; ++i) CodeMirror.extendMode(modes[i], {blockCommentContinue: " * "}); function continueComment(cm) { var pos = cm.getCursor(), token = cm.getTokenAt(pos); if (token.type != "comment") return CodeMirror.Pass; var mode = CodeMirror.innerMode(cm.getMode(), token.state).mode; var insert; if (mode.blockCommentStart && mode.blockCommentContinue) { var end = token.string.indexOf(mode.blockCommentEnd); var full = cm.getRange(CodeMirror.Pos(pos.line, 0), CodeMirror.Pos(pos.line, token.end)), found; if (end != -1 && end == token.string.length - mode.blockCommentEnd.length) { // Comment ended, don't continue it } else if (token.string.indexOf(mode.blockCommentStart) == 0) { insert = full.slice(0, token.start); if (!/^\s*$/.test(insert)) { insert = ""; for (var i = 0; i < token.start; ++i) insert += " "; } } else if ((found = full.indexOf(mode.blockCommentContinue)) != -1 && found + mode.blockCommentContinue.length > token.start && /^\s*$/.test(full.slice(0, found))) { insert = full.slice(0, found); } if (insert != null) insert += mode.blockCommentContinue; } if (insert == null && mode.lineComment) { var line = cm.getLine(pos.line), found = line.indexOf(mode.lineComment); if (found > -1) { insert = line.slice(0, found); if (/\S/.test(insert)) insert = null; else insert += mode.lineComment + line.slice(found + mode.lineComment.length).match(/^\s*/)[0]; } } if (insert != null) cm.replaceSelection("\n" + insert, "end"); else return CodeMirror.Pass; } CodeMirror.defineOption("continueComments", null, function(cm, val, prev) { if (prev && prev != CodeMirror.Init) cm.removeKeyMap("continueComment"); if (val) { var map = {name: "continueComment"}; map[typeof val == "string" ? val : "Enter"] = continueComment; cm.addKeyMap(map); } }); })(); ================================================ FILE: public/packages/codemirror-3.19/addon/dialog/dialog.css ================================================ .CodeMirror-dialog { position: absolute; left: 0; right: 0; background: white; z-index: 15; padding: .1em .8em; overflow: hidden; color: #333; } .CodeMirror-dialog-top { border-bottom: 1px solid #eee; top: 0; } .CodeMirror-dialog-bottom { border-top: 1px solid #eee; bottom: 0; } .CodeMirror-dialog input { border: none; outline: none; background: transparent; width: 20em; color: inherit; font-family: monospace; } .CodeMirror-dialog button { font-size: 70%; } ================================================ FILE: public/packages/codemirror-3.19/addon/dialog/dialog.js ================================================ // Open simple dialogs on top of an editor. Relies on dialog.css. (function() { function dialogDiv(cm, template, bottom) { var wrap = cm.getWrapperElement(); var dialog; dialog = wrap.appendChild(document.createElement("div")); if (bottom) { dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom"; } else { dialog.className = "CodeMirror-dialog CodeMirror-dialog-top"; } dialog.innerHTML = template; return dialog; } CodeMirror.defineExtension("openDialog", function(template, callback, options) { var dialog = dialogDiv(this, template, options && options.bottom); var closed = false, me = this; function close() { if (closed) return; closed = true; dialog.parentNode.removeChild(dialog); } var inp = dialog.getElementsByTagName("input")[0], button; if (inp) { CodeMirror.on(inp, "keydown", function(e) { if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; } if (e.keyCode == 13 || e.keyCode == 27) { CodeMirror.e_stop(e); close(); me.focus(); if (e.keyCode == 13) callback(inp.value); } }); if (options && options.onKeyUp) { CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);}); } if (options && options.value) inp.value = options.value; inp.focus(); CodeMirror.on(inp, "blur", close); } else if (button = dialog.getElementsByTagName("button")[0]) { CodeMirror.on(button, "click", function() { close(); me.focus(); }); button.focus(); CodeMirror.on(button, "blur", close); } return close; }); CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) { var dialog = dialogDiv(this, template, options && options.bottom); var buttons = dialog.getElementsByTagName("button"); var closed = false, me = this, blurring = 1; function close() { if (closed) return; closed = true; dialog.parentNode.removeChild(dialog); me.focus(); } buttons[0].focus(); for (var i = 0; i < buttons.length; ++i) { var b = buttons[i]; (function(callback) { CodeMirror.on(b, "click", function(e) { CodeMirror.e_preventDefault(e); close(); if (callback) callback(me); }); })(callbacks[i]); CodeMirror.on(b, "blur", function() { --blurring; setTimeout(function() { if (blurring <= 0) close(); }, 200); }); CodeMirror.on(b, "focus", function() { ++blurring; }); } }); })(); ================================================ FILE: public/packages/codemirror-3.19/addon/display/fullscreen.css ================================================ .CodeMirror-fullscreen { position: fixed; top: 0; left: 0; right: 0; bottom: 0; height: auto; z-index: 9; } ================================================ FILE: public/packages/codemirror-3.19/addon/display/fullscreen.js ================================================ (function() { "use strict"; CodeMirror.defineOption("fullScreen", false, function(cm, val, old) { if (old == CodeMirror.Init) old = false; if (!old == !val) return; if (val) setFullscreen(cm); else setNormal(cm); }); function setFullscreen(cm) { var wrap = cm.getWrapperElement(); cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset, width: wrap.style.width, height: wrap.style.height}; wrap.style.width = wrap.style.height = ""; wrap.className += " CodeMirror-fullscreen"; document.documentElement.style.overflow = "hidden"; cm.refresh(); } function setNormal(cm) { var wrap = cm.getWrapperElement(); wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, ""); document.documentElement.style.overflow = ""; var info = cm.state.fullScreenRestore; wrap.style.width = info.width; wrap.style.height = info.height; window.scrollTo(info.scrollLeft, info.scrollTop); cm.refresh(); } })(); ================================================ FILE: public/packages/codemirror-3.19/addon/display/placeholder.js ================================================ (function() { CodeMirror.defineOption("placeholder", "", function(cm, val, old) { var prev = old && old != CodeMirror.Init; if (val && !prev) { cm.on("focus", onFocus); cm.on("blur", onBlur); cm.on("change", onChange); onChange(cm); } else if (!val && prev) { cm.off("focus", onFocus); cm.off("blur", onBlur); cm.off("change", onChange); clearPlaceholder(cm); var wrapper = cm.getWrapperElement(); wrapper.className = wrapper.className.replace(" CodeMirror-empty", ""); } if (val && !cm.hasFocus()) onBlur(cm); }); function clearPlaceholder(cm) { if (cm.state.placeholder) { cm.state.placeholder.parentNode.removeChild(cm.state.placeholder); cm.state.placeholder = null; } } function setPlaceholder(cm) { clearPlaceholder(cm); var elt = cm.state.placeholder = document.createElement("pre"); elt.style.cssText = "height: 0; overflow: visible"; elt.className = "CodeMirror-placeholder"; elt.appendChild(document.createTextNode(cm.getOption("placeholder"))); cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild); } function onFocus(cm) { clearPlaceholder(cm); } function onBlur(cm) { if (isEmpty(cm)) setPlaceholder(cm); } function onChange(cm) { var wrapper = cm.getWrapperElement(), empty = isEmpty(cm); wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : ""); if (cm.hasFocus()) return; if (empty) setPlaceholder(cm); else clearPlaceholder(cm); } function isEmpty(cm) { return (cm.lineCount() === 1) && (cm.getLine(0) === ""); } })(); ================================================ FILE: public/packages/codemirror-3.19/addon/edit/closebrackets.js ================================================ (function() { var DEFAULT_BRACKETS = "()[]{}''\"\""; var DEFAULT_EXPLODE_ON_ENTER = "[]{}"; var SPACE_CHAR_REGEX = /\s/; CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) { if (old != CodeMirror.Init && old) cm.removeKeyMap("autoCloseBrackets"); if (!val) return; var pairs = DEFAULT_BRACKETS, explode = DEFAULT_EXPLODE_ON_ENTER; if (typeof val == "string") pairs = val; else if (typeof val == "object") { if (val.pairs != null) pairs = val.pairs; if (val.explode != null) explode = val.explode; } var map = buildKeymap(pairs); if (explode) map.Enter = buildExplodeHandler(explode); cm.addKeyMap(map); }); function charsAround(cm, pos) { var str = cm.getRange(CodeMirror.Pos(pos.line, pos.ch - 1), CodeMirror.Pos(pos.line, pos.ch + 1)); return str.length == 2 ? str : null; } function buildKeymap(pairs) { var map = { name : "autoCloseBrackets", Backspace: function(cm) { if (cm.somethingSelected()) return CodeMirror.Pass; var cur = cm.getCursor(), around = charsAround(cm, cur); if (around && pairs.indexOf(around) % 2 == 0) cm.replaceRange("", CodeMirror.Pos(cur.line, cur.ch - 1), CodeMirror.Pos(cur.line, cur.ch + 1)); else return CodeMirror.Pass; } }; var closingBrackets = ""; for (var i = 0; i < pairs.length; i += 2) (function(left, right) { if (left != right) closingBrackets += right; function surround(cm) { var selection = cm.getSelection(); cm.replaceSelection(left + selection + right); } function maybeOverwrite(cm) { var cur = cm.getCursor(), ahead = cm.getRange(cur, CodeMirror.Pos(cur.line, cur.ch + 1)); if (ahead != right || cm.somethingSelected()) return CodeMirror.Pass; else cm.execCommand("goCharRight"); } map["'" + left + "'"] = function(cm) { if (left == "'" && cm.getTokenAt(cm.getCursor()).type == "comment") return CodeMirror.Pass; if (cm.somethingSelected()) return surround(cm); if (left == right && maybeOverwrite(cm) != CodeMirror.Pass) return; var cur = cm.getCursor(), ahead = CodeMirror.Pos(cur.line, cur.ch + 1); var line = cm.getLine(cur.line), nextChar = line.charAt(cur.ch), curChar = cur.ch > 0 ? line.charAt(cur.ch - 1) : ""; if (left == right && CodeMirror.isWordChar(curChar)) return CodeMirror.Pass; if (line.length == cur.ch || closingBrackets.indexOf(nextChar) >= 0 || SPACE_CHAR_REGEX.test(nextChar)) cm.replaceSelection(left + right, {head: ahead, anchor: ahead}); else return CodeMirror.Pass; }; if (left != right) map["'" + right + "'"] = maybeOverwrite; })(pairs.charAt(i), pairs.charAt(i + 1)); return map; } function buildExplodeHandler(pairs) { return function(cm) { var cur = cm.getCursor(), around = charsAround(cm, cur); if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass; cm.operation(function() { var newPos = CodeMirror.Pos(cur.line + 1, 0); cm.replaceSelection("\n\n", {anchor: newPos, head: newPos}, "+input"); cm.indentLine(cur.line + 1, null, true); cm.indentLine(cur.line + 2, null, true); }); }; } })(); ================================================ FILE: public/packages/codemirror-3.19/addon/edit/closetag.js ================================================ /** * Tag-closer extension for CodeMirror. * * This extension adds an "autoCloseTags" option that can be set to * either true to get the default behavior, or an object to further * configure its behavior. * * These are supported options: * * `whenClosing` (default true) * Whether to autoclose when the '/' of a closing tag is typed. * `whenOpening` (default true) * Whether to autoclose the tag when the final '>' of an opening * tag is typed. * `dontCloseTags` (default is empty tags for HTML, none for XML) * An array of tag names that should not be autoclosed. * `indentTags` (default is block tags for HTML, none for XML) * An array of tag names that should, when opened, cause a * blank line to be added inside the tag, and the blank line and * closing line to be indented. * * See demos/closetag.html for a usage example. */ (function() { CodeMirror.defineOption("autoCloseTags", false, function(cm, val, old) { if (val && (old == CodeMirror.Init || !old)) { var map = {name: "autoCloseTags"}; if (typeof val != "object" || val.whenClosing) map["'/'"] = function(cm) { return autoCloseSlash(cm); }; if (typeof val != "object" || val.whenOpening) map["'>'"] = function(cm) { return autoCloseGT(cm); }; cm.addKeyMap(map); } else if (!val && (old != CodeMirror.Init && old)) { cm.removeKeyMap("autoCloseTags"); } }); var htmlDontClose = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]; var htmlIndent = ["applet", "blockquote", "body", "button", "div", "dl", "fieldset", "form", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "html", "iframe", "layer", "legend", "object", "ol", "p", "select", "table", "ul"]; function autoCloseGT(cm) { var pos = cm.getCursor(), tok = cm.getTokenAt(pos); var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state; if (inner.mode.name != "xml" || !state.tagName) return CodeMirror.Pass; var opt = cm.getOption("autoCloseTags"), html = inner.mode.configuration == "html"; var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose); var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent); var tagName = state.tagName; if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch); var lowerTagName = tagName.toLowerCase(); // Don't process the '>' at the end of an end-tag or self-closing tag if (tok.type == "tag" && state.type == "closeTag" || tok.string.indexOf("/") == (tok.string.length - 1) || // match something like dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1) return CodeMirror.Pass; var doIndent = indentTags && indexOf(indentTags, lowerTagName) > -1; var curPos = doIndent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1); cm.replaceSelection(">" + (doIndent ? "\n\n" : "") + "", {head: curPos, anchor: curPos}); if (doIndent) { cm.indentLine(pos.line + 1); cm.indentLine(pos.line + 2); } } function autoCloseSlash(cm) { var pos = cm.getCursor(), tok = cm.getTokenAt(pos); var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state; if (tok.string.charAt(0) != "<" || tok.start != pos.ch - 1 || inner.mode.name != "xml") return CodeMirror.Pass; var tagName = state.context && state.context.tagName; if (tagName) cm.replaceSelection("/" + tagName + ">", "end"); } function indexOf(collection, elt) { if (collection.indexOf) return collection.indexOf(elt); for (var i = 0, e = collection.length; i < e; ++i) if (collection[i] == elt) return i; return -1; } })(); ================================================ FILE: public/packages/codemirror-3.19/addon/edit/continuelist.js ================================================ (function() { 'use strict'; var listRE = /^(\s*)([*+-]|(\d+)\.)(\s*)/, unorderedBullets = '*+-'; CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) { var pos = cm.getCursor(), inList = cm.getStateAfter(pos.line).list !== false, match; if (!inList || !(match = cm.getLine(pos.line).match(listRE))) { cm.execCommand('newlineAndIndent'); return; } var indent = match[1], after = match[4]; var bullet = unorderedBullets.indexOf(match[2]) >= 0 ? match[2] : (parseInt(match[3], 10) + 1) + '.'; cm.replaceSelection('\n' + indent + bullet + after, 'end'); }; }()); ================================================ FILE: public/packages/codemirror-3.19/addon/edit/matchbrackets.js ================================================ (function() { var ie_lt8 = /MSIE \d/.test(navigator.userAgent) && (document.documentMode == null || document.documentMode < 8); var Pos = CodeMirror.Pos; var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"}; function findMatchingBracket(cm, where, strict) { var state = cm.state.matchBrackets; var maxScanLen = (state && state.maxScanLineLength) || 10000; var cur = where || cm.getCursor(), line = cm.getLineHandle(cur.line), pos = cur.ch - 1; var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)]; if (!match) return null; var forward = match.charAt(1) == ">", d = forward ? 1 : -1; if (strict && forward != (pos == cur.ch)) return null; var style = cm.getTokenTypeAt(Pos(cur.line, pos + 1)); var stack = [line.text.charAt(pos)], re = /[(){}[\]]/; function scan(line, lineNo, start) { if (!line.text) return; var pos = forward ? 0 : line.text.length - 1, end = forward ? line.text.length : -1; if (line.text.length > maxScanLen) return null; if (start != null) pos = start + d; for (; pos != end; pos += d) { var ch = line.text.charAt(pos); if (re.test(ch) && cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style) { var match = matching[ch]; if (match.charAt(1) == ">" == forward) stack.push(ch); else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false}; else if (!stack.length) return {pos: pos, match: true}; } } } for (var i = cur.line, found, e = forward ? Math.min(i + 100, cm.lineCount()) : Math.max(-1, i - 100); i != e; i+=d) { if (i == cur.line) found = scan(line, i, pos); else found = scan(cm.getLineHandle(i), i); if (found) break; } return {from: Pos(cur.line, pos), to: found && Pos(i, found.pos), match: found && found.match, forward: forward}; } function matchBrackets(cm, autoclear) { // Disable brace matching in long lines, since it'll cause hugely slow updates var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000; var found = findMatchingBracket(cm); if (!found || cm.getLine(found.from.line).length > maxHighlightLen || found.to && cm.getLine(found.to.line).length > maxHighlightLen) return; var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; var one = cm.markText(found.from, Pos(found.from.line, found.from.ch + 1), {className: style}); var two = found.to && cm.markText(found.to, Pos(found.to.line, found.to.ch + 1), {className: style}); // Kludge to work around the IE bug from issue #1193, where text // input stops going to the textare whever this fires. if (ie_lt8 && cm.state.focused) cm.display.input.focus(); var clear = function() { cm.operation(function() { one.clear(); two && two.clear(); }); }; if (autoclear) setTimeout(clear, 800); else return clear; } var currentlyHighlighted = null; function doMatchBrackets(cm) { cm.operation(function() { if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;} if (!cm.somethingSelected()) currentlyHighlighted = matchBrackets(cm, false); }); } CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) { if (old && old != CodeMirror.Init) cm.off("cursorActivity", doMatchBrackets); if (val) { cm.state.matchBrackets = typeof val == "object" ? val : {}; cm.on("cursorActivity", doMatchBrackets); } }); CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);}); CodeMirror.defineExtension("findMatchingBracket", function(pos, strict){ return findMatchingBracket(this, pos, strict); }); })(); ================================================ FILE: public/packages/codemirror-3.19/addon/edit/matchtags.js ================================================ (function() { "use strict"; CodeMirror.defineOption("matchTags", false, function(cm, val, old) { if (old && old != CodeMirror.Init) { cm.off("cursorActivity", doMatchTags); cm.off("viewportChange", maybeUpdateMatch); clear(cm); } if (val) { cm.state.matchBothTags = typeof val == "object" && val.bothTags; cm.on("cursorActivity", doMatchTags); cm.on("viewportChange", maybeUpdateMatch); doMatchTags(cm); } }); function clear(cm) { if (cm.state.tagHit) cm.state.tagHit.clear(); if (cm.state.tagOther) cm.state.tagOther.clear(); cm.state.tagHit = cm.state.tagOther = null; } function doMatchTags(cm) { cm.state.failedTagMatch = false; cm.operation(function() { clear(cm); if (cm.somethingSelected()) return; var cur = cm.getCursor(), range = cm.getViewport(); range.from = Math.min(range.from, cur.line); range.to = Math.max(cur.line + 1, range.to); var match = CodeMirror.findMatchingTag(cm, cur, range); if (!match) return; if (cm.state.matchBothTags) { var hit = match.at == "open" ? match.open : match.close; if (hit) cm.state.tagHit = cm.markText(hit.from, hit.to, {className: "CodeMirror-matchingtag"}); } var other = match.at == "close" ? match.open : match.close; if (other) cm.state.tagOther = cm.markText(other.from, other.to, {className: "CodeMirror-matchingtag"}); else cm.state.failedTagMatch = true; }); } function maybeUpdateMatch(cm) { if (cm.state.failedTagMatch) doMatchTags(cm); } CodeMirror.commands.toMatchingTag = function(cm) { var found = CodeMirror.findMatchingTag(cm, cm.getCursor()); if (found) { var other = found.at == "close" ? found.open : found.close; if (other) cm.setSelection(other.to, other.from); } }; })(); ================================================ FILE: public/packages/codemirror-3.19/addon/edit/trailingspace.js ================================================ CodeMirror.defineOption("showTrailingSpace", false, function(cm, val, prev) { if (prev == CodeMirror.Init) prev = false; if (prev && !val) cm.removeOverlay("trailingspace"); else if (!prev && val) cm.addOverlay({ token: function(stream) { for (var l = stream.string.length, i = l; i && /\s/.test(stream.string.charAt(i - 1)); --i) {} if (i > stream.pos) { stream.pos = i; return null; } stream.pos = l; return "trailingspace"; }, name: "trailingspace" }); }); ================================================ FILE: public/packages/codemirror-3.19/addon/fold/brace-fold.js ================================================ CodeMirror.registerHelper("fold", "brace", function(cm, start) { var line = start.line, lineText = cm.getLine(line); var startCh, tokenType; function findOpening(openCh) { for (var at = start.ch, pass = 0;;) { var found = at <= 0 ? -1 : lineText.lastIndexOf(openCh, at - 1); if (found == -1) { if (pass == 1) break; pass = 1; at = lineText.length; continue; } if (pass == 1 && found < start.ch) break; tokenType = cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1)); if (!/^(comment|string)/.test(tokenType)) return found + 1; at = found - 1; } } var startToken = "{", endToken = "}", startCh = findOpening("{"); if (startCh == null) { startToken = "[", endToken = "]"; startCh = findOpening("["); } if (startCh == null) return; var count = 1, lastLine = cm.lastLine(), end, endCh; outer: for (var i = line; i <= lastLine; ++i) { var text = cm.getLine(i), pos = i == line ? startCh : 0; for (;;) { var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos); if (nextOpen < 0) nextOpen = text.length; if (nextClose < 0) nextClose = text.length; pos = Math.min(nextOpen, nextClose); if (pos == text.length) break; if (cm.getTokenTypeAt(CodeMirror.Pos(i, pos + 1)) == tokenType) { if (pos == nextOpen) ++count; else if (!--count) { end = i; endCh = pos; break outer; } } ++pos; } } if (end == null || line == end && endCh == startCh) return; return {from: CodeMirror.Pos(line, startCh), to: CodeMirror.Pos(end, endCh)}; }); CodeMirror.braceRangeFinder = CodeMirror.fold.brace; // deprecated CodeMirror.registerHelper("fold", "import", function(cm, start) { function hasImport(line) { if (line < cm.firstLine() || line > cm.lastLine()) return null; var start = cm.getTokenAt(CodeMirror.Pos(line, 1)); if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1)); if (start.type != "keyword" || start.string != "import") return null; // Now find closing semicolon, return its position for (var i = line, e = Math.min(cm.lastLine(), line + 10); i <= e; ++i) { var text = cm.getLine(i), semi = text.indexOf(";"); if (semi != -1) return {startCh: start.end, end: CodeMirror.Pos(i, semi)}; } } var start = start.line, has = hasImport(start), prev; if (!has || hasImport(start - 1) || ((prev = hasImport(start - 2)) && prev.end.line == start - 1)) return null; for (var end = has.end;;) { var next = hasImport(end.line + 1); if (next == null) break; end = next.end; } return {from: cm.clipPos(CodeMirror.Pos(start, has.startCh + 1)), to: end}; }); CodeMirror.importRangeFinder = CodeMirror.fold["import"]; // deprecated CodeMirror.registerHelper("fold", "include", function(cm, start) { function hasInclude(line) { if (line < cm.firstLine() || line > cm.lastLine()) return null; var start = cm.getTokenAt(CodeMirror.Pos(line, 1)); if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1)); if (start.type == "meta" && start.string.slice(0, 8) == "#include") return start.start + 8; } var start = start.line, has = hasInclude(start); if (has == null || hasInclude(start - 1) != null) return null; for (var end = start;;) { var next = hasInclude(end + 1); if (next == null) break; ++end; } return {from: CodeMirror.Pos(start, has + 1), to: cm.clipPos(CodeMirror.Pos(end))}; }); CodeMirror.includeRangeFinder = CodeMirror.fold.include; // deprecated ================================================ FILE: public/packages/codemirror-3.19/addon/fold/comment-fold.js ================================================ CodeMirror.registerHelper("fold", "comment", function(cm, start) { var mode = cm.getModeAt(start), startToken = mode.blockCommentStart, endToken = mode.blockCommentEnd; if (!startToken || !endToken) return; var line = start.line, lineText = cm.getLine(line); var startCh; for (var at = start.ch, pass = 0;;) { var found = at <= 0 ? -1 : lineText.lastIndexOf(startToken, at - 1); if (found == -1) { if (pass == 1) return; pass = 1; at = lineText.length; continue; } if (pass == 1 && found < start.ch) return; if (/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1)))) { startCh = found + startToken.length; break; } at = found - 1; } var depth = 1, lastLine = cm.lastLine(), end, endCh; outer: for (var i = line; i <= lastLine; ++i) { var text = cm.getLine(i), pos = i == line ? startCh : 0; for (;;) { var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos); if (nextOpen < 0) nextOpen = text.length; if (nextClose < 0) nextClose = text.length; pos = Math.min(nextOpen, nextClose); if (pos == text.length) break; if (pos == nextOpen) ++depth; else if (!--depth) { end = i; endCh = pos; break outer; } ++pos; } } if (end == null || line == end && endCh == startCh) return; return {from: CodeMirror.Pos(line, startCh), to: CodeMirror.Pos(end, endCh)}; }); ================================================ FILE: public/packages/codemirror-3.19/addon/fold/foldcode.js ================================================ (function() { "use strict"; function doFold(cm, pos, options, force) { var finder = options && (options.call ? options : options.rangeFinder); if (!finder) finder = cm.getHelper(pos, "fold"); if (!finder) return; if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0); var minSize = options && options.minFoldSize || 0; function getRange(allowFolded) { var range = finder(cm, pos); if (!range || range.to.line - range.from.line < minSize) return null; var marks = cm.findMarksAt(range.from); for (var i = 0; i < marks.length; ++i) { if (marks[i].__isFold && force !== "fold") { if (!allowFolded) return null; range.cleared = true; marks[i].clear(); } } return range; } var range = getRange(true); if (options && options.scanUp) while (!range && pos.line > cm.firstLine()) { pos = CodeMirror.Pos(pos.line - 1, 0); range = getRange(false); } if (!range || range.cleared || force === "unfold") return; var myWidget = makeWidget(options); CodeMirror.on(myWidget, "mousedown", function() { myRange.clear(); }); var myRange = cm.markText(range.from, range.to, { replacedWith: myWidget, clearOnEnter: true, __isFold: true }); myRange.on("clear", function(from, to) { CodeMirror.signal(cm, "unfold", cm, from, to); }); CodeMirror.signal(cm, "fold", cm, range.from, range.to); } function makeWidget(options) { var widget = (options && options.widget) || "\u2194"; if (typeof widget == "string") { var text = document.createTextNode(widget); widget = document.createElement("span"); widget.appendChild(text); widget.className = "CodeMirror-foldmarker"; } return widget; } // Clumsy backwards-compatible interface CodeMirror.newFoldFunction = function(rangeFinder, widget) { return function(cm, pos) { doFold(cm, pos, {rangeFinder: rangeFinder, widget: widget}); }; }; // New-style interface CodeMirror.defineExtension("foldCode", function(pos, options, force) { doFold(this, pos, options, force); }); CodeMirror.registerHelper("fold", "combine", function() { var funcs = Array.prototype.slice.call(arguments, 0); return function(cm, start) { for (var i = 0; i < funcs.length; ++i) { var found = funcs[i](cm, start); if (found) return found; } }; }); })(); ================================================ FILE: public/packages/codemirror-3.19/addon/fold/foldgutter.css ================================================ .CodeMirror-foldmarker { color: blue; text-shadow: #b9f 1px 1px 2px, #b9f -1px -1px 2px, #b9f 1px -1px 2px, #b9f -1px 1px 2px; font-family: arial; line-height: .3; cursor: pointer; } .CodeMirror-foldgutter { width: .7em; } .CodeMirror-foldgutter-open, .CodeMirror-foldgutter-folded { color: #555; cursor: pointer; } .CodeMirror-foldgutter-open:after { content: "\25BE"; } .CodeMirror-foldgutter-folded:after { content: "\25B8"; } ================================================ FILE: public/packages/codemirror-3.19/addon/fold/foldgutter.js ================================================ (function() { "use strict"; CodeMirror.defineOption("foldGutter", false, function(cm, val, old) { if (old && old != CodeMirror.Init) { cm.clearGutter(cm.state.foldGutter.options.gutter); cm.state.foldGutter = null; cm.off("gutterClick", onGutterClick); cm.off("change", onChange); cm.off("viewportChange", onViewportChange); cm.off("fold", onFold); cm.off("unfold", onFold); cm.off("swapDoc", updateInViewport); } if (val) { cm.state.foldGutter = new State(parseOptions(val)); updateInViewport(cm); cm.on("gutterClick", onGutterClick); cm.on("change", onChange); cm.on("viewportChange", onViewportChange); cm.on("fold", onFold); cm.on("unfold", onFold); cm.on("swapDoc", updateInViewport); } }); var Pos = CodeMirror.Pos; function State(options) { this.options = options; this.from = this.to = 0; } function parseOptions(opts) { if (opts === true) opts = {}; if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter"; if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open"; if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded"; return opts; } function isFolded(cm, line) { var marks = cm.findMarksAt(Pos(line)); for (var i = 0; i < marks.length; ++i) if (marks[i].__isFold && marks[i].find().from.line == line) return true; } function marker(spec) { if (typeof spec == "string") { var elt = document.createElement("div"); elt.className = spec; return elt; } else { return spec.cloneNode(true); } } function updateFoldInfo(cm, from, to) { var opts = cm.state.foldGutter.options, cur = from; cm.eachLine(from, to, function(line) { var mark = null; if (isFolded(cm, cur)) { mark = marker(opts.indicatorFolded); } else { var pos = Pos(cur, 0), func = opts.rangeFinder || cm.getHelper(pos, "fold"); var range = func && func(cm, pos); if (range && range.from.line + 1 < range.to.line) mark = marker(opts.indicatorOpen); } cm.setGutterMarker(line, opts.gutter, mark); ++cur; }); } function updateInViewport(cm) { var vp = cm.getViewport(), state = cm.state.foldGutter; if (!state) return; cm.operation(function() { updateFoldInfo(cm, vp.from, vp.to); }); state.from = vp.from; state.to = vp.to; } function onGutterClick(cm, line, gutter) { var opts = cm.state.foldGutter.options; if (gutter != opts.gutter) return; cm.foldCode(Pos(line, 0), opts.rangeFinder); } function onChange(cm) { var state = cm.state.foldGutter; state.from = state.to = 0; clearTimeout(state.changeUpdate); state.changeUpdate = setTimeout(function() { updateInViewport(cm); }, 600); } function onViewportChange(cm) { var state = cm.state.foldGutter; clearTimeout(state.changeUpdate); state.changeUpdate = setTimeout(function() { var vp = cm.getViewport(); if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) { updateInViewport(cm); } else { cm.operation(function() { if (vp.from < state.from) { updateFoldInfo(cm, vp.from, state.from); state.from = vp.from; } if (vp.to > state.to) { updateFoldInfo(cm, state.to, vp.to); state.to = vp.to; } }); } }, 400); } function onFold(cm, from) { var state = cm.state.foldGutter, line = from.line; if (line >= state.from && line < state.to) updateFoldInfo(cm, line, line + 1); } })(); ================================================ FILE: public/packages/codemirror-3.19/addon/fold/indent-fold.js ================================================ CodeMirror.registerHelper("fold", "indent", function(cm, start) { var lastLine = cm.lastLine(), tabSize = cm.getOption("tabSize"), firstLine = cm.getLine(start.line), myIndent = CodeMirror.countColumn(firstLine, null, tabSize); function foldEnded(curColumn, prevColumn) { return curColumn < myIndent || (curColumn == myIndent && prevColumn >= myIndent) || (curColumn > myIndent && i == lastLine); } for (var i = start.line + 1; i <= lastLine; i++) { var curColumn = CodeMirror.countColumn(cm.getLine(i), null, tabSize); var prevColumn = CodeMirror.countColumn(cm.getLine(i-1), null, tabSize); if (foldEnded(curColumn, prevColumn)) { var lastFoldLineNumber = curColumn > myIndent && i == lastLine ? i : i-1; var lastFoldLine = cm.getLine(lastFoldLineNumber); return {from: CodeMirror.Pos(start.line, firstLine.length), to: CodeMirror.Pos(lastFoldLineNumber, lastFoldLine.length)}; } } }); CodeMirror.indentRangeFinder = CodeMirror.fold.indent; // deprecated ================================================ FILE: public/packages/codemirror-3.19/addon/fold/xml-fold.js ================================================ (function() { "use strict"; var Pos = CodeMirror.Pos; function cmp(a, b) { return a.line - b.line || a.ch - b.ch; } var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; var nameChar = nameStartChar + "\-\:\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; var xmlTagStart = new RegExp("<(/?)([" + nameStartChar + "][" + nameChar + "]*)", "g"); function Iter(cm, line, ch, range) { this.line = line; this.ch = ch; this.cm = cm; this.text = cm.getLine(line); this.min = range ? range.from : cm.firstLine(); this.max = range ? range.to - 1 : cm.lastLine(); } function tagAt(iter, ch) { var type = iter.cm.getTokenTypeAt(Pos(iter.line, ch)); return type && /\btag\b/.test(type); } function nextLine(iter) { if (iter.line >= iter.max) return; iter.ch = 0; iter.text = iter.cm.getLine(++iter.line); return true; } function prevLine(iter) { if (iter.line <= iter.min) return; iter.text = iter.cm.getLine(--iter.line); iter.ch = iter.text.length; return true; } function toTagEnd(iter) { for (;;) { var gt = iter.text.indexOf(">", iter.ch); if (gt == -1) { if (nextLine(iter)) continue; else return; } if (!tagAt(iter, gt + 1)) { iter.ch = gt + 1; continue; } var lastSlash = iter.text.lastIndexOf("/", gt); var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt)); iter.ch = gt + 1; return selfClose ? "selfClose" : "regular"; } } function toTagStart(iter) { for (;;) { var lt = iter.ch ? iter.text.lastIndexOf("<", iter.ch - 1) : -1; if (lt == -1) { if (prevLine(iter)) continue; else return; } if (!tagAt(iter, lt + 1)) { iter.ch = lt; continue; } xmlTagStart.lastIndex = lt; iter.ch = lt; var match = xmlTagStart.exec(iter.text); if (match && match.index == lt) return match; } } function toNextTag(iter) { for (;;) { xmlTagStart.lastIndex = iter.ch; var found = xmlTagStart.exec(iter.text); if (!found) { if (nextLine(iter)) continue; else return; } if (!tagAt(iter, found.index + 1)) { iter.ch = found.index + 1; continue; } iter.ch = found.index + found[0].length; return found; } } function toPrevTag(iter) { for (;;) { var gt = iter.ch ? iter.text.lastIndexOf(">", iter.ch - 1) : -1; if (gt == -1) { if (prevLine(iter)) continue; else return; } if (!tagAt(iter, gt + 1)) { iter.ch = gt; continue; } var lastSlash = iter.text.lastIndexOf("/", gt); var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt)); iter.ch = gt + 1; return selfClose ? "selfClose" : "regular"; } } function findMatchingClose(iter, tag) { var stack = []; for (;;) { var next = toNextTag(iter), end, startLine = iter.line, startCh = iter.ch - (next ? next[0].length : 0); if (!next || !(end = toTagEnd(iter))) return; if (end == "selfClose") continue; if (next[1]) { // closing tag for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == next[2]) { stack.length = i; break; } if (i < 0 && (!tag || tag == next[2])) return { tag: next[2], from: Pos(startLine, startCh), to: Pos(iter.line, iter.ch) }; } else { // opening tag stack.push(next[2]); } } } function findMatchingOpen(iter, tag) { var stack = []; for (;;) { var prev = toPrevTag(iter); if (!prev) return; if (prev == "selfClose") { toTagStart(iter); continue; } var endLine = iter.line, endCh = iter.ch; var start = toTagStart(iter); if (!start) return; if (start[1]) { // closing tag stack.push(start[2]); } else { // opening tag for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == start[2]) { stack.length = i; break; } if (i < 0 && (!tag || tag == start[2])) return { tag: start[2], from: Pos(iter.line, iter.ch), to: Pos(endLine, endCh) }; } } } CodeMirror.registerHelper("fold", "xml", function(cm, start) { var iter = new Iter(cm, start.line, 0); for (;;) { var openTag = toNextTag(iter), end; if (!openTag || iter.line != start.line || !(end = toTagEnd(iter))) return; if (!openTag[1] && end != "selfClose") { var start = Pos(iter.line, iter.ch); var close = findMatchingClose(iter, openTag[2]); return close && {from: start, to: close.from}; } } }); CodeMirror.tagRangeFinder = CodeMirror.fold.xml; // deprecated CodeMirror.findMatchingTag = function(cm, pos, range) { var iter = new Iter(cm, pos.line, pos.ch, range); if (iter.text.indexOf(">") == -1 && iter.text.indexOf("<") == -1) return; var end = toTagEnd(iter), to = end && Pos(iter.line, iter.ch); var start = end && toTagStart(iter); if (!end || end == "selfClose" || !start || cmp(iter, pos) > 0) return; var here = {from: Pos(iter.line, iter.ch), to: to, tag: start[2]}; if (start[1]) { // closing tag return {open: findMatchingOpen(iter, start[2]), close: here, at: "close"}; } else { // opening tag iter = new Iter(cm, to.line, to.ch, range); return {open: here, close: findMatchingClose(iter, start[2]), at: "open"}; } }; CodeMirror.findEnclosingTag = function(cm, pos, range) { var iter = new Iter(cm, pos.line, pos.ch, range); for (;;) { var open = findMatchingOpen(iter); if (!open) break; var forward = new Iter(cm, pos.line, pos.ch, range); var close = findMatchingClose(forward, open.tag); if (close) return {open: open, close: close}; } }; })(); ================================================ FILE: public/packages/codemirror-3.19/addon/hint/anyword-hint.js ================================================ (function() { "use strict"; var WORD = /[\w$]+/, RANGE = 500; CodeMirror.registerHelper("hint", "anyword", function(editor, options) { var word = options && options.word || WORD; var range = options && options.range || RANGE; var cur = editor.getCursor(), curLine = editor.getLine(cur.line); var start = cur.ch, end = start; while (end < curLine.length && word.test(curLine.charAt(end))) ++end; while (start && word.test(curLine.charAt(start - 1))) --start; var curWord = start != end && curLine.slice(start, end); var list = [], seen = {}; function scan(dir) { var line = cur.line, end = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir; for (; line != end; line += dir) { var text = editor.getLine(line), m; var re = new RegExp(word.source, "g"); while (m = re.exec(text)) { if (line == cur.line && m[0] === curWord) continue; if ((!curWord || m[0].indexOf(curWord) == 0) && !seen.hasOwnProperty(m[0])) { seen[m[0]] = true; list.push(m[0]); } } } } scan(-1); scan(1); return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)}; }); })(); ================================================ FILE: public/packages/codemirror-3.19/addon/hint/css-hint.js ================================================ (function () { "use strict"; function getHints(cm) { var cur = cm.getCursor(), token = cm.getTokenAt(cur); var inner = CodeMirror.innerMode(cm.getMode(), token.state); if (inner.mode.name != "css") return; // If it's not a 'word-style' token, ignore the token. if (!/^[\w$_-]*$/.test(token.string)) { token = { start: cur.ch, end: cur.ch, string: "", state: token.state, type: null }; var stack = token.state.stack; var lastToken = stack && stack.length > 0 ? stack[stack.length - 1] : ""; if (token.string == ":" || lastToken.indexOf("property") == 0) token.type = "variable"; else if (token.string == "{" || lastToken.indexOf("rule") == 0) token.type = "property"; } if (!token.type) return; var spec = CodeMirror.resolveMode("text/css"); var keywords = null; if (token.type.indexOf("property") == 0) keywords = spec.propertyKeywords; else if (token.type.indexOf("variable") == 0) keywords = spec.valueKeywords; if (!keywords) return; var result = []; for (var name in keywords) { if (name.indexOf(token.string) == 0 /* > -1 */) result.push(name); } return { list: result, from: CodeMirror.Pos(cur.line, token.start), to: CodeMirror.Pos(cur.line, token.end) }; } CodeMirror.registerHelper("hint", "css", getHints); })(); ================================================ FILE: public/packages/codemirror-3.19/addon/hint/html-hint.js ================================================ (function () { var langs = "ab aa af ak sq am ar an hy as av ae ay az bm ba eu be bn bh bi bs br bg my ca ch ce ny zh cv kw co cr hr cs da dv nl dz en eo et ee fo fj fi fr ff gl ka de el gn gu ht ha he hz hi ho hu ia id ie ga ig ik io is it iu ja jv kl kn kr ks kk km ki rw ky kv kg ko ku kj la lb lg li ln lo lt lu lv gv mk mg ms ml mt mi mr mh mn na nv nb nd ne ng nn no ii nr oc oj cu om or os pa pi fa pl ps pt qu rm rn ro ru sa sc sd se sm sg sr gd sn si sk sl so st es su sw ss sv ta te tg th ti bo tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa cy wo fy xh yi yo za zu".split(" "); var targets = ["_blank", "_self", "_top", "_parent"]; var charsets = ["ascii", "utf-8", "utf-16", "latin1", "latin1"]; var methods = ["get", "post", "put", "delete"]; var encs = ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]; var media = ["all", "screen", "print", "embossed", "braille", "handheld", "print", "projection", "screen", "tty", "tv", "speech", "3d-glasses", "resolution [>][<][=] [X]", "device-aspect-ratio: X/Y", "orientation:portrait", "orientation:landscape", "device-height: [X]", "device-width: [X]"]; var s = { attrs: {} }; // Simple tag, reused for a whole lot of tags var data = { a: { attrs: { href: null, ping: null, type: null, media: media, target: targets, hreflang: langs } }, abbr: s, acronym: s, address: s, applet: s, area: { attrs: { alt: null, coords: null, href: null, target: null, ping: null, media: media, hreflang: langs, type: null, shape: ["default", "rect", "circle", "poly"] } }, article: s, aside: s, audio: { attrs: { src: null, mediagroup: null, crossorigin: ["anonymous", "use-credentials"], preload: ["none", "metadata", "auto"], autoplay: ["", "autoplay"], loop: ["", "loop"], controls: ["", "controls"] } }, b: s, base: { attrs: { href: null, target: targets } }, basefont: s, bdi: s, bdo: s, big: s, blockquote: { attrs: { cite: null } }, body: s, br: s, button: { attrs: { form: null, formaction: null, name: null, value: null, autofocus: ["", "autofocus"], disabled: ["", "autofocus"], formenctype: encs, formmethod: methods, formnovalidate: ["", "novalidate"], formtarget: targets, type: ["submit", "reset", "button"] } }, canvas: { attrs: { width: null, height: null } }, caption: s, center: s, cite: s, code: s, col: { attrs: { span: null } }, colgroup: { attrs: { span: null } }, command: { attrs: { type: ["command", "checkbox", "radio"], label: null, icon: null, radiogroup: null, command: null, title: null, disabled: ["", "disabled"], checked: ["", "checked"] } }, data: { attrs: { value: null } }, datagrid: { attrs: { disabled: ["", "disabled"], multiple: ["", "multiple"] } }, datalist: { attrs: { data: null } }, dd: s, del: { attrs: { cite: null, datetime: null } }, details: { attrs: { open: ["", "open"] } }, dfn: s, dir: s, div: s, dl: s, dt: s, em: s, embed: { attrs: { src: null, type: null, width: null, height: null } }, eventsource: { attrs: { src: null } }, fieldset: { attrs: { disabled: ["", "disabled"], form: null, name: null } }, figcaption: s, figure: s, font: s, footer: s, form: { attrs: { action: null, name: null, "accept-charset": charsets, autocomplete: ["on", "off"], enctype: encs, method: methods, novalidate: ["", "novalidate"], target: targets } }, frame: s, frameset: s, h1: s, h2: s, h3: s, h4: s, h5: s, h6: s, head: { attrs: {}, children: ["title", "base", "link", "style", "meta", "script", "noscript", "command"] }, header: s, hgroup: s, hr: s, html: { attrs: { manifest: null }, children: ["head", "body"] }, i: s, iframe: { attrs: { src: null, srcdoc: null, name: null, width: null, height: null, sandbox: ["allow-top-navigation", "allow-same-origin", "allow-forms", "allow-scripts"], seamless: ["", "seamless"] } }, img: { attrs: { alt: null, src: null, ismap: null, usemap: null, width: null, height: null, crossorigin: ["anonymous", "use-credentials"] } }, input: { attrs: { alt: null, dirname: null, form: null, formaction: null, height: null, list: null, max: null, maxlength: null, min: null, name: null, pattern: null, placeholder: null, size: null, src: null, step: null, value: null, width: null, accept: ["audio/*", "video/*", "image/*"], autocomplete: ["on", "off"], autofocus: ["", "autofocus"], checked: ["", "checked"], disabled: ["", "disabled"], formenctype: encs, formmethod: methods, formnovalidate: ["", "novalidate"], formtarget: targets, multiple: ["", "multiple"], readonly: ["", "readonly"], required: ["", "required"], type: ["hidden", "text", "search", "tel", "url", "email", "password", "datetime", "date", "month", "week", "time", "datetime-local", "number", "range", "color", "checkbox", "radio", "file", "submit", "image", "reset", "button"] } }, ins: { attrs: { cite: null, datetime: null } }, kbd: s, keygen: { attrs: { challenge: null, form: null, name: null, autofocus: ["", "autofocus"], disabled: ["", "disabled"], keytype: ["RSA"] } }, label: { attrs: { "for": null, form: null } }, legend: s, li: { attrs: { value: null } }, link: { attrs: { href: null, type: null, hreflang: langs, media: media, sizes: ["all", "16x16", "16x16 32x32", "16x16 32x32 64x64"] } }, map: { attrs: { name: null } }, mark: s, menu: { attrs: { label: null, type: ["list", "context", "toolbar"] } }, meta: { attrs: { content: null, charset: charsets, name: ["viewport", "application-name", "author", "description", "generator", "keywords"], "http-equiv": ["content-language", "content-type", "default-style", "refresh"] } }, meter: { attrs: { value: null, min: null, low: null, high: null, max: null, optimum: null } }, nav: s, noframes: s, noscript: s, object: { attrs: { data: null, type: null, name: null, usemap: null, form: null, width: null, height: null, typemustmatch: ["", "typemustmatch"] } }, ol: { attrs: { reversed: ["", "reversed"], start: null, type: ["1", "a", "A", "i", "I"] } }, optgroup: { attrs: { disabled: ["", "disabled"], label: null } }, option: { attrs: { disabled: ["", "disabled"], label: null, selected: ["", "selected"], value: null } }, output: { attrs: { "for": null, form: null, name: null } }, p: s, param: { attrs: { name: null, value: null } }, pre: s, progress: { attrs: { value: null, max: null } }, q: { attrs: { cite: null } }, rp: s, rt: s, ruby: s, s: s, samp: s, script: { attrs: { type: ["text/javascript"], src: null, async: ["", "async"], defer: ["", "defer"], charset: charsets } }, section: s, select: { attrs: { form: null, name: null, size: null, autofocus: ["", "autofocus"], disabled: ["", "disabled"], multiple: ["", "multiple"] } }, small: s, source: { attrs: { src: null, type: null, media: null } }, span: s, strike: s, strong: s, style: { attrs: { type: ["text/css"], media: media, scoped: null } }, sub: s, summary: s, sup: s, table: s, tbody: s, td: { attrs: { colspan: null, rowspan: null, headers: null } }, textarea: { attrs: { dirname: null, form: null, maxlength: null, name: null, placeholder: null, rows: null, cols: null, autofocus: ["", "autofocus"], disabled: ["", "disabled"], readonly: ["", "readonly"], required: ["", "required"], wrap: ["soft", "hard"] } }, tfoot: s, th: { attrs: { colspan: null, rowspan: null, headers: null, scope: ["row", "col", "rowgroup", "colgroup"] } }, thead: s, time: { attrs: { datetime: null } }, title: s, tr: s, track: { attrs: { src: null, label: null, "default": null, kind: ["subtitles", "captions", "descriptions", "chapters", "metadata"], srclang: langs } }, tt: s, u: s, ul: s, "var": s, video: { attrs: { src: null, poster: null, width: null, height: null, crossorigin: ["anonymous", "use-credentials"], preload: ["auto", "metadata", "none"], autoplay: ["", "autoplay"], mediagroup: ["movie"], muted: ["", "muted"], controls: ["", "controls"] } }, wbr: s }; var globalAttrs = { accesskey: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], "class": null, contenteditable: ["true", "false"], contextmenu: null, dir: ["ltr", "rtl", "auto"], draggable: ["true", "false", "auto"], dropzone: ["copy", "move", "link", "string:", "file:"], hidden: ["hidden"], id: null, inert: ["inert"], itemid: null, itemprop: null, itemref: null, itemscope: ["itemscope"], itemtype: null, lang: ["en", "es"], spellcheck: ["true", "false"], style: null, tabindex: ["1", "2", "3", "4", "5", "6", "7", "8", "9"], title: null, translate: ["yes", "no"], onclick: null, rel: ["stylesheet", "alternate", "author", "bookmark", "help", "license", "next", "nofollow", "noreferrer", "prefetch", "prev", "search", "tag"] }; function populate(obj) { for (var attr in globalAttrs) if (globalAttrs.hasOwnProperty(attr)) obj.attrs[attr] = globalAttrs[attr]; } populate(s); for (var tag in data) if (data.hasOwnProperty(tag) && data[tag] != s) populate(data[tag]); CodeMirror.htmlSchema = data; function htmlHint(cm, options) { var local = {schemaInfo: data}; if (options) for (var opt in options) local[opt] = options[opt]; return CodeMirror.hint.xml(cm, local); } CodeMirror.htmlHint = htmlHint; // deprecated CodeMirror.registerHelper("hint", "html", htmlHint); })(); ================================================ FILE: public/packages/codemirror-3.19/addon/hint/javascript-hint.js ================================================ (function () { var Pos = CodeMirror.Pos; function forEach(arr, f) { for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); } function arrayContains(arr, item) { if (!Array.prototype.indexOf) { var i = arr.length; while (i--) { if (arr[i] === item) { return true; } } return false; } return arr.indexOf(item) != -1; } function scriptHint(editor, keywords, getToken, options) { // Find the token at the cursor var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token; token.state = CodeMirror.innerMode(editor.getMode(), token.state).state; // If it's not a 'word-style' token, ignore the token. if (!/^[\w$_]*$/.test(token.string)) { token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state, type: token.string == "." ? "property" : null}; } // If it is a property, find out what it is a property of. while (tprop.type == "property") { tprop = getToken(editor, Pos(cur.line, tprop.start)); if (tprop.string != ".") return; tprop = getToken(editor, Pos(cur.line, tprop.start)); if (!context) var context = []; context.push(tprop); } return {list: getCompletions(token, context, keywords, options), from: Pos(cur.line, token.start), to: Pos(cur.line, token.end)}; } function javascriptHint(editor, options) { return scriptHint(editor, javascriptKeywords, function (e, cur) {return e.getTokenAt(cur);}, options); }; CodeMirror.javascriptHint = javascriptHint; // deprecated CodeMirror.registerHelper("hint", "javascript", javascriptHint); function getCoffeeScriptToken(editor, cur) { // This getToken, it is for coffeescript, imitates the behavior of // getTokenAt method in javascript.js, that is, returning "property" // type and treat "." as indepenent token. var token = editor.getTokenAt(cur); if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') { token.end = token.start; token.string = '.'; token.type = "property"; } else if (/^\.[\w$_]*$/.test(token.string)) { token.type = "property"; token.start++; token.string = token.string.replace(/\./, ''); } return token; } function coffeescriptHint(editor, options) { return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken, options); } CodeMirror.coffeescriptHint = coffeescriptHint; // deprecated CodeMirror.registerHelper("hint", "coffeescript", coffeescriptHint); var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " + "toUpperCase toLowerCase split concat match replace search").split(" "); var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " + "lastIndexOf every some filter forEach map reduce reduceRight ").split(" "); var funcProps = "prototype apply call bind".split(" "); var javascriptKeywords = ("break case catch continue debugger default delete do else false finally for function " + "if in instanceof new null return switch throw true try typeof var void while with").split(" "); var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " + "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" "); function getCompletions(token, context, keywords, options) { var found = [], start = token.string; function maybeAdd(str) { if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str); } function gatherCompletions(obj) { if (typeof obj == "string") forEach(stringProps, maybeAdd); else if (obj instanceof Array) forEach(arrayProps, maybeAdd); else if (obj instanceof Function) forEach(funcProps, maybeAdd); for (var name in obj) maybeAdd(name); } if (context && context.length) { // If this is a property, see if it belongs to some object we can // find in the current environment. var obj = context.pop(), base; if (obj.type && obj.type.indexOf("variable") === 0) { if (options && options.additionalContext) base = options.additionalContext[obj.string]; base = base || window[obj.string]; } else if (obj.type == "string") { base = ""; } else if (obj.type == "atom") { base = 1; } else if (obj.type == "function") { if (window.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') && (typeof window.jQuery == 'function')) base = window.jQuery(); else if (window._ != null && (obj.string == '_') && (typeof window._ == 'function')) base = window._(); } while (base != null && context.length) base = base[context.pop().string]; if (base != null) gatherCompletions(base); } else { // If not, just look in the window object and any local scope // (reading into JS mode internals to get at the local and global variables) for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name); for (var v = token.state.globalVars; v; v = v.next) maybeAdd(v.name); gatherCompletions(window); forEach(keywords, maybeAdd); } return found; } })(); ================================================ FILE: public/packages/codemirror-3.19/addon/hint/pig-hint.js ================================================ (function () { "use strict"; function forEach(arr, f) { for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); } function arrayContains(arr, item) { if (!Array.prototype.indexOf) { var i = arr.length; while (i--) { if (arr[i] === item) { return true; } } return false; } return arr.indexOf(item) != -1; } function scriptHint(editor, _keywords, getToken) { // Find the token at the cursor var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token; // If it's not a 'word-style' token, ignore the token. if (!/^[\w$_]*$/.test(token.string)) { token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state, className: token.string == ":" ? "pig-type" : null}; } if (!context) var context = []; context.push(tprop); var completionList = getCompletions(token, context); completionList = completionList.sort(); //prevent autocomplete for last word, instead show dropdown with one word if(completionList.length == 1) { completionList.push(" "); } return {list: completionList, from: CodeMirror.Pos(cur.line, token.start), to: CodeMirror.Pos(cur.line, token.end)}; } function pigHint(editor) { return scriptHint(editor, pigKeywordsU, function (e, cur) {return e.getTokenAt(cur);}); } CodeMirror.pigHint = pigHint; // deprecated CodeMirror.registerHelper("hint", "pig", pigHint); var pigKeywords = "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"; var pigKeywordsU = pigKeywords.split(" "); var pigKeywordsL = pigKeywords.toLowerCase().split(" "); var pigTypes = "BOOLEAN INT LONG FLOAT DOUBLE CHARARRAY BYTEARRAY BAG TUPLE MAP"; var pigTypesU = pigTypes.split(" "); var pigTypesL = pigTypes.toLowerCase().split(" "); var pigBuiltins = "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"; var pigBuiltinsU = pigBuiltins.split(" ").join("() ").split(" "); var pigBuiltinsL = pigBuiltins.toLowerCase().split(" ").join("() ").split(" "); var pigBuiltinsC = ("BagSize BinStorage Bloom BuildBloom ConstantSize CubeDimensions DoubleAbs " + "DoubleAvg DoubleBase DoubleMax DoubleMin DoubleRound DoubleSum FloatAbs FloatAvg FloatMax " + "FloatMin FloatRound FloatSum GenericInvoker IntAbs IntAvg IntMax IntMin IntSum " + "InvokeForDouble InvokeForFloat InvokeForInt InvokeForLong InvokeForString Invoker " + "IsEmpty JsonLoader JsonMetadata JsonStorage LongAbs LongAvg LongMax LongMin LongSum MapSize " + "MonitoredUDF Nondeterministic OutputSchema PigStorage PigStreaming StringConcat StringMax " + "StringMin StringSize TextLoader TupleSize Utf8StorageConverter").split(" ").join("() ").split(" "); function getCompletions(token, context) { var found = [], start = token.string; function maybeAdd(str) { if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str); } function gatherCompletions(obj) { if(obj == ":") { forEach(pigTypesL, maybeAdd); } else { forEach(pigBuiltinsU, maybeAdd); forEach(pigBuiltinsL, maybeAdd); forEach(pigBuiltinsC, maybeAdd); forEach(pigTypesU, maybeAdd); forEach(pigTypesL, maybeAdd); forEach(pigKeywordsU, maybeAdd); forEach(pigKeywordsL, maybeAdd); } } if (context) { // If this is a property, see if it belongs to some object we can // find in the current environment. var obj = context.pop(), base; if (obj.type == "variable") base = obj.string; else if(obj.type == "variable-3") base = ":" + obj.string; while (base != null && context.length) base = base[context.pop().string]; if (base != null) gatherCompletions(base); } return found; } })(); ================================================ FILE: public/packages/codemirror-3.19/addon/hint/python-hint.js ================================================ (function () { function forEach(arr, f) { for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); } function arrayContains(arr, item) { if (!Array.prototype.indexOf) { var i = arr.length; while (i--) { if (arr[i] === item) { return true; } } return false; } return arr.indexOf(item) != -1; } function scriptHint(editor, _keywords, getToken) { // Find the token at the cursor var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token; // If it's not a 'word-style' token, ignore the token. if (!/^[\w$_]*$/.test(token.string)) { token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state, className: token.string == ":" ? "python-type" : null}; } if (!context) var context = []; context.push(tprop); var completionList = getCompletions(token, context); completionList = completionList.sort(); //prevent autocomplete for last word, instead show dropdown with one word if(completionList.length == 1) { completionList.push(" "); } return {list: completionList, from: CodeMirror.Pos(cur.line, token.start), to: CodeMirror.Pos(cur.line, token.end)}; } function pythonHint(editor) { return scriptHint(editor, pythonKeywordsU, function (e, cur) {return e.getTokenAt(cur);}); } CodeMirror.pythonHint = pythonHint; // deprecated CodeMirror.registerHelper("hint", "python", pythonHint); var pythonKeywords = "and del from not while as elif global or with assert else if pass yield" + "break except import print class exec in raise continue finally is return def for lambda try"; var pythonKeywordsL = pythonKeywords.split(" "); var pythonKeywordsU = pythonKeywords.toUpperCase().split(" "); var pythonBuiltins = "abs divmod input open staticmethod all enumerate int ord str " + "any eval isinstance pow sum basestring execfile issubclass print super" + "bin file iter property tuple bool filter len range type" + "bytearray float list raw_input unichr callable format locals reduce unicode" + "chr frozenset long reload vars classmethod getattr map repr xrange" + "cmp globals max reversed zip compile hasattr memoryview round __import__" + "complex hash min set apply delattr help next setattr buffer" + "dict hex object slice coerce dir id oct sorted intern "; var pythonBuiltinsL = pythonBuiltins.split(" ").join("() ").split(" "); var pythonBuiltinsU = pythonBuiltins.toUpperCase().split(" ").join("() ").split(" "); function getCompletions(token, context) { var found = [], start = token.string; function maybeAdd(str) { if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str); } function gatherCompletions(_obj) { forEach(pythonBuiltinsL, maybeAdd); forEach(pythonBuiltinsU, maybeAdd); forEach(pythonKeywordsL, maybeAdd); forEach(pythonKeywordsU, maybeAdd); } if (context) { // If this is a property, see if it belongs to some object we can // find in the current environment. var obj = context.pop(), base; if (obj.type == "variable") base = obj.string; else if(obj.type == "variable-3") base = ":" + obj.string; while (base != null && context.length) base = base[context.pop().string]; if (base != null) gatherCompletions(base); } return found; } })(); ================================================ FILE: public/packages/codemirror-3.19/addon/hint/show-hint.css ================================================ .CodeMirror-hints { position: absolute; z-index: 10; overflow: hidden; list-style: none; margin: 0; padding: 2px; -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2); -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2); box-shadow: 2px 3px 5px rgba(0,0,0,.2); border-radius: 3px; border: 1px solid silver; background: white; font-size: 90%; font-family: monospace; max-height: 20em; overflow-y: auto; } .CodeMirror-hint { margin: 0; padding: 0 4px; border-radius: 2px; max-width: 19em; overflow: hidden; white-space: pre; color: black; cursor: pointer; } .CodeMirror-hint-active { background: #08f; color: white; } ================================================ FILE: public/packages/codemirror-3.19/addon/hint/show-hint.js ================================================ (function() { "use strict"; CodeMirror.showHint = function(cm, getHints, options) { // We want a single cursor position. if (cm.somethingSelected()) return; if (getHints == null) getHints = cm.getHelper(cm.getCursor(), "hint"); if (getHints == null) return; if (cm.state.completionActive) cm.state.completionActive.close(); var completion = cm.state.completionActive = new Completion(cm, getHints, options || {}); CodeMirror.signal(cm, "startCompletion", cm); if (completion.options.async) getHints(cm, function(hints) { completion.showHints(hints); }, completion.options); else return completion.showHints(getHints(cm, completion.options)); }; function Completion(cm, getHints, options) { this.cm = cm; this.getHints = getHints; this.options = options; this.widget = this.onClose = null; } Completion.prototype = { close: function() { if (!this.active()) return; this.cm.state.completionActive = null; if (this.widget) this.widget.close(); if (this.onClose) this.onClose(); CodeMirror.signal(this.cm, "endCompletion", this.cm); }, active: function() { return this.cm.state.completionActive == this; }, pick: function(data, i) { var completion = data.list[i]; if (completion.hint) completion.hint(this.cm, data, completion); else this.cm.replaceRange(getText(completion), data.from, data.to); this.close(); }, showHints: function(data) { if (!data || !data.list.length || !this.active()) return this.close(); if (this.options.completeSingle != false && data.list.length == 1) this.pick(data, 0); else this.showWidget(data); }, showWidget: function(data) { this.widget = new Widget(this, data); CodeMirror.signal(data, "shown"); var debounce = null, completion = this, finished; var closeOn = this.options.closeCharacters || /[\s()\[\]{};:>,]/; var startPos = this.cm.getCursor(), startLen = this.cm.getLine(startPos.line).length; function done() { if (finished) return; finished = true; completion.close(); completion.cm.off("cursorActivity", activity); if (data) CodeMirror.signal(data, "close"); } function update() { if (finished) return; CodeMirror.signal(data, "update"); if (completion.options.async) completion.getHints(completion.cm, finishUpdate, completion.options); else finishUpdate(completion.getHints(completion.cm, completion.options)); } function finishUpdate(data_) { data = data_; if (finished) return; if (!data || !data.list.length) return done(); completion.widget = new Widget(completion, data); } function activity() { clearTimeout(debounce); var pos = completion.cm.getCursor(), line = completion.cm.getLine(pos.line); if (pos.line != startPos.line || line.length - pos.ch != startLen - startPos.ch || pos.ch < startPos.ch || completion.cm.somethingSelected() || (pos.ch && closeOn.test(line.charAt(pos.ch - 1)))) { completion.close(); } else { debounce = setTimeout(update, 170); if (completion.widget) completion.widget.close(); } } this.cm.on("cursorActivity", activity); this.onClose = done; } }; function getText(completion) { if (typeof completion == "string") return completion; else return completion.text; } function buildKeyMap(options, handle) { var baseMap = { Up: function() {handle.moveFocus(-1);}, Down: function() {handle.moveFocus(1);}, PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);}, PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);}, Home: function() {handle.setFocus(0);}, End: function() {handle.setFocus(handle.length - 1);}, Enter: handle.pick, Tab: handle.pick, Esc: handle.close }; var ourMap = options.customKeys ? {} : baseMap; function addBinding(key, val) { var bound; if (typeof val != "string") bound = function(cm) { return val(cm, handle); }; // This mechanism is deprecated else if (baseMap.hasOwnProperty(val)) bound = baseMap[val]; else bound = val; ourMap[key] = bound; } if (options.customKeys) for (var key in options.customKeys) if (options.customKeys.hasOwnProperty(key)) addBinding(key, options.customKeys[key]); if (options.extraKeys) for (var key in options.extraKeys) if (options.extraKeys.hasOwnProperty(key)) addBinding(key, options.extraKeys[key]); return ourMap; } function Widget(completion, data) { this.completion = completion; this.data = data; var widget = this, cm = completion.cm, options = completion.options; var hints = this.hints = document.createElement("ul"); hints.className = "CodeMirror-hints"; this.selectedHint = 0; var completions = data.list; for (var i = 0; i < completions.length; ++i) { var elt = hints.appendChild(document.createElement("li")), cur = completions[i]; var className = "CodeMirror-hint" + (i ? "" : " CodeMirror-hint-active"); if (cur.className != null) className = cur.className + " " + className; elt.className = className; if (cur.render) cur.render(elt, data, cur); else elt.appendChild(document.createTextNode(cur.displayText || getText(cur))); elt.hintId = i; } var pos = cm.cursorCoords(options.alignWithWord !== false ? data.from : null); var left = pos.left, top = pos.bottom, below = true; hints.style.left = left + "px"; hints.style.top = top + "px"; // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor. var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth); var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight); (options.container || document.body).appendChild(hints); var box = hints.getBoundingClientRect(); var overlapX = box.right - winW, overlapY = box.bottom - winH; if (overlapX > 0) { if (box.right - box.left > winW) { hints.style.width = (winW - 5) + "px"; overlapX -= (box.right - box.left) - winW; } hints.style.left = (left = pos.left - overlapX) + "px"; } if (overlapY > 0) { var height = box.bottom - box.top; if (box.top - (pos.bottom - pos.top) - height > 0) { overlapY = height + (pos.bottom - pos.top); below = false; } else if (height > winH) { hints.style.height = (winH - 5) + "px"; overlapY -= height - winH; } hints.style.top = (top = pos.bottom - overlapY) + "px"; } cm.addKeyMap(this.keyMap = buildKeyMap(options, { moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); }, setFocus: function(n) { widget.changeActive(n); }, menuSize: function() { return widget.screenAmount(); }, length: completions.length, close: function() { completion.close(); }, pick: function() { widget.pick(); } })); if (options.closeOnUnfocus !== false) { var closingOnBlur; cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); }); cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); }); } var startScroll = cm.getScrollInfo(); cm.on("scroll", this.onScroll = function() { var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect(); var newTop = top + startScroll.top - curScroll.top; var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop); if (!below) point += hints.offsetHeight; if (point <= editor.top || point >= editor.bottom) return completion.close(); hints.style.top = newTop + "px"; hints.style.left = (left + startScroll.left - curScroll.left) + "px"; }); CodeMirror.on(hints, "dblclick", function(e) { var t = e.target || e.srcElement; if (t.hintId != null) {widget.changeActive(t.hintId); widget.pick();} }); CodeMirror.on(hints, "click", function(e) { var t = e.target || e.srcElement; if (t.hintId != null) widget.changeActive(t.hintId); }); CodeMirror.on(hints, "mousedown", function() { setTimeout(function(){cm.focus();}, 20); }); CodeMirror.signal(data, "select", completions[0], hints.firstChild); return true; } Widget.prototype = { close: function() { if (this.completion.widget != this) return; this.completion.widget = null; this.hints.parentNode.removeChild(this.hints); this.completion.cm.removeKeyMap(this.keyMap); var cm = this.completion.cm; if (this.completion.options.closeOnUnfocus !== false) { cm.off("blur", this.onBlur); cm.off("focus", this.onFocus); } cm.off("scroll", this.onScroll); }, pick: function() { this.completion.pick(this.data, this.selectedHint); }, changeActive: function(i, avoidWrap) { if (i >= this.data.list.length) i = avoidWrap ? this.data.list.length - 1 : 0; else if (i < 0) i = avoidWrap ? 0 : this.data.list.length - 1; if (this.selectedHint == i) return; var node = this.hints.childNodes[this.selectedHint]; node.className = node.className.replace(" CodeMirror-hint-active", ""); node = this.hints.childNodes[this.selectedHint = i]; node.className += " CodeMirror-hint-active"; if (node.offsetTop < this.hints.scrollTop) this.hints.scrollTop = node.offsetTop - 3; else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3; CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); }, screenAmount: function() { return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1; } }; })(); ================================================ FILE: public/packages/codemirror-3.19/addon/hint/sql-hint.js ================================================ (function () { "use strict"; var tables; var keywords; function getKeywords(editor) { var mode = editor.doc.modeOption; if(mode === "sql") mode = "text/x-sql"; return CodeMirror.resolveMode(mode).keywords; } function match(string, word) { var len = string.length; var sub = word.substr(0, len); return string.toUpperCase() === sub.toUpperCase(); } function addMatches(result, search, wordlist, formatter) { for(var word in wordlist) { if(!wordlist.hasOwnProperty(word)) continue; if(Array.isArray(wordlist)) { word = wordlist[word]; } if(match(search, word)) { result.push(formatter(word)); } } } function columnCompletion(result, editor) { var cur = editor.getCursor(); var token = editor.getTokenAt(cur); var string = token.string.substr(1); var prevCur = CodeMirror.Pos(cur.line, token.start); var table = editor.getTokenAt(prevCur).string; var columns = tables[table]; if(!columns) { table = findTableByAlias(table, editor); } columns = tables[table]; if(!columns) { return; } addMatches(result, string, columns, function(w) {return "." + w;}); } function eachWord(line, f) { var words = line.text.split(" "); for(var i = 0; i < words.length; i++) { f(words[i]); } } // Tries to find possible table name from alias. function findTableByAlias(alias, editor) { var aliasUpperCase = alias.toUpperCase(); var previousWord = ""; var table = ""; editor.eachLine(function(line) { eachWord(line, function(word) { var wordUpperCase = word.toUpperCase(); if(wordUpperCase === aliasUpperCase) { if(tables.hasOwnProperty(previousWord)) { table = previousWord; } } if(wordUpperCase !== "AS") { previousWord = word; } }); }); return table; } function sqlHint(editor, options) { tables = (options && options.tables) || {}; keywords = keywords || getKeywords(editor); var cur = editor.getCursor(); var token = editor.getTokenAt(cur); var result = []; var search = token.string.trim(); addMatches(result, search, keywords, function(w) {return w.toUpperCase();}); addMatches(result, search, tables, function(w) {return w;}); if(search.lastIndexOf('.') === 0) { columnCompletion(result, editor); } return { list: result, from: CodeMirror.Pos(cur.line, token.start), to: CodeMirror.Pos(cur.line, token.end) }; } CodeMirror.registerHelper("hint", "sql", sqlHint); })(); ================================================ FILE: public/packages/codemirror-3.19/addon/hint/xml-hint.js ================================================ (function() { "use strict"; var Pos = CodeMirror.Pos; function getHints(cm, options) { var tags = options && options.schemaInfo; var quote = (options && options.quoteChar) || '"'; if (!tags) return; var cur = cm.getCursor(), token = cm.getTokenAt(cur); var inner = CodeMirror.innerMode(cm.getMode(), token.state); if (inner.mode.name != "xml") return; var result = [], replaceToken = false, prefix; var isTag = token.string.charAt(0) == "<"; if (!inner.state.tagName || isTag) { // Tag completion if (isTag) { prefix = token.string.slice(1); replaceToken = true; } var cx = inner.state.context, curTag = cx && tags[cx.tagName]; var childList = cx ? curTag && curTag.children : tags["!top"]; if (childList) { for (var i = 0; i < childList.length; ++i) if (!prefix || childList[i].indexOf(prefix) == 0) result.push("<" + childList[i]); } else { for (var name in tags) if (tags.hasOwnProperty(name) && name != "!top" && (!prefix || name.indexOf(prefix) == 0)) result.push("<" + name); } if (cx && (!prefix || ("/" + cx.tagName).indexOf(prefix) == 0)) result.push(""); } else { // Attribute completion var curTag = tags[inner.state.tagName], attrs = curTag && curTag.attrs; if (!attrs) return; if (token.type == "string" || token.string == "=") { // A value var before = cm.getRange(Pos(cur.line, Math.max(0, cur.ch - 60)), Pos(cur.line, token.type == "string" ? token.start : token.end)); var atName = before.match(/([^\s\u00a0=<>\"\']+)=$/), atValues; if (!atName || !attrs.hasOwnProperty(atName[1]) || !(atValues = attrs[atName[1]])) return; if (typeof atValues == 'function') atValues = atValues.call(this, cm); // Functions can be used to supply values for autocomplete widget if (token.type == "string") { prefix = token.string; if (/['"]/.test(token.string.charAt(0))) { quote = token.string.charAt(0); prefix = token.string.slice(1); } replaceToken = true; } for (var i = 0; i < atValues.length; ++i) if (!prefix || atValues[i].indexOf(prefix) == 0) result.push(quote + atValues[i] + quote); } else { // An attribute name if (token.type == "attribute") { prefix = token.string; replaceToken = true; } for (var attr in attrs) if (attrs.hasOwnProperty(attr) && (!prefix || attr.indexOf(prefix) == 0)) result.push(attr); } } return { list: result, from: replaceToken ? Pos(cur.line, token.start) : cur, to: replaceToken ? Pos(cur.line, token.end) : cur }; } CodeMirror.xmlHint = getHints; // deprecated CodeMirror.registerHelper("hint", "xml", getHints); })(); ================================================ FILE: public/packages/codemirror-3.19/addon/lint/coffeescript-lint.js ================================================ // Depends on coffeelint.js from http://www.coffeelint.org/js/coffeelint.js // declare global: coffeelint CodeMirror.registerHelper("lint", "coffeescript", function(text) { var found = []; var parseError = function(err) { var loc = err.lineNumber; found.push({from: CodeMirror.Pos(loc-1, 0), to: CodeMirror.Pos(loc, 0), severity: err.level, message: err.message}); }; try { var res = coffeelint.lint(text); for(var i = 0; i < res.length; i++) { parseError(res[i]); } } catch(e) { found.push({from: CodeMirror.Pos(e.location.first_line, 0), to: CodeMirror.Pos(e.location.last_line, e.location.last_column), severity: 'error', message: e.message}); } return found; }); CodeMirror.coffeeValidator = CodeMirror.lint.coffeescript; // deprecated ================================================ FILE: public/packages/codemirror-3.19/addon/lint/css-lint.js ================================================ // Depends on csslint.js from https://github.com/stubbornella/csslint // declare global: CSSLint CodeMirror.registerHelper("lint", "css", function(text) { var found = []; var results = CSSLint.verify(text), messages = results.messages, message = null; for ( var i = 0; i < messages.length; i++) { message = messages[i]; var startLine = message.line -1, endLine = message.line -1, startCol = message.col -1, endCol = message.col; found.push({ from: CodeMirror.Pos(startLine, startCol), to: CodeMirror.Pos(endLine, endCol), message: message.message, severity : message.type }); } return found; }); ================================================ FILE: public/packages/codemirror-3.19/addon/lint/javascript-lint.js ================================================ (function() { "use strict"; // declare global: JSHINT var bogus = [ "Dangerous comment" ]; var warnings = [ [ "Expected '{'", "Statement body should be inside '{ }' braces." ] ]; var errors = [ "Missing semicolon", "Extra comma", "Missing property name", "Unmatched ", " and instead saw", " is not defined", "Unclosed string", "Stopping, unable to continue" ]; function validator(text, options) { JSHINT(text, options); var errors = JSHINT.data().errors, result = []; if (errors) parseErrors(errors, result); return result; } CodeMirror.registerHelper("lint", "javascript", validator); CodeMirror.javascriptValidator = CodeMirror.lint.javascript; // deprecated function cleanup(error) { // All problems are warnings by default fixWith(error, warnings, "warning", true); fixWith(error, errors, "error"); return isBogus(error) ? null : error; } function fixWith(error, fixes, severity, force) { var description, fix, find, replace, found; description = error.description; for ( var i = 0; i < fixes.length; i++) { fix = fixes[i]; find = (typeof fix === "string" ? fix : fix[0]); replace = (typeof fix === "string" ? null : fix[1]); found = description.indexOf(find) !== -1; if (force || found) { error.severity = severity; } if (found && replace) { error.description = replace; } } } function isBogus(error) { var description = error.description; for ( var i = 0; i < bogus.length; i++) { if (description.indexOf(bogus[i]) !== -1) { return true; } } return false; } function parseErrors(errors, output) { for ( var i = 0; i < errors.length; i++) { var error = errors[i]; if (error) { var linetabpositions, index; linetabpositions = []; // This next block is to fix a problem in jshint. Jshint // replaces // all tabs with spaces then performs some checks. The error // positions (character/space) are then reported incorrectly, // not taking the replacement step into account. Here we look // at the evidence line and try to adjust the character position // to the correct value. if (error.evidence) { // Tab positions are computed once per line and cached var tabpositions = linetabpositions[error.line]; if (!tabpositions) { var evidence = error.evidence; tabpositions = []; // ugggh phantomjs does not like this // forEachChar(evidence, function(item, index) { Array.prototype.forEach.call(evidence, function(item, index) { if (item === '\t') { // First col is 1 (not 0) to match error // positions tabpositions.push(index + 1); } }); linetabpositions[error.line] = tabpositions; } if (tabpositions.length > 0) { var pos = error.character; tabpositions.forEach(function(tabposition) { if (pos > tabposition) pos -= 1; }); error.character = pos; } } var start = error.character - 1, end = start + 1; if (error.evidence) { index = error.evidence.substring(start).search(/.\b/); if (index > -1) { end += index; } } // Convert to format expected by validation service error.description = error.reason;// + "(jshint)"; error.start = error.character; error.end = end; error = cleanup(error); if (error) output.push({message: error.description, severity: error.severity, from: CodeMirror.Pos(error.line - 1, start), to: CodeMirror.Pos(error.line - 1, end)}); } } } })(); ================================================ FILE: public/packages/codemirror-3.19/addon/lint/json-lint.js ================================================ // Depends on jsonlint.js from https://github.com/zaach/jsonlint // declare global: jsonlint CodeMirror.registerHelper("lint", "json", function(text) { var found = []; jsonlint.parseError = function(str, hash) { var loc = hash.loc; found.push({from: CodeMirror.Pos(loc.first_line - 1, loc.first_column), to: CodeMirror.Pos(loc.last_line - 1, loc.last_column), message: str}); }; try { jsonlint.parse(text); } catch(e) {} return found; }); CodeMirror.jsonValidator = CodeMirror.lint.json; // deprecated ================================================ FILE: public/packages/codemirror-3.19/addon/lint/lint.css ================================================ /* The lint marker gutter */ .CodeMirror-lint-markers { width: 16px; } .CodeMirror-lint-tooltip { background-color: infobackground; border: 1px solid black; border-radius: 4px 4px 4px 4px; color: infotext; font-family: monospace; font-size: 10pt; overflow: hidden; padding: 2px 5px; position: fixed; white-space: pre; white-space: pre-wrap; z-index: 100; max-width: 600px; opacity: 0; transition: opacity .4s; -moz-transition: opacity .4s; -webkit-transition: opacity .4s; -o-transition: opacity .4s; -ms-transition: opacity .4s; } .CodeMirror-lint-mark-error, .CodeMirror-lint-mark-warning { background-position: left bottom; background-repeat: repeat-x; } .CodeMirror-lint-mark-error { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJDw4cOCW1/KIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAHElEQVQI12NggIL/DAz/GdA5/xkY/qPKMDAwAADLZwf5rvm+LQAAAABJRU5ErkJggg==") ; } .CodeMirror-lint-mark-warning { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJFhQXEbhTg7YAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVQI12NkgIIvJ3QXMjAwdDN+OaEbysDA4MPAwNDNwMCwiOHLCd1zX07o6kBVGQEAKBANtobskNMAAAAASUVORK5CYII="); } .CodeMirror-lint-marker-error, .CodeMirror-lint-marker-warning { background-position: center center; background-repeat: no-repeat; cursor: pointer; display: inline-block; height: 16px; width: 16px; vertical-align: middle; position: relative; } .CodeMirror-lint-message-error, .CodeMirror-lint-message-warning { padding-left: 18px; background-position: top left; background-repeat: no-repeat; } .CodeMirror-lint-marker-error, .CodeMirror-lint-message-error { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAHlBMVEW7AAC7AACxAAC7AAC7AAAAAAC4AAC5AAD///+7AAAUdclpAAAABnRSTlMXnORSiwCK0ZKSAAAATUlEQVR42mWPOQ7AQAgDuQLx/z8csYRmPRIFIwRGnosRrpamvkKi0FTIiMASR3hhKW+hAN6/tIWhu9PDWiTGNEkTtIOucA5Oyr9ckPgAWm0GPBog6v4AAAAASUVORK5CYII="); } .CodeMirror-lint-marker-warning, .CodeMirror-lint-message-warning { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAANlBMVEX/uwDvrwD/uwD/uwD/uwD/uwD/uwD/uwD/uwD6twD/uwAAAADurwD2tQD7uAD+ugAAAAD/uwDhmeTRAAAADHRSTlMJ8mN1EYcbmiixgACm7WbuAAAAVklEQVR42n3PUQqAIBBFUU1LLc3u/jdbOJoW1P08DA9Gba8+YWJ6gNJoNYIBzAA2chBth5kLmG9YUoG0NHAUwFXwO9LuBQL1giCQb8gC9Oro2vp5rncCIY8L8uEx5ZkAAAAASUVORK5CYII="); } .CodeMirror-lint-marker-multiple { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAMAAADzjKfhAAAACVBMVEUAAAAAAAC/v7914kyHAAAAAXRSTlMAQObYZgAAACNJREFUeNo1ioEJAAAIwmz/H90iFFSGJgFMe3gaLZ0od+9/AQZ0ADosbYraAAAAAElFTkSuQmCC"); background-repeat: no-repeat; background-position: right bottom; width: 100%; height: 100%; } ================================================ FILE: public/packages/codemirror-3.19/addon/lint/lint.js ================================================ (function() { "use strict"; var GUTTER_ID = "CodeMirror-lint-markers"; var SEVERITIES = /^(?:error|warning)$/; function showTooltip(e, content) { var tt = document.createElement("div"); tt.className = "CodeMirror-lint-tooltip"; tt.appendChild(content.cloneNode(true)); document.body.appendChild(tt); function position(e) { if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position); tt.style.top = Math.max(0, e.clientY - tt.offsetHeight - 5) + "px"; tt.style.left = (e.clientX + 5) + "px"; } CodeMirror.on(document, "mousemove", position); position(e); if (tt.style.opacity != null) tt.style.opacity = 1; return tt; } function rm(elt) { if (elt.parentNode) elt.parentNode.removeChild(elt); } function hideTooltip(tt) { if (!tt.parentNode) return; if (tt.style.opacity == null) rm(tt); tt.style.opacity = 0; setTimeout(function() { rm(tt); }, 600); } function showTooltipFor(e, content, node) { var tooltip = showTooltip(e, content); function hide() { CodeMirror.off(node, "mouseout", hide); if (tooltip) { hideTooltip(tooltip); tooltip = null; } } var poll = setInterval(function() { if (tooltip) for (var n = node;; n = n.parentNode) { if (n == document.body) return; if (!n) { hide(); break; } } if (!tooltip) return clearInterval(poll); }, 400); CodeMirror.on(node, "mouseout", hide); } function LintState(cm, options, hasGutter) { this.marked = []; this.options = options; this.timeout = null; this.hasGutter = hasGutter; this.onMouseOver = function(e) { onMouseOver(cm, e); }; } function parseOptions(cm, options) { if (options instanceof Function) return {getAnnotations: options}; if (!options || options === true) options = {}; if (!options.getAnnotations) options.getAnnotations = cm.getHelper(CodeMirror.Pos(0, 0), "lint"); if (!options.getAnnotations) throw new Error("Required option 'getAnnotations' missing (lint addon)"); return options; } function clearMarks(cm) { var state = cm.state.lint; if (state.hasGutter) cm.clearGutter(GUTTER_ID); for (var i = 0; i < state.marked.length; ++i) state.marked[i].clear(); state.marked.length = 0; } function makeMarker(labels, severity, multiple, tooltips) { var marker = document.createElement("div"), inner = marker; marker.className = "CodeMirror-lint-marker-" + severity; if (multiple) { inner = marker.appendChild(document.createElement("div")); inner.className = "CodeMirror-lint-marker-multiple"; } if (tooltips != false) CodeMirror.on(inner, "mouseover", function(e) { showTooltipFor(e, labels, inner); }); return marker; } function getMaxSeverity(a, b) { if (a == "error") return a; else return b; } function groupByLine(annotations) { var lines = []; for (var i = 0; i < annotations.length; ++i) { var ann = annotations[i], line = ann.from.line; (lines[line] || (lines[line] = [])).push(ann); } return lines; } function annotationTooltip(ann) { var severity = ann.severity; if (!SEVERITIES.test(severity)) severity = "error"; var tip = document.createElement("div"); tip.className = "CodeMirror-lint-message-" + severity; tip.appendChild(document.createTextNode(ann.message)); return tip; } function startLinting(cm) { var state = cm.state.lint, options = state.options; if (options.async) options.getAnnotations(cm, updateLinting, options); else updateLinting(cm, options.getAnnotations(cm.getValue(), options)); } function updateLinting(cm, annotationsNotSorted) { clearMarks(cm); var state = cm.state.lint, options = state.options; var annotations = groupByLine(annotationsNotSorted); for (var line = 0; line < annotations.length; ++line) { var anns = annotations[line]; if (!anns) continue; var maxSeverity = null; var tipLabel = state.hasGutter && document.createDocumentFragment(); for (var i = 0; i < anns.length; ++i) { var ann = anns[i]; var severity = ann.severity; if (!SEVERITIES.test(severity)) severity = "error"; maxSeverity = getMaxSeverity(maxSeverity, severity); if (options.formatAnnotation) ann = options.formatAnnotation(ann); if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann)); if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, { className: "CodeMirror-lint-mark-" + severity, __annotation: ann })); } if (state.hasGutter) cm.setGutterMarker(line, GUTTER_ID, makeMarker(tipLabel, maxSeverity, anns.length > 1, state.options.tooltips)); } if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm); } function onChange(cm) { var state = cm.state.lint; clearTimeout(state.timeout); state.timeout = setTimeout(function(){startLinting(cm);}, state.options.delay || 500); } function popupSpanTooltip(ann, e) { var target = e.target || e.srcElement; showTooltipFor(e, annotationTooltip(ann), target); } // When the mouseover fires, the cursor might not actually be over // the character itself yet. These pairs of x,y offsets are used to // probe a few nearby points when no suitable marked range is found. var nearby = [0, 0, 0, 5, 0, -5, 5, 0, -5, 0]; function onMouseOver(cm, e) { if (!/\bCodeMirror-lint-mark-/.test((e.target || e.srcElement).className)) return; for (var i = 0; i < nearby.length; i += 2) { var spans = cm.findMarksAt(cm.coordsChar({left: e.clientX + nearby[i], top: e.clientY + nearby[i + 1]})); for (var j = 0; j < spans.length; ++j) { var span = spans[j], ann = span.__annotation; if (ann) return popupSpanTooltip(ann, e); } } } function optionHandler(cm, val, old) { if (old && old != CodeMirror.Init) { clearMarks(cm); cm.off("change", onChange); CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver); delete cm.state.lint; } if (val) { var gutters = cm.getOption("gutters"), hasLintGutter = false; for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true; var state = cm.state.lint = new LintState(cm, parseOptions(cm, val), hasLintGutter); cm.on("change", onChange); if (state.options.tooltips != false) CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); startLinting(cm); } } CodeMirror.defineOption("lintWith", false, optionHandler); // deprecated CodeMirror.defineOption("lint", false, optionHandler); // deprecated })(); ================================================ FILE: public/packages/codemirror-3.19/addon/merge/dep/diff_match_patch.js ================================================ // From https://code.google.com/p/google-diff-match-patch/ , licensed under the Apache License 2.0 (function(){function diff_match_patch(){this.Diff_Timeout=1;this.Diff_EditCost=4;this.Match_Threshold=0.5;this.Match_Distance=1E3;this.Patch_DeleteThreshold=0.5;this.Patch_Margin=4;this.Match_MaxBits=32} diff_match_patch.prototype.diff_main=function(a,b,c,d){"undefined"==typeof d&&(d=0>=this.Diff_Timeout?Number.MAX_VALUE:(new Date).getTime()+1E3*this.Diff_Timeout);if(null==a||null==b)throw Error("Null input. (diff_main)");if(a==b)return a?[[0,a]]:[];"undefined"==typeof c&&(c=!0);var e=c,f=this.diff_commonPrefix(a,b);c=a.substring(0,f);a=a.substring(f);b=b.substring(f);var f=this.diff_commonSuffix(a,b),g=a.substring(a.length-f);a=a.substring(0,a.length-f);b=b.substring(0,b.length-f);a=this.diff_compute_(a, b,e,d);c&&a.unshift([0,c]);g&&a.push([0,g]);this.diff_cleanupMerge(a);return a}; diff_match_patch.prototype.diff_compute_=function(a,b,c,d){if(!a)return[[1,b]];if(!b)return[[-1,a]];var e=a.length>b.length?a:b,f=a.length>b.length?b:a,g=e.indexOf(f);return-1!=g?(c=[[1,e.substring(0,g)],[0,f],[1,e.substring(g+f.length)]],a.length>b.length&&(c[0][0]=c[2][0]=-1),c):1==f.length?[[-1,a],[1,b]]:(e=this.diff_halfMatch_(a,b))?(f=e[0],a=e[1],g=e[2],b=e[3],e=e[4],f=this.diff_main(f,g,c,d),c=this.diff_main(a,b,c,d),f.concat([[0,e]],c)):c&&100c);v++){for(var n=-v+r;n<=v-t;n+=2){var l=g+n,m;m=n==-v||n!=v&&j[l-1]d)t+=2;else if(s>e)r+=2;else if(q&&(l=g+k-n,0<=l&&l= u)return this.diff_bisectSplit_(a,b,m,s,c)}}for(n=-v+p;n<=v-w;n+=2){l=g+n;u=n==-v||n!=v&&i[l-1]d)w+=2;else if(m>e)p+=2;else if(!q&&(l=g+k-n,0<=l&&(l=u)))return this.diff_bisectSplit_(a,b,m,s,c)}}return[[-1,a],[1,b]]}; diff_match_patch.prototype.diff_bisectSplit_=function(a,b,c,d,e){var f=a.substring(0,c),g=b.substring(0,d);a=a.substring(c);b=b.substring(d);f=this.diff_main(f,g,!1,e);e=this.diff_main(a,b,!1,e);return f.concat(e)}; diff_match_patch.prototype.diff_linesToChars_=function(a,b){function c(a){for(var b="",c=0,f=-1,g=d.length;fd?a=a.substring(c-d):c=a.length?[h,j,n,l,g]:null}if(0>=this.Diff_Timeout)return null; var d=a.length>b.length?a:b,e=a.length>b.length?b:a;if(4>d.length||2*e.lengthd[4].length?g:d:d:g;var j;a.length>b.length?(g=h[0],d=h[1],e=h[2],j=h[3]):(e=h[0],j=h[1],g=h[2],d=h[3]);h=h[4];return[g,d,e,j,h]}; diff_match_patch.prototype.diff_cleanupSemantic=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=0,h=0,j=0,i=0;f=e){if(d>=b.length/2||d>=c.length/2)a.splice(f,0,[0,c.substring(0,d)]),a[f-1][1]=b.substring(0,b.length-d),a[f+1][1]=c.substring(d),f++}else if(e>=b.length/2||e>=c.length/2)a.splice(f,0,[0,b.substring(0,e)]),a[f-1][0]=1,a[f-1][1]=c.substring(0,c.length-e),a[f+1][0]=-1,a[f+1][1]=b.substring(e),f++;f++}f++}}; diff_match_patch.prototype.diff_cleanupSemanticLossless=function(a){function b(a,b){if(!a||!b)return 6;var c=a.charAt(a.length-1),d=b.charAt(0),e=c.match(diff_match_patch.nonAlphaNumericRegex_),f=d.match(diff_match_patch.nonAlphaNumericRegex_),g=e&&c.match(diff_match_patch.whitespaceRegex_),h=f&&d.match(diff_match_patch.whitespaceRegex_),c=g&&c.match(diff_match_patch.linebreakRegex_),d=h&&d.match(diff_match_patch.linebreakRegex_),i=c&&a.match(diff_match_patch.blanklineEndRegex_),j=d&&b.match(diff_match_patch.blanklineStartRegex_); return i||j?5:c||d?4:e&&!g&&h?3:g||h?2:e||f?1:0}for(var c=1;c=i&&(i=k,g=d,h=e,j=f)}a[c-1][1]!=g&&(g?a[c-1][1]=g:(a.splice(c-1,1),c--),a[c][1]= h,j?a[c+1][1]=j:(a.splice(c+1,1),c--))}c++}};diff_match_patch.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;diff_match_patch.whitespaceRegex_=/\s/;diff_match_patch.linebreakRegex_=/[\r\n]/;diff_match_patch.blanklineEndRegex_=/\n\r?\n$/;diff_match_patch.blanklineStartRegex_=/^\r?\n\r?\n/; diff_match_patch.prototype.diff_cleanupEfficiency=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=!1,h=!1,j=!1,i=!1;fb)break;e=c;f=d}return a.length!=g&&-1===a[g][0]?f:f+(b-e)}; diff_match_patch.prototype.diff_prettyHtml=function(a){for(var b=[],c=/&/g,d=//g,f=/\n/g,g=0;g");switch(h){case 1:b[g]=''+j+"";break;case -1:b[g]=''+j+"";break;case 0:b[g]=""+j+""}}return b.join("")}; diff_match_patch.prototype.diff_text1=function(a){for(var b=[],c=0;cthis.Match_MaxBits)throw Error("Pattern too long for this browser.");var e=this.match_alphabet_(b),f=this,g=this.Match_Threshold,h=a.indexOf(b,c);-1!=h&&(g=Math.min(d(0,h),g),h=a.lastIndexOf(b,c+b.length),-1!=h&&(g=Math.min(d(0,h),g)));for(var j=1<=i;p--){var w=e[a.charAt(p-1)];k[p]=0===t?(k[p+1]<<1|1)&w:(k[p+1]<<1|1)&w|((r[p+1]|r[p])<<1|1)|r[p+1];if(k[p]&j&&(w=d(t,p-1),w<=g))if(g=w,h=p-1,h>c)i=Math.max(1,2*c-h);else break}if(d(t+1,c)>g)break;r=k}return h}; diff_match_patch.prototype.match_alphabet_=function(a){for(var b={},c=0;c=2*this.Patch_Margin&& e&&(this.patch_addContext_(a,h),c.push(a),a=new diff_match_patch.patch_obj,e=0,h=d,f=g)}1!==i&&(f+=k.length);-1!==i&&(g+=k.length)}e&&(this.patch_addContext_(a,h),c.push(a));return c};diff_match_patch.prototype.patch_deepCopy=function(a){for(var b=[],c=0;cthis.Match_MaxBits){if(j=this.match_main(b,h.substring(0,this.Match_MaxBits),g),-1!=j&&(i=this.match_main(b,h.substring(h.length-this.Match_MaxBits),g+h.length-this.Match_MaxBits),-1==i||j>=i))j=-1}else j=this.match_main(b,h,g); if(-1==j)e[f]=!1,d-=a[f].length2-a[f].length1;else if(e[f]=!0,d=j-g,g=-1==i?b.substring(j,j+h.length):b.substring(j,i+this.Match_MaxBits),h==g)b=b.substring(0,j)+this.diff_text2(a[f].diffs)+b.substring(j+h.length);else if(g=this.diff_main(h,g,!1),h.length>this.Match_MaxBits&&this.diff_levenshtein(g)/h.length>this.Patch_DeleteThreshold)e[f]=!1;else{this.diff_cleanupSemanticLossless(g);for(var h=0,k,i=0;ie[0][1].length){var f=b-e[0][1].length;e[0][1]=c.substring(e[0][1].length)+e[0][1];d.start1-=f;d.start2-=f;d.length1+=f;d.length2+=f}d=a[a.length-1];e=d.diffs;0==e.length||0!=e[e.length-1][0]?(e.push([0, c]),d.length1+=b,d.length2+=b):b>e[e.length-1][1].length&&(f=b-e[e.length-1][1].length,e[e.length-1][1]+=c.substring(0,f),d.length1+=f,d.length2+=f);return c}; diff_match_patch.prototype.patch_splitMax=function(a){for(var b=this.Match_MaxBits,c=0;c2*b?(h.length1+=i.length,e+=i.length,j=!1,h.diffs.push([g,i]),d.diffs.shift()):(i=i.substring(0,b-h.length1-this.Patch_Margin),h.length1+=i.length,e+=i.length,0===g?(h.length2+=i.length,f+=i.length):j=!1,h.diffs.push([g,i]),i==d.diffs[0][1]?d.diffs.shift():d.diffs[0][1]=d.diffs[0][1].substring(i.length))}g=this.diff_text2(h.diffs);g=g.substring(g.length-this.Patch_Margin);i=this.diff_text1(d.diffs).substring(0,this.Patch_Margin);""!==i&& (h.length1+=i.length,h.length2+=i.length,0!==h.diffs.length&&0===h.diffs[h.diffs.length-1][0]?h.diffs[h.diffs.length-1][1]+=i:h.diffs.push([0,i]));j||a.splice(++c,0,h)}}};diff_match_patch.prototype.patch_toText=function(a){for(var b=[],c=0;c now) return false; var sInfo = editor.getScrollInfo(), halfScreen = .5 * sInfo.clientHeight, midY = sInfo.top + halfScreen; var mid = editor.lineAtHeight(midY, "local"); var around = chunkBoundariesAround(dv.diff, mid, type == DIFF_INSERT); var off = getOffsets(editor, type == DIFF_INSERT ? around.edit : around.orig); var offOther = getOffsets(other, type == DIFF_INSERT ? around.orig : around.edit); var ratio = (midY - off.top) / (off.bot - off.top); var targetPos = (offOther.top - halfScreen) + ratio * (offOther.bot - offOther.top); var botDist, mix; // Some careful tweaking to make sure no space is left out of view // when scrolling to top or bottom. if (targetPos > sInfo.top && (mix = sInfo.top / halfScreen) < 1) { targetPos = targetPos * mix + sInfo.top * (1 - mix); } else if ((botDist = sInfo.height - sInfo.clientHeight - sInfo.top) < halfScreen) { var otherInfo = other.getScrollInfo(); var botDistOther = otherInfo.height - otherInfo.clientHeight - targetPos; if (botDistOther > botDist && (mix = botDist / halfScreen) < 1) targetPos = targetPos * mix + (otherInfo.height - otherInfo.clientHeight - botDist) * (1 - mix); } other.scrollTo(sInfo.left, targetPos); other.state.scrollSetAt = now; other.state.scrollSetBy = dv; return true; } function getOffsets(editor, around) { var bot = around.after; if (bot == null) bot = editor.lastLine() + 1; return {top: editor.heightAtLine(around.before || 0, "local"), bot: editor.heightAtLine(bot, "local")}; } function setScrollLock(dv, val, action) { dv.lockScroll = val; if (val && action != false) syncScroll(dv, DIFF_INSERT) && drawConnectors(dv); dv.lockButton.innerHTML = val ? "\u21db\u21da" : "\u21db  \u21da"; } // Updating the marks for editor content function clearMarks(editor, arr, classes) { for (var i = 0; i < arr.length; ++i) { var mark = arr[i]; if (mark instanceof CodeMirror.TextMarker) { mark.clear(); } else { editor.removeLineClass(mark, "background", classes.chunk); editor.removeLineClass(mark, "background", classes.start); editor.removeLineClass(mark, "background", classes.end); } } arr.length = 0; } // FIXME maybe add a margin around viewport to prevent too many updates function updateMarks(editor, diff, state, type, classes) { var vp = editor.getViewport(); editor.operation(function() { if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) { clearMarks(editor, state.marked, classes); markChanges(editor, diff, type, state.marked, vp.from, vp.to, classes); state.from = vp.from; state.to = vp.to; } else { if (vp.from < state.from) { markChanges(editor, diff, type, state.marked, vp.from, state.from, classes); state.from = vp.from; } if (vp.to > state.to) { markChanges(editor, diff, type, state.marked, state.to, vp.to, classes); state.to = vp.to; } } }); } function markChanges(editor, diff, type, marks, from, to, classes) { var pos = Pos(0, 0); var top = Pos(from, 0), bot = editor.clipPos(Pos(to - 1)); var cls = type == DIFF_DELETE ? classes.del : classes.insert; function markChunk(start, end) { var bfrom = Math.max(from, start), bto = Math.min(to, end); for (var i = bfrom; i < bto; ++i) { var line = editor.addLineClass(i, "background", classes.chunk); if (i == start) editor.addLineClass(line, "background", classes.start); if (i == end - 1) editor.addLineClass(line, "background", classes.end); marks.push(line); } // When the chunk is empty, make sure a horizontal line shows up if (start == end && bfrom == end && bto == end) { if (bfrom) marks.push(editor.addLineClass(bfrom - 1, "background", classes.end)); else marks.push(editor.addLineClass(bfrom, "background", classes.start)); } } var chunkStart = 0; for (var i = 0; i < diff.length; ++i) { var part = diff[i], tp = part[0], str = part[1]; if (tp == DIFF_EQUAL) { var cleanFrom = pos.line + (startOfLineClean(diff, i) ? 0 : 1); moveOver(pos, str); var cleanTo = pos.line + (endOfLineClean(diff, i) ? 1 : 0); if (cleanTo > cleanFrom) { if (i) markChunk(chunkStart, cleanFrom); chunkStart = cleanTo; } } else { if (tp == type) { var end = moveOver(pos, str, true); var a = posMax(top, pos), b = posMin(bot, end); if (!posEq(a, b)) marks.push(editor.markText(a, b, {className: cls})); pos = end; } } } if (chunkStart <= pos.line) markChunk(chunkStart, pos.line + 1); } // Updating the gap between editor and original function drawConnectors(dv) { if (!dv.showDifferences) return; if (dv.svg) { clear(dv.svg); var w = dv.gap.offsetWidth; attrs(dv.svg, "width", w, "height", dv.gap.offsetHeight); } clear(dv.copyButtons); var flip = dv.type == "left"; var vpEdit = dv.edit.getViewport(), vpOrig = dv.orig.getViewport(); var sTopEdit = dv.edit.getScrollInfo().top, sTopOrig = dv.orig.getScrollInfo().top; iterateChunks(dv.diff, function(topOrig, botOrig, topEdit, botEdit) { if (topEdit > vpEdit.to || botEdit < vpEdit.from || topOrig > vpOrig.to || botOrig < vpOrig.from) return; var topLpx = dv.orig.heightAtLine(topOrig, "local") - sTopOrig, top = topLpx; if (dv.svg) { var topRpx = dv.edit.heightAtLine(topEdit, "local") - sTopEdit; if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; } var botLpx = dv.orig.heightAtLine(botOrig, "local") - sTopOrig; var botRpx = dv.edit.heightAtLine(botEdit, "local") - sTopEdit; if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; } var curveTop = " C " + w/2 + " " + topRpx + " " + w/2 + " " + topLpx + " " + (w + 2) + " " + topLpx; var curveBot = " C " + w/2 + " " + botLpx + " " + w/2 + " " + botRpx + " -1 " + botRpx; attrs(dv.svg.appendChild(document.createElementNS(svgNS, "path")), "d", "M -1 " + topRpx + curveTop + " L " + (w + 2) + " " + botLpx + curveBot + " z", "class", dv.classes.connect); } var copy = dv.copyButtons.appendChild(elt("div", dv.type == "left" ? "\u21dd" : "\u21dc", "CodeMirror-merge-copy")); copy.title = "Revert chunk"; copy.chunk = {topEdit: topEdit, botEdit: botEdit, topOrig: topOrig, botOrig: botOrig}; copy.style.top = top + "px"; }); } function copyChunk(dv, chunk) { if (dv.diffOutOfDate) return; dv.edit.replaceRange(dv.orig.getRange(Pos(chunk.topOrig, 0), Pos(chunk.botOrig, 0)), Pos(chunk.topEdit, 0), Pos(chunk.botEdit, 0)); } // Merge view, containing 0, 1, or 2 diff views. var MergeView = CodeMirror.MergeView = function(node, options) { if (!(this instanceof MergeView)) return new MergeView(node, options); var origLeft = options.origLeft, origRight = options.origRight == null ? options.orig : options.origRight; var hasLeft = origLeft != null, hasRight = origRight != null; var panes = 1 + (hasLeft ? 1 : 0) + (hasRight ? 1 : 0); var wrap = [], left = this.left = null, right = this.right = null; if (hasLeft) { left = this.left = new DiffView(this, "left"); var leftPane = elt("div", null, "CodeMirror-merge-pane"); wrap.push(leftPane); wrap.push(buildGap(left)); } var editPane = elt("div", null, "CodeMirror-merge-pane"); wrap.push(editPane); if (hasRight) { right = this.right = new DiffView(this, "right"); wrap.push(buildGap(right)); var rightPane = elt("div", null, "CodeMirror-merge-pane"); wrap.push(rightPane); } (hasRight ? rightPane : editPane).className += " CodeMirror-merge-pane-rightmost"; wrap.push(elt("div", null, null, "height: 0; clear: both;")); var wrapElt = this.wrap = node.appendChild(elt("div", wrap, "CodeMirror-merge CodeMirror-merge-" + panes + "pane")); this.edit = CodeMirror(editPane, copyObj(options)); if (left) left.init(leftPane, origLeft, options); if (right) right.init(rightPane, origRight, options); var onResize = function() { if (left) drawConnectors(left); if (right) drawConnectors(right); }; CodeMirror.on(window, "resize", onResize); var resizeInterval = setInterval(function() { for (var p = wrapElt.parentNode; p && p != document.body; p = p.parentNode) {} if (!p) { clearInterval(resizeInterval); CodeMirror.off(window, "resize", onResize); } }, 5000); }; function buildGap(dv) { var lock = dv.lockButton = elt("div", null, "CodeMirror-merge-scrolllock"); lock.title = "Toggle locked scrolling"; var lockWrap = elt("div", [lock], "CodeMirror-merge-scrolllock-wrap"); CodeMirror.on(lock, "click", function() { setScrollLock(dv, !dv.lockScroll); }); dv.copyButtons = elt("div", null, "CodeMirror-merge-copybuttons-" + dv.type); CodeMirror.on(dv.copyButtons, "click", function(e) { var node = e.target || e.srcElement; if (node.chunk) copyChunk(dv, node.chunk); }); var gapElts = [dv.copyButtons, lockWrap]; var svg = document.createElementNS && document.createElementNS(svgNS, "svg"); if (svg && !svg.createSVGRect) svg = null; dv.svg = svg; if (svg) gapElts.push(svg); return dv.gap = elt("div", gapElts, "CodeMirror-merge-gap"); } MergeView.prototype = { constuctor: MergeView, editor: function() { return this.edit; }, rightOriginal: function() { return this.right && this.right.orig; }, leftOriginal: function() { return this.left && this.left.orig; }, setShowDifferences: function(val) { if (this.right) this.right.setShowDifferences(val); if (this.left) this.left.setShowDifferences(val); } }; // Operations on diffs var dmp = new diff_match_patch(); function getDiff(a, b) { var diff = dmp.diff_main(a, b); dmp.diff_cleanupSemantic(diff); // The library sometimes leaves in empty parts, which confuse the algorithm for (var i = 0; i < diff.length; ++i) { var part = diff[i]; if (!part[1]) { diff.splice(i--, 1); } else if (i && diff[i - 1][0] == part[0]) { diff.splice(i--, 1); diff[i][1] += part[1]; } } return diff; } function iterateChunks(diff, f) { var startEdit = 0, startOrig = 0; var edit = Pos(0, 0), orig = Pos(0, 0); for (var i = 0; i < diff.length; ++i) { var part = diff[i], tp = part[0]; if (tp == DIFF_EQUAL) { var startOff = startOfLineClean(diff, i) ? 0 : 1; var cleanFromEdit = edit.line + startOff, cleanFromOrig = orig.line + startOff; moveOver(edit, part[1], null, orig); var endOff = endOfLineClean(diff, i) ? 1 : 0; var cleanToEdit = edit.line + endOff, cleanToOrig = orig.line + endOff; if (cleanToEdit > cleanFromEdit) { if (i) f(startOrig, cleanFromOrig, startEdit, cleanFromEdit); startEdit = cleanToEdit; startOrig = cleanToOrig; } } else { moveOver(tp == DIFF_INSERT ? edit : orig, part[1]); } } if (startEdit <= edit.line || startOrig <= orig.line) f(startOrig, orig.line + 1, startEdit, edit.line + 1); } function endOfLineClean(diff, i) { if (i == diff.length - 1) return true; var next = diff[i + 1][1]; if (next.length == 1 || next.charCodeAt(0) != 10) return false; if (i == diff.length - 2) return true; next = diff[i + 2][1]; return next.length > 1 && next.charCodeAt(0) == 10; } function startOfLineClean(diff, i) { if (i == 0) return true; var last = diff[i - 1][1]; if (last.charCodeAt(last.length - 1) != 10) return false; if (i == 1) return true; last = diff[i - 2][1]; return last.charCodeAt(last.length - 1) == 10; } function chunkBoundariesAround(diff, n, nInEdit) { var beforeE, afterE, beforeO, afterO; iterateChunks(diff, function(fromOrig, toOrig, fromEdit, toEdit) { var fromLocal = nInEdit ? fromEdit : fromOrig; var toLocal = nInEdit ? toEdit : toOrig; if (afterE == null) { if (fromLocal > n) { afterE = fromEdit; afterO = fromOrig; } else if (toLocal > n) { afterE = toEdit; afterO = toOrig; } } if (toLocal <= n) { beforeE = toEdit; beforeO = toOrig; } else if (fromLocal <= n) { beforeE = fromEdit; beforeO = fromOrig; } }); return {edit: {before: beforeE, after: afterE}, orig: {before: beforeO, after: afterO}}; } // General utilities 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; } function clear(node) { for (var count = node.childNodes.length; count > 0; --count) node.removeChild(node.firstChild); } function attrs(elt) { for (var i = 1; i < arguments.length; i += 2) elt.setAttribute(arguments[i], arguments[i+1]); } function copyObj(obj, target) { if (!target) target = {}; for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop]; return target; } function moveOver(pos, str, copy, other) { var out = copy ? Pos(pos.line, pos.ch) : pos, at = 0; for (;;) { var nl = str.indexOf("\n", at); if (nl == -1) break; ++out.line; if (other) ++other.line; at = nl + 1; } out.ch = (at ? 0 : out.ch) + (str.length - at); if (other) other.ch = (at ? 0 : other.ch) + (str.length - at); return out; } function posMin(a, b) { return (a.line - b.line || a.ch - b.ch) < 0 ? a : b; } function posMax(a, b) { return (a.line - b.line || a.ch - b.ch) > 0 ? a : b; } function posEq(a, b) { return a.line == b.line && a.ch == b.ch; } })(); ================================================ FILE: public/packages/codemirror-3.19/addon/mode/loadmode.js ================================================ (function() { if (!CodeMirror.modeURL) CodeMirror.modeURL = "../mode/%N/%N.js"; var loading = {}; function splitCallback(cont, n) { var countDown = n; return function() { if (--countDown == 0) cont(); }; } function ensureDeps(mode, cont) { var deps = CodeMirror.modes[mode].dependencies; if (!deps) return cont(); var missing = []; for (var i = 0; i < deps.length; ++i) { if (!CodeMirror.modes.hasOwnProperty(deps[i])) missing.push(deps[i]); } if (!missing.length) return cont(); var split = splitCallback(cont, missing.length); for (var i = 0; i < missing.length; ++i) CodeMirror.requireMode(missing[i], split); } CodeMirror.requireMode = function(mode, cont) { if (typeof mode != "string") mode = mode.name; if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont); if (loading.hasOwnProperty(mode)) return loading[mode].push(cont); var script = document.createElement("script"); script.src = CodeMirror.modeURL.replace(/%N/g, mode); var others = document.getElementsByTagName("script")[0]; others.parentNode.insertBefore(script, others); var list = loading[mode] = [cont]; var count = 0, poll = setInterval(function() { if (++count > 100) return clearInterval(poll); if (CodeMirror.modes.hasOwnProperty(mode)) { clearInterval(poll); loading[mode] = null; ensureDeps(mode, function() { for (var i = 0; i < list.length; ++i) list[i](); }); } }, 200); }; CodeMirror.autoLoadMode = function(instance, mode) { if (!CodeMirror.modes.hasOwnProperty(mode)) CodeMirror.requireMode(mode, function() { instance.setOption("mode", instance.getOption("mode")); }); }; }()); ================================================ FILE: public/packages/codemirror-3.19/addon/mode/multiplex.js ================================================ CodeMirror.multiplexingMode = function(outer /*, others */) { // Others should be {open, close, mode [, delimStyle] [, innerStyle]} objects var others = Array.prototype.slice.call(arguments, 1); var n_others = others.length; function indexOf(string, pattern, from) { if (typeof pattern == "string") return string.indexOf(pattern, from); var m = pattern.exec(from ? string.slice(from) : string); return m ? m.index + from : -1; } return { startState: function() { return { outer: CodeMirror.startState(outer), innerActive: null, inner: null }; }, copyState: function(state) { return { outer: CodeMirror.copyState(outer, state.outer), innerActive: state.innerActive, inner: state.innerActive && CodeMirror.copyState(state.innerActive.mode, state.inner) }; }, token: function(stream, state) { if (!state.innerActive) { var cutOff = Infinity, oldContent = stream.string; for (var i = 0; i < n_others; ++i) { var other = others[i]; var found = indexOf(oldContent, other.open, stream.pos); if (found == stream.pos) { stream.match(other.open); state.innerActive = other; state.inner = CodeMirror.startState(other.mode, outer.indent ? outer.indent(state.outer, "") : 0); return other.delimStyle; } else if (found != -1 && found < cutOff) { cutOff = found; } } if (cutOff != Infinity) stream.string = oldContent.slice(0, cutOff); var outerToken = outer.token(stream, state.outer); if (cutOff != Infinity) stream.string = oldContent; return outerToken; } else { var curInner = state.innerActive, oldContent = stream.string; var found = indexOf(oldContent, curInner.close, stream.pos); if (found == stream.pos) { stream.match(curInner.close); state.innerActive = state.inner = null; return curInner.delimStyle; } if (found > -1) stream.string = oldContent.slice(0, found); var innerToken = curInner.mode.token(stream, state.inner); if (found > -1) stream.string = oldContent; var cur = stream.current(), found = cur.indexOf(curInner.close); if (found > -1) stream.backUp(cur.length - found); if (curInner.innerStyle) { if (innerToken) innerToken = innerToken + ' ' + curInner.innerStyle; else innerToken = curInner.innerStyle; } return innerToken; } }, indent: function(state, textAfter) { var mode = state.innerActive ? state.innerActive.mode : outer; if (!mode.indent) return CodeMirror.Pass; return mode.indent(state.innerActive ? state.inner : state.outer, textAfter); }, blankLine: function(state) { var mode = state.innerActive ? state.innerActive.mode : outer; if (mode.blankLine) { mode.blankLine(state.innerActive ? state.inner : state.outer); } if (!state.innerActive) { for (var i = 0; i < n_others; ++i) { var other = others[i]; if (other.open === "\n") { state.innerActive = other; state.inner = CodeMirror.startState(other.mode, mode.indent ? mode.indent(state.outer, "") : 0); } } } else if (state.innerActive.close === "\n") { state.innerActive = state.inner = null; } }, electricChars: outer.electricChars, innerMode: function(state) { return state.inner ? {state: state.inner, mode: state.innerActive.mode} : {state: state.outer, mode: outer}; } }; }; ================================================ FILE: public/packages/codemirror-3.19/addon/mode/multiplex_test.js ================================================ (function() { CodeMirror.defineMode("markdown_with_stex", function(){ var inner = CodeMirror.getMode({}, "stex"); var outer = CodeMirror.getMode({}, "markdown"); var innerOptions = { open: '$', close: '$', mode: inner, delimStyle: 'delim', innerStyle: 'inner' }; return CodeMirror.multiplexingMode(outer, innerOptions); }); var mode = CodeMirror.getMode({}, "markdown_with_stex"); function MT(name) { test.mode( name, mode, Array.prototype.slice.call(arguments, 1), 'multiplexing'); } MT( "stexInsideMarkdown", "[strong **Equation:**] [delim $][inner&tag \\pi][delim $]"); })(); ================================================ FILE: public/packages/codemirror-3.19/addon/mode/overlay.js ================================================ // Utility function that allows modes to be combined. The mode given // as the base argument takes care of most of the normal mode // functionality, but a second (typically simple) mode is used, which // can override the style of text. Both modes get to parse all of the // text, but when both assign a non-null style to a piece of code, the // overlay wins, unless the combine argument was true, in which case // the styles are combined. // overlayParser is the old, deprecated name CodeMirror.overlayMode = CodeMirror.overlayParser = function(base, overlay, combine) { return { startState: function() { return { base: CodeMirror.startState(base), overlay: CodeMirror.startState(overlay), basePos: 0, baseCur: null, overlayPos: 0, overlayCur: null }; }, copyState: function(state) { return { base: CodeMirror.copyState(base, state.base), overlay: CodeMirror.copyState(overlay, state.overlay), basePos: state.basePos, baseCur: null, overlayPos: state.overlayPos, overlayCur: null }; }, token: function(stream, state) { if (stream.start == state.basePos) { state.baseCur = base.token(stream, state.base); state.basePos = stream.pos; } if (stream.start == state.overlayPos) { stream.pos = stream.start; state.overlayCur = overlay.token(stream, state.overlay); state.overlayPos = stream.pos; } stream.pos = Math.min(state.basePos, state.overlayPos); if (stream.eol()) state.basePos = state.overlayPos = 0; if (state.overlayCur == null) return state.baseCur; if (state.baseCur != null && combine) return state.baseCur + " " + state.overlayCur; else return state.overlayCur; }, indent: base.indent && function(state, textAfter) { return base.indent(state.base, textAfter); }, electricChars: base.electricChars, innerMode: function(state) { return {state: state.base, mode: base}; }, blankLine: function(state) { if (base.blankLine) base.blankLine(state.base); if (overlay.blankLine) overlay.blankLine(state.overlay); } }; }; ================================================ FILE: public/packages/codemirror-3.19/addon/runmode/colorize.js ================================================ CodeMirror.colorize = (function() { var isBlock = /^(p|li|div|h\\d|pre|blockquote|td)$/; function textContent(node, out) { if (node.nodeType == 3) return out.push(node.nodeValue); for (var ch = node.firstChild; ch; ch = ch.nextSibling) { textContent(ch, out); if (isBlock.test(node.nodeType)) out.push("\n"); } } return function(collection, defaultMode) { if (!collection) collection = document.body.getElementsByTagName("pre"); for (var i = 0; i < collection.length; ++i) { var node = collection[i]; var mode = node.getAttribute("data-lang") || defaultMode; if (!mode) continue; var text = []; textContent(node, text); node.innerHTML = ""; CodeMirror.runMode(text.join(""), mode, node); node.className += " cm-s-default"; } }; })(); ================================================ FILE: public/packages/codemirror-3.19/addon/runmode/runmode-standalone.js ================================================ /* Just enough of CodeMirror to run runMode under node.js */ window.CodeMirror = {}; (function() { "use strict"; function splitLines(string){ return string.split(/\r?\n|\r/); }; function StringStream(string) { this.pos = this.start = 0; this.string = string; } StringStream.prototype = { eol: function() {return this.pos >= this.string.length;}, sol: function() {return this.pos == 0;}, peek: function() {return this.string.charAt(this.pos) || null;}, next: function() { if (this.pos < this.string.length) return this.string.charAt(this.pos++); }, eat: function(match) { var ch = this.string.charAt(this.pos); if (typeof match == "string") var ok = ch == match; else var ok = ch && (match.test ? match.test(ch) : match(ch)); if (ok) {++this.pos; return ch;} }, eatWhile: function(match) { var start = this.pos; while (this.eat(match)){} return this.pos > start; }, eatSpace: function() { var start = this.pos; while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; return this.pos > start; }, skipToEnd: function() {this.pos = this.string.length;}, skipTo: function(ch) { var found = this.string.indexOf(ch, this.pos); if (found > -1) {this.pos = found; return true;} }, backUp: function(n) {this.pos -= n;}, column: function() {return this.start;}, indentation: function() {return 0;}, 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; } }, current: function(){return this.string.slice(this.start, this.pos);} }; CodeMirror.StringStream = StringStream; CodeMirror.startState = function (mode, a1, a2) { return mode.startState ? mode.startState(a1, a2) : true; }; var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; CodeMirror.defineMode = function (name, mode) { modes[name] = mode; }; CodeMirror.defineMIME = function (mime, spec) { mimeModes[mime] = spec; }; CodeMirror.getMode = function (options, spec) { if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) spec = mimeModes[spec]; if (typeof spec == "string") var mname = spec, config = {}; else if (spec != null) var mname = spec.name, config = spec; var mfactory = modes[mname]; if (!mfactory) throw new Error("Unknown mode: " + spec); return mfactory(options, config || {}); }; CodeMirror.runMode = function (string, modespec, callback, options) { var mode = CodeMirror.getMode({ indentUnit: 2 }, modespec); if (callback.nodeType == 1) { var tabSize = (options && options.tabSize) || 4; var node = callback, col = 0; node.innerHTML = ""; callback = function (text, style) { if (text == "\n") { node.appendChild(document.createElement("br")); col = 0; return; } var content = ""; // replace tabs for (var pos = 0; ;) { var idx = text.indexOf("\t", pos); if (idx == -1) { content += text.slice(pos); col += text.length - pos; break; } else { col += idx - pos; content += text.slice(pos, idx); var size = tabSize - col % tabSize; col += size; for (var i = 0; i < size; ++i) content += " "; pos = idx + 1; } } if (style) { var sp = node.appendChild(document.createElement("span")); sp.className = "cm-" + style.replace(/ +/g, " cm-"); sp.appendChild(document.createTextNode(content)); } else { node.appendChild(document.createTextNode(content)); } }; } var lines = splitLines(string), state = CodeMirror.startState(mode); for (var i = 0, e = lines.length; i < e; ++i) { if (i) callback("\n"); var stream = new CodeMirror.StringStream(lines[i]); while (!stream.eol()) { var style = mode.token(stream, state); callback(stream.current(), style, i, stream.start, state); stream.start = stream.pos; } } }; })(); ================================================ FILE: public/packages/codemirror-3.19/addon/runmode/runmode.js ================================================ CodeMirror.runMode = function(string, modespec, callback, options) { var mode = CodeMirror.getMode(CodeMirror.defaults, modespec); var ie = /MSIE \d/.test(navigator.userAgent); var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9); if (callback.nodeType == 1) { var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize; var node = callback, col = 0; node.innerHTML = ""; callback = function(text, style) { if (text == "\n") { // Emitting LF or CRLF on IE8 or earlier results in an incorrect display. // Emitting a carriage return makes everything ok. node.appendChild(document.createTextNode(ie_lt9 ? '\r' : text)); col = 0; return; } var content = ""; // replace tabs for (var pos = 0;;) { var idx = text.indexOf("\t", pos); if (idx == -1) { content += text.slice(pos); col += text.length - pos; break; } else { col += idx - pos; content += text.slice(pos, idx); var size = tabSize - col % tabSize; col += size; for (var i = 0; i < size; ++i) content += " "; pos = idx + 1; } } if (style) { var sp = node.appendChild(document.createElement("span")); sp.className = "cm-" + style.replace(/ +/g, " cm-"); sp.appendChild(document.createTextNode(content)); } else { node.appendChild(document.createTextNode(content)); } }; } var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode); for (var i = 0, e = lines.length; i < e; ++i) { if (i) callback("\n"); var stream = new CodeMirror.StringStream(lines[i]); while (!stream.eol()) { var style = mode.token(stream, state); callback(stream.current(), style, i, stream.start, state); stream.start = stream.pos; } } }; ================================================ FILE: public/packages/codemirror-3.19/addon/runmode/runmode.node.js ================================================ /* Just enough of CodeMirror to run runMode under node.js */ function splitLines(string){ return string.split(/\r?\n|\r/); }; function StringStream(string) { this.pos = this.start = 0; this.string = string; } StringStream.prototype = { eol: function() {return this.pos >= this.string.length;}, sol: function() {return this.pos == 0;}, peek: function() {return this.string.charAt(this.pos) || null;}, next: function() { if (this.pos < this.string.length) return this.string.charAt(this.pos++); }, eat: function(match) { var ch = this.string.charAt(this.pos); if (typeof match == "string") var ok = ch == match; else var ok = ch && (match.test ? match.test(ch) : match(ch)); if (ok) {++this.pos; return ch;} }, eatWhile: function(match) { var start = this.pos; while (this.eat(match)){} return this.pos > start; }, eatSpace: function() { var start = this.pos; while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; return this.pos > start; }, skipToEnd: function() {this.pos = this.string.length;}, skipTo: function(ch) { var found = this.string.indexOf(ch, this.pos); if (found > -1) {this.pos = found; return true;} }, backUp: function(n) {this.pos -= n;}, column: function() {return this.start;}, indentation: function() {return 0;}, 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; } }, current: function(){return this.string.slice(this.start, this.pos);} }; exports.StringStream = StringStream; exports.startState = function(mode, a1, a2) { return mode.startState ? mode.startState(a1, a2) : true; }; var modes = exports.modes = {}, mimeModes = exports.mimeModes = {}; exports.defineMode = function(name, mode) { if (arguments.length > 2) { mode.dependencies = []; for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]); } modes[name] = mode; }; exports.defineMIME = function(mime, spec) { mimeModes[mime] = spec; }; exports.defineMode("null", function() { return {token: function(stream) {stream.skipToEnd();}}; }); exports.defineMIME("text/plain", "null"); exports.getMode = function(options, spec) { if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) spec = mimeModes[spec]; if (typeof spec == "string") var mname = spec, config = {}; else if (spec != null) var mname = spec.name, config = spec; var mfactory = modes[mname]; if (!mfactory) throw new Error("Unknown mode: " + spec); return mfactory(options, config || {}); }; exports.runMode = function(string, modespec, callback) { var mode = exports.getMode({indentUnit: 2}, modespec); var lines = splitLines(string), state = exports.startState(mode); for (var i = 0, e = lines.length; i < e; ++i) { if (i) callback("\n"); var stream = new exports.StringStream(lines[i]); while (!stream.eol()) { var style = mode.token(stream, state); callback(stream.current(), style, i, stream.start, state); stream.start = stream.pos; } } }; ================================================ FILE: public/packages/codemirror-3.19/addon/scroll/scrollpastend.js ================================================ (function() { "use strict"; CodeMirror.defineOption("scrollPastEnd", false, function(cm, val, old) { if (old && old != CodeMirror.Init) { cm.off("change", onChange); cm.display.lineSpace.parentNode.style.paddingBottom = ""; cm.state.scrollPastEndPadding = null; } if (val) { cm.on("change", onChange); updateBottomMargin(cm); } }); function onChange(cm, change) { if (CodeMirror.changeEnd(change).line == cm.lastLine()) updateBottomMargin(cm); } function updateBottomMargin(cm) { var padding = ""; if (cm.lineCount() > 1) { var totalH = cm.display.scroller.clientHeight - 30, lastLineH = cm.getLineHandle(cm.lastLine()).height; padding = (totalH - lastLineH) + "px"; } if (cm.state.scrollPastEndPadding != padding) { cm.state.scrollPastEndPadding = padding; cm.display.lineSpace.parentNode.style.paddingBottom = padding; cm.setSize(); } } })(); ================================================ FILE: public/packages/codemirror-3.19/addon/search/match-highlighter.js ================================================ // Highlighting text that matches the selection // // Defines an option highlightSelectionMatches, which, when enabled, // will style strings that match the selection throughout the // document. // // The option can be set to true to simply enable it, or to a // {minChars, style, showToken} object to explicitly configure it. // minChars is the minimum amount of characters that should be // selected for the behavior to occur, and style is the token style to // apply to the matches. This will be prefixed by "cm-" to create an // actual CSS class name. showToken, when enabled, will cause the // current token to be highlighted when nothing is selected. (function() { var DEFAULT_MIN_CHARS = 2; var DEFAULT_TOKEN_STYLE = "matchhighlight"; var DEFAULT_DELAY = 100; function State(options) { if (typeof options == "object") { this.minChars = options.minChars; this.style = options.style; this.showToken = options.showToken; this.delay = options.delay; } if (this.style == null) this.style = DEFAULT_TOKEN_STYLE; if (this.minChars == null) this.minChars = DEFAULT_MIN_CHARS; if (this.delay == null) this.delay = DEFAULT_DELAY; this.overlay = this.timeout = null; } CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) { if (old && old != CodeMirror.Init) { var over = cm.state.matchHighlighter.overlay; if (over) cm.removeOverlay(over); clearTimeout(cm.state.matchHighlighter.timeout); cm.state.matchHighlighter = null; cm.off("cursorActivity", cursorActivity); } if (val) { cm.state.matchHighlighter = new State(val); highlightMatches(cm); cm.on("cursorActivity", cursorActivity); } }); function cursorActivity(cm) { var state = cm.state.matchHighlighter; clearTimeout(state.timeout); state.timeout = setTimeout(function() {highlightMatches(cm);}, state.delay); } function highlightMatches(cm) { cm.operation(function() { var state = cm.state.matchHighlighter; if (state.overlay) { cm.removeOverlay(state.overlay); state.overlay = null; } if (!cm.somethingSelected() && state.showToken) { var re = state.showToken === true ? /[\w$]/ : state.showToken; var cur = cm.getCursor(), line = cm.getLine(cur.line), start = cur.ch, end = start; while (start && re.test(line.charAt(start - 1))) --start; while (end < line.length && re.test(line.charAt(end))) ++end; if (start < end) cm.addOverlay(state.overlay = makeOverlay(line.slice(start, end), re, state.style)); return; } if (cm.getCursor("head").line != cm.getCursor("anchor").line) return; var selection = cm.getSelection().replace(/^\s+|\s+$/g, ""); if (selection.length >= state.minChars) cm.addOverlay(state.overlay = makeOverlay(selection, false, state.style)); }); } function boundariesAround(stream, re) { return (!stream.start || !re.test(stream.string.charAt(stream.start - 1))) && (stream.pos == stream.string.length || !re.test(stream.string.charAt(stream.pos))); } function makeOverlay(query, hasBoundary, style) { return {token: function(stream) { if (stream.match(query) && (!hasBoundary || boundariesAround(stream, hasBoundary))) return style; stream.next(); stream.skipTo(query.charAt(0)) || stream.skipToEnd(); }}; } })(); ================================================ FILE: public/packages/codemirror-3.19/addon/search/search.js ================================================ // Define search commands. Depends on dialog.js or another // implementation of the openDialog method. // Replace works a little oddly -- it will do the replace on the next // Ctrl-G (or whatever is bound to findNext) press. You prevent a // replace by making sure the match is no longer selected when hitting // Ctrl-G. (function() { function searchOverlay(query) { if (typeof query == "string") return {token: function(stream) { if (stream.match(query)) return "searching"; stream.next(); stream.skipTo(query.charAt(0)) || stream.skipToEnd(); }}; return {token: function(stream) { if (stream.match(query)) return "searching"; while (!stream.eol()) { stream.next(); if (stream.match(query, false)) break; } }}; } function SearchState() { this.posFrom = this.posTo = this.query = null; this.overlay = null; } function getSearchState(cm) { return cm.state.search || (cm.state.search = new SearchState()); } function getSearchCursor(cm, query, pos) { // Heuristic: if the query string is all lowercase, do a case insensitive search. return cm.getSearchCursor(query, pos, typeof query == "string" && query == query.toLowerCase()); } function dialog(cm, text, shortText, f) { if (cm.openDialog) cm.openDialog(text, f); else f(prompt(shortText, "")); } function confirmDialog(cm, text, shortText, fs) { if (cm.openConfirm) cm.openConfirm(text, fs); else if (confirm(shortText)) fs[0](); } function parseQuery(query) { var isRE = query.match(/^\/(.*)\/([a-z]*)$/); return isRE ? new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i") : query; } var queryDialog = 'Search: (Use /re/ syntax for regexp search)'; function doSearch(cm, rev) { var state = getSearchState(cm); if (state.query) return findNext(cm, rev); dialog(cm, queryDialog, "Search for:", function(query) { cm.operation(function() { if (!query || state.query) return; state.query = parseQuery(query); cm.removeOverlay(state.overlay); state.overlay = searchOverlay(state.query); cm.addOverlay(state.overlay); state.posFrom = state.posTo = cm.getCursor(); findNext(cm, rev); }); }); } function findNext(cm, rev) {cm.operation(function() { var state = getSearchState(cm); var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo); if (!cursor.find(rev)) { cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0)); if (!cursor.find(rev)) return; } cm.setSelection(cursor.from(), cursor.to()); cm.scrollIntoView({from: cursor.from(), to: cursor.to()}); state.posFrom = cursor.from(); state.posTo = cursor.to(); });} function clearSearch(cm) {cm.operation(function() { var state = getSearchState(cm); if (!state.query) return; state.query = null; cm.removeOverlay(state.overlay); });} var replaceQueryDialog = 'Replace: (Use /re/ syntax for regexp search)'; var replacementQueryDialog = 'With: '; var doReplaceConfirm = "Replace? "; function replace(cm, all) { dialog(cm, replaceQueryDialog, "Replace:", function(query) { if (!query) return; query = parseQuery(query); dialog(cm, replacementQueryDialog, "Replace with:", function(text) { if (all) { cm.operation(function() { for (var cursor = getSearchCursor(cm, query); cursor.findNext();) { if (typeof query != "string") { var match = cm.getRange(cursor.from(), cursor.to()).match(query); cursor.replace(text.replace(/\$(\d)/, function(_, i) {return match[i];})); } else cursor.replace(text); } }); } else { clearSearch(cm); var cursor = getSearchCursor(cm, query, cm.getCursor()); var advance = function() { var start = cursor.from(), match; if (!(match = cursor.findNext())) { cursor = getSearchCursor(cm, query); if (!(match = cursor.findNext()) || (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return; } cm.setSelection(cursor.from(), cursor.to()); cm.scrollIntoView({from: cursor.from(), to: cursor.to()}); confirmDialog(cm, doReplaceConfirm, "Replace?", [function() {doReplace(match);}, advance]); }; var doReplace = function(match) { cursor.replace(typeof query == "string" ? text : text.replace(/\$(\d)/, function(_, i) {return match[i];})); advance(); }; advance(); } }); }); } CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);}; CodeMirror.commands.findNext = doSearch; CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);}; CodeMirror.commands.clearSearch = clearSearch; CodeMirror.commands.replace = replace; CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);}; })(); ================================================ FILE: public/packages/codemirror-3.19/addon/search/searchcursor.js ================================================ (function(){ var Pos = CodeMirror.Pos; function SearchCursor(doc, query, pos, caseFold) { this.atOccurrence = false; this.doc = doc; if (caseFold == null && typeof query == "string") caseFold = false; pos = pos ? doc.clipPos(pos) : Pos(0, 0); this.pos = {from: pos, to: pos}; // The matches method is filled in based on the type of query. // It takes a position and a direction, and returns an object // describing the next occurrence of the query, or null if no // more matches were found. if (typeof query != "string") { // Regexp match if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "ig" : "g"); this.matches = function(reverse, pos) { if (reverse) { query.lastIndex = 0; var line = doc.getLine(pos.line).slice(0, pos.ch), cutOff = 0, match, start; for (;;) { query.lastIndex = cutOff; var newMatch = query.exec(line); if (!newMatch) break; match = newMatch; start = match.index; cutOff = match.index + (match[0].length || 1); if (cutOff == line.length) break; } var matchLen = (match && match[0].length) || 0; if (!matchLen) { if (start == 0 && line.length == 0) {match = undefined;} else if (start != doc.getLine(pos.line).length) { matchLen++; } } } else { query.lastIndex = pos.ch; var line = doc.getLine(pos.line), match = query.exec(line); var matchLen = (match && match[0].length) || 0; var start = match && match.index; if (start + matchLen != line.length && !matchLen) matchLen = 1; } if (match && matchLen) return {from: Pos(pos.line, start), to: Pos(pos.line, start + matchLen), match: match}; }; } else { // String query if (caseFold) query = query.toLowerCase(); var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;}; var target = query.split("\n"); // Different methods for single-line and multi-line queries if (target.length == 1) { if (!query.length) { // Empty string would match anything and never progress, so // we define it to match nothing instead. this.matches = function() {}; } else { this.matches = function(reverse, pos) { var line = fold(doc.getLine(pos.line)), len = query.length, match; if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1) : (match = line.indexOf(query, pos.ch)) != -1) return {from: Pos(pos.line, match), to: Pos(pos.line, match + len)}; }; } } else { this.matches = function(reverse, pos) { var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(doc.getLine(ln)); var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match)); if (reverse ? offsetA > pos.ch || offsetA != match.length : offsetA < pos.ch || offsetA != line.length - match.length) return; for (;;) { if (reverse ? !ln : ln == doc.lineCount() - 1) return; line = fold(doc.getLine(ln += reverse ? -1 : 1)); match = target[reverse ? --idx : ++idx]; if (idx > 0 && idx < target.length - 1) { if (line != match) return; else continue; } var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length); if (reverse ? offsetB != line.length - match.length : offsetB != match.length) return; var start = Pos(pos.line, offsetA), end = Pos(ln, offsetB); return {from: reverse ? end : start, to: reverse ? start : end}; } }; } } } SearchCursor.prototype = { findNext: function() {return this.find(false);}, findPrevious: function() {return this.find(true);}, find: function(reverse) { var self = this, pos = this.doc.clipPos(reverse ? this.pos.from : this.pos.to); function savePosAndFail(line) { var pos = Pos(line, 0); self.pos = {from: pos, to: pos}; self.atOccurrence = false; return false; } for (;;) { if (this.pos = this.matches(reverse, pos)) { if (!this.pos.from || !this.pos.to) { console.log(this.matches, this.pos); } this.atOccurrence = true; return this.pos.match || true; } if (reverse) { if (!pos.line) return savePosAndFail(0); pos = Pos(pos.line-1, this.doc.getLine(pos.line-1).length); } else { var maxLine = this.doc.lineCount(); if (pos.line == maxLine - 1) return savePosAndFail(maxLine); pos = Pos(pos.line + 1, 0); } } }, from: function() {if (this.atOccurrence) return this.pos.from;}, to: function() {if (this.atOccurrence) return this.pos.to;}, replace: function(newText) { if (!this.atOccurrence) return; var lines = CodeMirror.splitLines(newText); this.doc.replaceRange(lines, this.pos.from, this.pos.to); this.pos.to = Pos(this.pos.from.line + lines.length - 1, lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0)); } }; CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) { return new SearchCursor(this.doc, query, pos, caseFold); }); CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) { return new SearchCursor(this, query, pos, caseFold); }); })(); ================================================ FILE: public/packages/codemirror-3.19/addon/selection/active-line.js ================================================ // Because sometimes you need to style the cursor's line. // // Adds an option 'styleActiveLine' which, when enabled, gives the // active line's wrapping
            the CSS class "CodeMirror-activeline", // and gives its background
            the class "CodeMirror-activeline-background". (function() { "use strict"; var WRAP_CLASS = "CodeMirror-activeline"; var BACK_CLASS = "CodeMirror-activeline-background"; CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) { var prev = old && old != CodeMirror.Init; if (val && !prev) { updateActiveLine(cm); cm.on("cursorActivity", updateActiveLine); } else if (!val && prev) { cm.off("cursorActivity", updateActiveLine); clearActiveLine(cm); delete cm.state.activeLine; } }); function clearActiveLine(cm) { if ("activeLine" in cm.state) { cm.removeLineClass(cm.state.activeLine, "wrap", WRAP_CLASS); cm.removeLineClass(cm.state.activeLine, "background", BACK_CLASS); } } function updateActiveLine(cm) { var line = cm.getLineHandleVisualStart(cm.getCursor().line); if (cm.state.activeLine == line) return; clearActiveLine(cm); cm.addLineClass(line, "wrap", WRAP_CLASS); cm.addLineClass(line, "background", BACK_CLASS); cm.state.activeLine = line; } })(); ================================================ FILE: public/packages/codemirror-3.19/addon/selection/mark-selection.js ================================================ // Because sometimes you need to mark the selected *text*. // // Adds an option 'styleSelectedText' which, when enabled, gives // selected text the CSS class given as option value, or // "CodeMirror-selectedtext" when the value is not a string. (function() { "use strict"; CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) { var prev = old && old != CodeMirror.Init; if (val && !prev) { cm.state.markedSelection = []; cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext"; reset(cm); cm.on("cursorActivity", onCursorActivity); cm.on("change", onChange); } else if (!val && prev) { cm.off("cursorActivity", onCursorActivity); cm.off("change", onChange); clear(cm); cm.state.markedSelection = cm.state.markedSelectionStyle = null; } }); function onCursorActivity(cm) { cm.operation(function() { update(cm); }); } function onChange(cm) { if (cm.state.markedSelection.length) cm.operation(function() { clear(cm); }); } var CHUNK_SIZE = 8; var Pos = CodeMirror.Pos; function cmp(pos1, pos2) { return pos1.line - pos2.line || pos1.ch - pos2.ch; } function coverRange(cm, from, to, addAt) { if (cmp(from, to) == 0) return; var array = cm.state.markedSelection; var cls = cm.state.markedSelectionStyle; for (var line = from.line;;) { var start = line == from.line ? from : Pos(line, 0); var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line; var end = atEnd ? to : Pos(endLine, 0); var mark = cm.markText(start, end, {className: cls}); if (addAt == null) array.push(mark); else array.splice(addAt++, 0, mark); if (atEnd) break; line = endLine; } } function clear(cm) { var array = cm.state.markedSelection; for (var i = 0; i < array.length; ++i) array[i].clear(); array.length = 0; } function reset(cm) { clear(cm); var from = cm.getCursor("start"), to = cm.getCursor("end"); coverRange(cm, from, to); } function update(cm) { var from = cm.getCursor("start"), to = cm.getCursor("end"); if (cmp(from, to) == 0) return clear(cm); var array = cm.state.markedSelection; if (!array.length) return coverRange(cm, from, to); var coverStart = array[0].find(), coverEnd = array[array.length - 1].find(); if (!coverStart || !coverEnd || to.line - from.line < CHUNK_SIZE || cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0) return reset(cm); while (cmp(from, coverStart.from) > 0) { array.shift().clear(); coverStart = array[0].find(); } if (cmp(from, coverStart.from) < 0) { if (coverStart.to.line - from.line < CHUNK_SIZE) { array.shift().clear(); coverRange(cm, from, coverStart.to, 0); } else { coverRange(cm, from, coverStart.from, 0); } } while (cmp(to, coverEnd.to) < 0) { array.pop().clear(); coverEnd = array[array.length - 1].find(); } if (cmp(to, coverEnd.to) > 0) { if (to.line - coverEnd.from.line < CHUNK_SIZE) { array.pop().clear(); coverRange(cm, coverEnd.from, to); } else { coverRange(cm, coverEnd.to, to); } } } })(); ================================================ FILE: public/packages/codemirror-3.19/addon/tern/tern.css ================================================ .CodeMirror-Tern-completion { padding-left: 22px; position: relative; } .CodeMirror-Tern-completion:before { position: absolute; left: 2px; bottom: 2px; border-radius: 50%; font-size: 12px; font-weight: bold; height: 15px; width: 15px; line-height: 16px; text-align: center; color: white; -moz-box-sizing: border-box; box-sizing: border-box; } .CodeMirror-Tern-completion-unknown:before { content: "?"; background: #4bb; } .CodeMirror-Tern-completion-object:before { content: "O"; background: #77c; } .CodeMirror-Tern-completion-fn:before { content: "F"; background: #7c7; } .CodeMirror-Tern-completion-array:before { content: "A"; background: #c66; } .CodeMirror-Tern-completion-number:before { content: "1"; background: #999; } .CodeMirror-Tern-completion-string:before { content: "S"; background: #999; } .CodeMirror-Tern-completion-bool:before { content: "B"; background: #999; } .CodeMirror-Tern-completion-guess { color: #999; } .CodeMirror-Tern-tooltip { border: 1px solid silver; border-radius: 3px; color: #444; padding: 2px 5px; font-size: 90%; font-family: monospace; background-color: white; white-space: pre-wrap; max-width: 40em; position: absolute; z-index: 10; -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2); -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2); box-shadow: 2px 3px 5px rgba(0,0,0,.2); transition: opacity 1s; -moz-transition: opacity 1s; -webkit-transition: opacity 1s; -o-transition: opacity 1s; -ms-transition: opacity 1s; } .CodeMirror-Tern-hint-doc { max-width: 25em; } .CodeMirror-Tern-fname { color: black; } .CodeMirror-Tern-farg { color: #70a; } .CodeMirror-Tern-farg-current { text-decoration: underline; } .CodeMirror-Tern-type { color: #07c; } .CodeMirror-Tern-fhint-guess { opacity: .7; } ================================================ FILE: public/packages/codemirror-3.19/addon/tern/tern.js ================================================ // Glue code between CodeMirror and Tern. // // Create a CodeMirror.TernServer to wrap an actual Tern server, // register open documents (CodeMirror.Doc instances) with it, and // call its methods to activate the assisting functions that Tern // provides. // // Options supported (all optional): // * defs: An array of JSON definition data structures. // * plugins: An object mapping plugin names to configuration // options. // * getFile: A function(name, c) that can be used to access files in // the project that haven't been loaded yet. Simply do c(null) to // indicate that a file is not available. // * fileFilter: A function(value, docName, doc) that will be applied // to documents before passing them on to Tern. // * switchToDoc: A function(name) that should, when providing a // multi-file view, switch the view or focus to the named file. // * showError: A function(editor, message) that can be used to // override the way errors are displayed. // * completionTip: Customize the content in tooltips for completions. // Is passed a single argument—the completion's data as returned by // Tern—and may return a string, DOM node, or null to indicate that // no tip should be shown. By default the docstring is shown. // * typeTip: Like completionTip, but for the tooltips shown for type // queries. // * responseFilter: A function(doc, query, request, error, data) that // will be applied to the Tern responses before treating them // // // It is possible to run the Tern server in a web worker by specifying // these additional options: // * useWorker: Set to true to enable web worker mode. You'll probably // want to feature detect the actual value you use here, for example // !!window.Worker. // * workerScript: The main script of the worker. Point this to // wherever you are hosting worker.js from this directory. // * workerDeps: An array of paths pointing (relative to workerScript) // to the Acorn and Tern libraries and any Tern plugins you want to // load. Or, if you minified those into a single script and included // them in the workerScript, simply leave this undefined. (function() { "use strict"; // declare global: tern CodeMirror.TernServer = function(options) { var self = this; this.options = options || {}; var plugins = this.options.plugins || (this.options.plugins = {}); if (!plugins.doc_comment) plugins.doc_comment = true; if (this.options.useWorker) { this.server = new WorkerServer(this); } else { this.server = new tern.Server({ getFile: function(name, c) { return getFile(self, name, c); }, async: true, defs: this.options.defs || [], plugins: plugins }); } this.docs = Object.create(null); this.trackChange = function(doc, change) { trackChange(self, doc, change); }; this.cachedArgHints = null; this.activeArgHints = null; this.jumpStack = []; }; CodeMirror.TernServer.prototype = { addDoc: function(name, doc) { var data = {doc: doc, name: name, changed: null}; this.server.addFile(name, docValue(this, data)); CodeMirror.on(doc, "change", this.trackChange); return this.docs[name] = data; }, delDoc: function(name) { var found = this.docs[name]; if (!found) return; CodeMirror.off(found.doc, "change", this.trackChange); delete this.docs[name]; this.server.delFile(name); }, hideDoc: function(name) { closeArgHints(this); var found = this.docs[name]; if (found && found.changed) sendDoc(this, found); }, complete: function(cm) { var self = this; CodeMirror.showHint(cm, function(cm, c) { return hint(self, cm, c); }, {async: true}); }, getHint: function(cm, c) { return hint(this, cm, c); }, showType: function(cm) { showType(this, cm); }, updateArgHints: function(cm) { updateArgHints(this, cm); }, jumpToDef: function(cm) { jumpToDef(this, cm); }, jumpBack: function(cm) { jumpBack(this, cm); }, rename: function(cm) { rename(this, cm); }, request: function (cm, query, c) { var self = this; var doc = findDoc(this, cm.getDoc()); var request = buildRequest(this, doc, query); this.server.request(request, function (error, data) { if (!error && self.options.responseFilter) data = self.options.responseFilter(doc, query, request, error, data); c(error, data); }); } }; var Pos = CodeMirror.Pos; var cls = "CodeMirror-Tern-"; var bigDoc = 250; function getFile(ts, name, c) { var buf = ts.docs[name]; if (buf) c(docValue(ts, buf)); else if (ts.options.getFile) ts.options.getFile(name, c); else c(null); } function findDoc(ts, doc, name) { for (var n in ts.docs) { var cur = ts.docs[n]; if (cur.doc == doc) return cur; } if (!name) for (var i = 0;; ++i) { n = "[doc" + (i || "") + "]"; if (!ts.docs[n]) { name = n; break; } } return ts.addDoc(name, doc); } function trackChange(ts, doc, change) { var data = findDoc(ts, doc); var argHints = ts.cachedArgHints; if (argHints && argHints.doc == doc && cmpPos(argHints.start, change.to) <= 0) ts.cachedArgHints = null; var changed = data.changed; if (changed == null) data.changed = changed = {from: change.from.line, to: change.from.line}; var end = change.from.line + (change.text.length - 1); if (change.from.line < changed.to) changed.to = changed.to - (change.to.line - end); if (end >= changed.to) changed.to = end + 1; if (changed.from > change.from.line) changed.from = change.from.line; if (doc.lineCount() > bigDoc && change.to - changed.from > 100) setTimeout(function() { if (data.changed && data.changed.to - data.changed.from > 100) sendDoc(ts, data); }, 200); } function sendDoc(ts, doc) { ts.server.request({files: [{type: "full", name: doc.name, text: docValue(ts, doc)}]}, function(error) { if (error) console.error(error); else doc.changed = null; }); } // Completion function hint(ts, cm, c) { ts.request(cm, {type: "completions", types: true, docs: true, urls: true}, function(error, data) { if (error) return showError(ts, cm, error); var completions = [], after = ""; var from = data.start, to = data.end; if (cm.getRange(Pos(from.line, from.ch - 2), from) == "[\"" && cm.getRange(to, Pos(to.line, to.ch + 2)) != "\"]") after = "\"]"; for (var i = 0; i < data.completions.length; ++i) { var completion = data.completions[i], className = typeToIcon(completion.type); if (data.guess) className += " " + cls + "guess"; completions.push({text: completion.name + after, displayText: completion.name, className: className, data: completion}); } var obj = {from: from, to: to, list: completions}; var tooltip = null; CodeMirror.on(obj, "close", function() { remove(tooltip); }); CodeMirror.on(obj, "update", function() { remove(tooltip); }); CodeMirror.on(obj, "select", function(cur, node) { remove(tooltip); var content = ts.options.completionTip ? ts.options.completionTip(cur.data) : cur.data.doc; if (content) { tooltip = makeTooltip(node.parentNode.getBoundingClientRect().right + window.pageXOffset, node.getBoundingClientRect().top + window.pageYOffset, content); tooltip.className += " " + cls + "hint-doc"; } }); c(obj); }); } function typeToIcon(type) { var suffix; if (type == "?") suffix = "unknown"; else if (type == "number" || type == "string" || type == "bool") suffix = type; else if (/^fn\(/.test(type)) suffix = "fn"; else if (/^\[/.test(type)) suffix = "array"; else suffix = "object"; return cls + "completion " + cls + "completion-" + suffix; } // Type queries function showType(ts, cm) { ts.request(cm, "type", function(error, data) { if (error) return showError(ts, cm, error); if (ts.options.typeTip) { var tip = ts.options.typeTip(data); } else { var tip = elt("span", null, elt("strong", null, data.type || "not found")); if (data.doc) tip.appendChild(document.createTextNode(" — " + data.doc)); if (data.url) { tip.appendChild(document.createTextNode(" ")); tip.appendChild(elt("a", null, "[docs]")).href = data.url; } } tempTooltip(cm, tip); }); } // Maintaining argument hints function updateArgHints(ts, cm) { closeArgHints(ts); if (cm.somethingSelected()) return; var state = cm.getTokenAt(cm.getCursor()).state; var inner = CodeMirror.innerMode(cm.getMode(), state); if (inner.mode.name != "javascript") return; var lex = inner.state.lexical; if (lex.info != "call") return; var ch, pos = lex.pos || 0, tabSize = cm.getOption("tabSize"); for (var line = cm.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line) { var str = cm.getLine(line), extra = 0; for (var pos = 0;;) { var tab = str.indexOf("\t", pos); if (tab == -1) break; extra += tabSize - (tab + extra) % tabSize - 1; pos = tab + 1; } ch = lex.column - extra; if (str.charAt(ch) == "(") {found = true; break;} } if (!found) return; var start = Pos(line, ch); var cache = ts.cachedArgHints; if (cache && cache.doc == cm.getDoc() && cmpPos(start, cache.start) == 0) return showArgHints(ts, cm, pos); ts.request(cm, {type: "type", preferFunction: true, end: start}, function(error, data) { if (error || !data.type || !(/^fn\(/).test(data.type)) return; ts.cachedArgHints = { start: pos, type: parseFnType(data.type), name: data.exprName || data.name || "fn", guess: data.guess, doc: cm.getDoc() }; showArgHints(ts, cm, pos); }); } function showArgHints(ts, cm, pos) { closeArgHints(ts); var cache = ts.cachedArgHints, tp = cache.type; var tip = elt("span", cache.guess ? cls + "fhint-guess" : null, elt("span", cls + "fname", cache.name), "("); for (var i = 0; i < tp.args.length; ++i) { if (i) tip.appendChild(document.createTextNode(", ")); var arg = tp.args[i]; tip.appendChild(elt("span", cls + "farg" + (i == pos ? " " + cls + "farg-current" : ""), arg.name || "?")); if (arg.type != "?") { tip.appendChild(document.createTextNode(":\u00a0")); tip.appendChild(elt("span", cls + "type", arg.type)); } } tip.appendChild(document.createTextNode(tp.rettype ? ") ->\u00a0" : ")")); if (tp.rettype) tip.appendChild(elt("span", cls + "type", tp.rettype)); var place = cm.cursorCoords(null, "page"); ts.activeArgHints = makeTooltip(place.right + 1, place.bottom, tip); } function parseFnType(text) { var args = [], pos = 3; function skipMatching(upto) { var depth = 0, start = pos; for (;;) { var next = text.charAt(pos); if (upto.test(next) && !depth) return text.slice(start, pos); if (/[{\[\(]/.test(next)) ++depth; else if (/[}\]\)]/.test(next)) --depth; ++pos; } } // Parse arguments if (text.charAt(pos) != ")") for (;;) { var name = text.slice(pos).match(/^([^, \(\[\{]+): /); if (name) { pos += name[0].length; name = name[1]; } args.push({name: name, type: skipMatching(/[\),]/)}); if (text.charAt(pos) == ")") break; pos += 2; } var rettype = text.slice(pos).match(/^\) -> (.*)$/); return {args: args, rettype: rettype && rettype[1]}; } // Moving to the definition of something function jumpToDef(ts, cm) { function inner(varName) { var req = {type: "definition", variable: varName || null}; var doc = findDoc(ts, cm.getDoc()); ts.server.request(buildRequest(ts, doc, req), function(error, data) { if (error) return showError(ts, cm, error); if (!data.file && data.url) { window.open(data.url); return; } if (data.file) { var localDoc = ts.docs[data.file], found; if (localDoc && (found = findContext(localDoc.doc, data))) { ts.jumpStack.push({file: doc.name, start: cm.getCursor("from"), end: cm.getCursor("to")}); moveTo(ts, doc, localDoc, found.start, found.end); return; } } showError(ts, cm, "Could not find a definition."); }); } if (!atInterestingExpression(cm)) dialog(cm, "Jump to variable", function(name) { if (name) inner(name); }); else inner(); } function jumpBack(ts, cm) { var pos = ts.jumpStack.pop(), doc = pos && ts.docs[pos.file]; if (!doc) return; moveTo(ts, findDoc(ts, cm.getDoc()), doc, pos.start, pos.end); } function moveTo(ts, curDoc, doc, start, end) { doc.doc.setSelection(end, start); if (curDoc != doc && ts.options.switchToDoc) { closeArgHints(ts); ts.options.switchToDoc(doc.name); } } // The {line,ch} representation of positions makes this rather awkward. function findContext(doc, data) { var before = data.context.slice(0, data.contextOffset).split("\n"); var startLine = data.start.line - (before.length - 1); var start = Pos(startLine, (before.length == 1 ? data.start.ch : doc.getLine(startLine).length) - before[0].length); var text = doc.getLine(startLine).slice(start.ch); for (var cur = startLine + 1; cur < doc.lineCount() && text.length < data.context.length; ++cur) text += "\n" + doc.getLine(cur); if (text.slice(0, data.context.length) == data.context) return data; var cursor = doc.getSearchCursor(data.context, 0, false); var nearest, nearestDist = Infinity; while (cursor.findNext()) { var from = cursor.from(), dist = Math.abs(from.line - start.line) * 10000; if (!dist) dist = Math.abs(from.ch - start.ch); if (dist < nearestDist) { nearest = from; nearestDist = dist; } } if (!nearest) return null; if (before.length == 1) nearest.ch += before[0].length; else nearest = Pos(nearest.line + (before.length - 1), before[before.length - 1].length); if (data.start.line == data.end.line) var end = Pos(nearest.line, nearest.ch + (data.end.ch - data.start.ch)); else var end = Pos(nearest.line + (data.end.line - data.start.line), data.end.ch); return {start: nearest, end: end}; } function atInterestingExpression(cm) { var pos = cm.getCursor("end"), tok = cm.getTokenAt(pos); if (tok.start < pos.ch && (tok.type == "comment" || tok.type == "string")) return false; return /\w/.test(cm.getLine(pos.line).slice(Math.max(pos.ch - 1, 0), pos.ch + 1)); } // Variable renaming function rename(ts, cm) { var token = cm.getTokenAt(cm.getCursor()); if (!/\w/.test(token.string)) showError(ts, cm, "Not at a variable"); dialog(cm, "New name for " + token.string, function(newName) { ts.request(cm, {type: "rename", newName: newName, fullDocs: true}, function(error, data) { if (error) return showError(ts, cm, error); applyChanges(ts, data.changes); }); }); } var nextChangeOrig = 0; function applyChanges(ts, changes) { var perFile = Object.create(null); for (var i = 0; i < changes.length; ++i) { var ch = changes[i]; (perFile[ch.file] || (perFile[ch.file] = [])).push(ch); } for (var file in perFile) { var known = ts.docs[file], chs = perFile[file];; if (!known) continue; chs.sort(function(a, b) { return cmpPos(b.start, a.start); }); var origin = "*rename" + (++nextChangeOrig); for (var i = 0; i < chs.length; ++i) { var ch = chs[i]; known.doc.replaceRange(ch.text, ch.start, ch.end, origin); } } } // Generic request-building helper function buildRequest(ts, doc, query) { var files = [], offsetLines = 0, allowFragments = !query.fullDocs; if (!allowFragments) delete query.fullDocs; if (typeof query == "string") query = {type: query}; query.lineCharPositions = true; if (query.end == null) { query.end = doc.doc.getCursor("end"); if (doc.doc.somethingSelected()) query.start = doc.doc.getCursor("start"); } var startPos = query.start || query.end; if (doc.changed) { if (doc.doc.lineCount() > bigDoc && allowFragments !== false && doc.changed.to - doc.changed.from < 100 && doc.changed.from <= startPos.line && doc.changed.to > query.end.line) { files.push(getFragmentAround(doc, startPos, query.end)); query.file = "#0"; var offsetLines = files[0].offsetLines; if (query.start != null) query.start = Pos(query.start.line - -offsetLines, query.start.ch); query.end = Pos(query.end.line - offsetLines, query.end.ch); } else { files.push({type: "full", name: doc.name, text: docValue(ts, doc)}); query.file = doc.name; doc.changed = null; } } else { query.file = doc.name; } for (var name in ts.docs) { var cur = ts.docs[name]; if (cur.changed && cur != doc) { files.push({type: "full", name: cur.name, text: docValue(ts, cur)}); cur.changed = null; } } return {query: query, files: files}; } function getFragmentAround(data, start, end) { var doc = data.doc; var minIndent = null, minLine = null, endLine, tabSize = 4; for (var p = start.line - 1, min = Math.max(0, p - 50); p >= min; --p) { var line = doc.getLine(p), fn = line.search(/\bfunction\b/); if (fn < 0) continue; var indent = CodeMirror.countColumn(line, null, tabSize); if (minIndent != null && minIndent <= indent) continue; minIndent = indent; minLine = p; } if (minLine == null) minLine = min; var max = Math.min(doc.lastLine(), end.line + 20); if (minIndent == null || minIndent == CodeMirror.countColumn(doc.getLine(start.line), null, tabSize)) endLine = max; else for (endLine = end.line + 1; endLine < max; ++endLine) { var indent = CodeMirror.countColumn(doc.getLine(endLine), null, tabSize); if (indent <= minIndent) break; } var from = Pos(minLine, 0); return {type: "part", name: data.name, offsetLines: from.line, text: doc.getRange(from, Pos(endLine, 0))}; } // Generic utilities function cmpPos(a, b) { return a.line - b.line || a.ch - b.ch; } function elt(tagname, cls /*, ... elts*/) { var e = document.createElement(tagname); if (cls) e.className = cls; for (var i = 2; i < arguments.length; ++i) { var elt = arguments[i]; if (typeof elt == "string") elt = document.createTextNode(elt); e.appendChild(elt); } return e; } function dialog(cm, text, f) { if (cm.openDialog) cm.openDialog(text + ": ", f); else f(prompt(text, "")); } // Tooltips function tempTooltip(cm, content) { var where = cm.cursorCoords(); var tip = makeTooltip(where.right + 1, where.bottom, content); function clear() { if (!tip.parentNode) return; cm.off("cursorActivity", clear); fadeOut(tip); } setTimeout(clear, 1700); cm.on("cursorActivity", clear); } function makeTooltip(x, y, content) { var node = elt("div", cls + "tooltip", content); node.style.left = x + "px"; node.style.top = y + "px"; document.body.appendChild(node); return node; } function remove(node) { var p = node && node.parentNode; if (p) p.removeChild(node); } function fadeOut(tooltip) { tooltip.style.opacity = "0"; setTimeout(function() { remove(tooltip); }, 1100); } function showError(ts, cm, msg) { if (ts.options.showError) ts.options.showError(cm, msg); else tempTooltip(cm, String(msg)); } function closeArgHints(ts) { if (ts.activeArgHints) { remove(ts.activeArgHints); ts.activeArgHints = null; } } function docValue(ts, doc) { var val = doc.doc.getValue(); if (ts.options.fileFilter) val = ts.options.fileFilter(val, doc.name, doc.doc); return val; } // Worker wrapper function WorkerServer(ts) { var worker = new Worker(ts.options.workerScript); worker.postMessage({type: "init", defs: ts.options.defs, plugins: ts.options.plugins, scripts: ts.options.workerDeps}); var msgId = 0, pending = {}; function send(data, c) { if (c) { data.id = ++msgId; pending[msgId] = c; } worker.postMessage(data); } worker.onmessage = function(e) { var data = e.data; if (data.type == "getFile") { getFile(ts, data.name, function(err, text) { send({type: "getFile", err: String(err), text: text, id: data.id}); }); } else if (data.type == "debug") { console.log(data.message); } else if (data.id && pending[data.id]) { pending[data.id](data.err, data.body); delete pending[data.id]; } }; worker.onerror = function(e) { for (var id in pending) pending[id](e); pending = {}; }; this.addFile = function(name, text) { send({type: "add", name: name, text: text}); }; this.delFile = function(name) { send({type: "del", name: name}); }; this.request = function(body, c) { send({type: "req", body: body}, c); }; } })(); ================================================ FILE: public/packages/codemirror-3.19/addon/tern/worker.js ================================================ // declare global: tern, server var server; this.onmessage = function(e) { var data = e.data; switch (data.type) { case "init": return startServer(data.defs, data.plugins, data.scripts); case "add": return server.addFile(data.name, data.text); case "del": return server.delFile(data.name); case "req": return server.request(data.body, function(err, reqData) { postMessage({id: data.id, body: reqData, err: err && String(err)}); }); case "getFile": var c = pending[data.id]; delete pending[data.id]; return c(data.err, data.text); default: throw new Error("Unknown message type: " + data.type); } }; var nextId = 0, pending = {}; function getFile(file, c) { postMessage({type: "getFile", name: file, id: ++nextId}); pending[nextId] = c; } function startServer(defs, plugins, scripts) { if (scripts) importScripts.apply(null, scripts); server = new tern.Server({ getFile: getFile, async: true, defs: defs, plugins: plugins }); } var console = { log: function(v) { postMessage({type: "debug", message: v}); } }; ================================================ FILE: public/packages/codemirror-3.19/addon/wrap/hardwrap.js ================================================ (function() { "use strict"; var Pos = CodeMirror.Pos; function findParagraph(cm, pos, options) { var startRE = options.paragraphStart || cm.getHelper(pos, "paragraphStart"); for (var start = pos.line, first = cm.firstLine(); start > first; --start) { var line = cm.getLine(start); if (startRE && startRE.test(line)) break; if (!/\S/.test(line)) { ++start; break; } } var endRE = options.paragraphEnd || cm.getHelper(pos, "paragraphEnd"); for (var end = pos.line + 1, last = cm.lastLine(); end <= last; ++end) { var line = cm.getLine(end); if (endRE && endRE.test(line)) { ++end; break; } if (!/\S/.test(line)) break; } return {from: start, to: end}; } function findBreakPoint(text, column, wrapOn, killTrailingSpace) { for (var at = column; at > 0; --at) if (wrapOn.test(text.slice(at - 1, at + 1))) break; if (at == 0) at = column; var endOfText = at; if (killTrailingSpace) while (text.charAt(endOfText - 1) == " ") --endOfText; return {from: endOfText, to: at}; } function wrapRange(cm, from, to, options) { from = cm.clipPos(from); to = cm.clipPos(to); var column = options.column || 80; var wrapOn = options.wrapOn || /\s\S|-[^\.\d]/; var killTrailing = options.killTrailingSpace !== false; var changes = [], curLine = "", curNo = from.line; var lines = cm.getRange(from, to, false); for (var i = 0; i < lines.length; ++i) { var text = lines[i], oldLen = curLine.length, spaceInserted = 0; if (curLine && text && !wrapOn.test(curLine.charAt(curLine.length - 1) + text.charAt(0))) { curLine += " "; spaceInserted = 1; } curLine += text; if (i) { var firstBreak = curLine.length > column && findBreakPoint(curLine, column, wrapOn, killTrailing); // If this isn't broken, or is broken at a different point, remove old break if (!firstBreak || firstBreak.from != oldLen || firstBreak.to != oldLen + spaceInserted) { changes.push({text: spaceInserted ? " " : "", from: Pos(curNo, oldLen), to: Pos(curNo + 1, 0)}); } else { curLine = text; ++curNo; } } while (curLine.length > column) { var bp = findBreakPoint(curLine, column, wrapOn, killTrailing); changes.push({text: "\n", from: Pos(curNo, bp.from), to: Pos(curNo, bp.to)}); curLine = curLine.slice(bp.to); ++curNo; } } if (changes.length) cm.operation(function() { for (var i = 0; i < changes.length; ++i) { var change = changes[i]; cm.replaceRange(change.text, change.from, change.to); } }); } CodeMirror.defineExtension("wrapParagraph", function(pos, options) { options = options || {}; if (!pos) pos = this.getCursor(); var para = findParagraph(this, pos, options); wrapRange(this, Pos(para.from, 0), Pos(para.to - 1), options); }); CodeMirror.defineExtension("wrapRange", function(from, to, options) { wrapRange(this, from, to, options || {}); }); CodeMirror.defineExtension("wrapParagraphsInRange", function(from, to, options) { options = options || {}; var cm = this, paras = []; for (var line = from.line; line <= to.line;) { var para = findParagraph(cm, Pos(line, 0), options); paras.push(para); line = para.to; } if (paras.length) cm.operation(function() { for (var i = paras.length - 1; i >= 0; --i) wrapRange(cm, Pos(paras[i].from, 0), Pos(paras[i].to - 1), options); }); }); })(); ================================================ FILE: public/packages/codemirror-3.19/bin/authors.sh ================================================ # Combine existing list of authors with everyone known in git, sort, add header. tail --lines=+3 AUTHORS > AUTHORS.tmp git log --format='%aN' >> AUTHORS.tmp echo -e "List of CodeMirror contributors. Updated before every release.\n" > AUTHORS sort -u AUTHORS.tmp >> AUTHORS rm -f AUTHORS.tmp ================================================ FILE: public/packages/codemirror-3.19/bin/compress ================================================ #!/usr/bin/env node // Compression helper for CodeMirror // // Example: // // bin/compress codemirror runmode javascript xml // // Will take lib/codemirror.js, addon/runmode/runmode.js, // mode/javascript/javascript.js, and mode/xml/xml.js, run them though // the online minifier at http://marijnhaverbeke.nl/uglifyjs, and spit // out the result. // // bin/compress codemirror --local /path/to/bin/UglifyJS // // Will use a local minifier instead of the online default one. // // Script files are specified without .js ending. Prefixing them with // their full (local) path is optional. So you may say lib/codemirror // or mode/xml/xml to be more precise. In fact, even the .js suffix // may be speficied, if wanted. "use strict"; var fs = require("fs"); function help(ok) { console.log("usage: " + process.argv[1] + " [--local /path/to/uglifyjs] files..."); process.exit(ok ? 0 : 1); } var local = null, args = [], extraArgs = null, files = [], blob = ""; for (var i = 2; i < process.argv.length; ++i) { var arg = process.argv[i]; if (arg == "--local" && i + 1 < process.argv.length) { var parts = process.argv[++i].split(/\s+/); local = parts[0]; extraArgs = parts.slice(1); if (!extraArgs.length) extraArgs = ["-c", "-m"]; } else if (arg == "--help") { help(true); } else if (arg[0] != "-") { files.push({name: arg, re: new RegExp("(?:\\/|^)" + arg + (/\.js$/.test(arg) ? "$" : "\\.js$"))}); } else help(false); } function walk(dir) { fs.readdirSync(dir).forEach(function(fname) { if (/^[_\.]/.test(fname)) return; var file = dir + fname; if (fs.statSync(file).isDirectory()) return walk(file + "/"); if (files.some(function(spec, i) { var match = spec.re.test(file); if (match) files.splice(i, 1); return match; })) { if (local) args.push(file); else blob += fs.readFileSync(file, "utf8"); } }); } walk("lib/"); walk("addon/"); walk("mode/"); if (!local && !blob) help(false); if (files.length) { console.log("Some speficied files were not found: " + files.map(function(a){return a.name;}).join(", ")); process.exit(1); } if (local) { require("child_process").spawn(local, args.concat(extraArgs), {stdio: ["ignore", process.stdout, process.stderr]}); } else { var data = new Buffer("js_code=" + require("querystring").escape(blob), "utf8"); var req = require("http").request({ host: "marijnhaverbeke.nl", port: 80, method: "POST", path: "/uglifyjs", headers: {"content-type": "application/x-www-form-urlencoded", "content-length": data.length} }); req.on("response", function(resp) { resp.on("data", function (chunk) { process.stdout.write(chunk); }); }); req.end(data); } ================================================ FILE: public/packages/codemirror-3.19/bin/lint ================================================ #!/usr/bin/env node var lint = require("../test/lint/lint"), path = require("path"); if (process.argv.length > 2) { lint.checkDir(process.argv[2]); } else { process.chdir(path.resolve(__dirname, "..")); lint.checkDir("lib"); lint.checkDir("mode"); lint.checkDir("addon"); lint.checkDir("keymap"); } process.exit(lint.success() ? 0 : 1); ================================================ FILE: public/packages/codemirror-3.19/bin/source-highlight ================================================ #!/usr/bin/env node // Simple command-line code highlighting tool. Reads code from stdin, // spits html to stdout. For example: // // echo 'function foo(a) { return a; }' | bin/source-highlight -s javascript // bin/source-highlight -s var fs = require("fs"); CodeMirror = require("../addon/runmode/runmode.node.js"); require("../mode/meta.js"); var sPos = process.argv.indexOf("-s"); if (sPos == -1 || sPos == process.argv.length - 1) { console.error("Usage: source-highlight -s language"); process.exit(1); } var lang = process.argv[sPos + 1].toLowerCase(), modeName = lang; CodeMirror.modeInfo.forEach(function(info) { if (info.mime == lang) { modeName = info.mode; } else if (info.name.toLowerCase() == lang) { modeName = info.mode; lang = info.mime; } }); function ensureMode(name) { if (CodeMirror.modes[name] || name == "null") return; try { require("../mode/" + name + "/" + name + ".js"); } catch(e) { console.error("Could not load mode " + name + "."); process.exit(1); } var obj = CodeMirror.modes[name]; if (obj.dependencies) obj.dependencies.forEach(ensureMode); } ensureMode(modeName); function esc(str) { return str.replace(/[<&]/, function(ch) { return ch == "&" ? "&" : "<"; }); } var code = fs.readFileSync("/dev/stdin", "utf8"); var curStyle = null, accum = ""; function flush() { if (curStyle) process.stdout.write("" + esc(accum) + ""); else process.stdout.write(esc(accum)); } CodeMirror.runMode(code, lang, function(text, style) { if (style != curStyle) { flush(); curStyle = style; accum = text; } else { accum += text; } }); flush(); ================================================ FILE: public/packages/codemirror-3.19/bower.json ================================================ { "name": "CodeMirror", "main": ["lib/codemirror.js", "lib/codemirror.css"], "ignore": [ "**/.*", "node_modules", "components", "bin", "demo", "doc", "test", "index.html", "package.json" ] } ================================================ FILE: public/packages/codemirror-3.19/demo/activeline.html ================================================ CodeMirror: Active Line Demo

            Active Line Demo

            Styling the current cursor line.

            ================================================ FILE: public/packages/codemirror-3.19/demo/anywordhint.html ================================================ CodeMirror: Any Word Completion Demo

            Any Word Completion Demo

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/bidi.html ================================================ CodeMirror: Bi-directional Text Demo

            Bi-directional Text Demo

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

            Note: There is a known bug with cursor motion and mouse clicks in bi-directional lines that are line wrapped.

            ================================================ FILE: public/packages/codemirror-3.19/demo/btree.html ================================================ CodeMirror: B-Tree visualization

            B-Tree visualization

            ================================================ FILE: public/packages/codemirror-3.19/demo/buffers.html ================================================ CodeMirror: Multiple Buffer & Split View Demo

            Multiple Buffer & Split View Demo

            Select buffer:    
            Select buffer:    

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/changemode.html ================================================ CodeMirror: Mode-Changing Demo

            Mode-Changing Demo

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/closebrackets.html ================================================ CodeMirror: Closebrackets Demo

            Closebrackets Demo

            ================================================ FILE: public/packages/codemirror-3.19/demo/closetag.html ================================================ CodeMirror: Close-Tag Demo

            Close-Tag Demo

            ================================================ FILE: public/packages/codemirror-3.19/demo/complete.html ================================================ CodeMirror: Autocomplete Demo

            Autocomplete Demo

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/emacs.html ================================================ CodeMirror: Emacs bindings demo

            Emacs bindings demo

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

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/folding.html ================================================ CodeMirror: Code Folding Demo

            Code Folding Demo

            JavaScript:
            HTML:
            ================================================ FILE: public/packages/codemirror-3.19/demo/fullscreen.html ================================================ CodeMirror: Full Screen Editing

            Full Screen Editing

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/hardwrap.html ================================================ CodeMirror: Hard-wrapping Demo

            Hard-wrapping Demo

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/html5complete.html ================================================ CodeMirror: HTML completion demo

            HTML completion demo

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/indentwrap.html ================================================ CodeMirror: Indented wrapped line demo

            Indented wrapped line demo

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/lint.html ================================================ CodeMirror: Linter Demo

            Linter Demo

            ================================================ FILE: public/packages/codemirror-3.19/demo/loadmode.html ================================================ CodeMirror: Lazy Mode Loading Demo

            Lazy Mode Loading Demo

            ================================================ FILE: public/packages/codemirror-3.19/demo/marker.html ================================================ CodeMirror: Breakpoint Demo

            Breakpoint Demo

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/markselection.html ================================================ CodeMirror: Match Selection Demo

            Match Selection Demo

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/matchhighlighter.html ================================================ CodeMirror: Match Highlighter Demo

            Match Highlighter Demo

            Search and highlight occurences of the selected text.

            ================================================ FILE: public/packages/codemirror-3.19/demo/matchtags.html ================================================ CodeMirror: Tag Matcher Demo

            Tag Matcher Demo

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/merge.html ================================================ CodeMirror: merge view demo

            merge view demo

            The merge addon provides an interface for displaying and merging diffs, either two-way or three-way. The left (or center) pane is editable, and the differences with the other pane(s) are optionally shown live as you edit it.

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/multiplex.html ================================================ CodeMirror: Multiplexing Parser Demo

            Multiplexing Parser Demo

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

            Parsing/Highlighting Tests: normal, verbose.

            ================================================ FILE: public/packages/codemirror-3.19/demo/mustache.html ================================================ CodeMirror: Overlay Parser Demo

            Overlay Parser Demo

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/placeholder.html ================================================ CodeMirror: Placeholder demo

            Placeholder demo

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/preview.html ================================================ CodeMirror: HTML5 preview

            HTML5 preview

            ================================================ FILE: public/packages/codemirror-3.19/demo/resize.html ================================================ CodeMirror: Autoresize Demo

            Autoresize Demo

            By setting a few CSS properties, and giving the viewportMargin a value of Infinity, CodeMirror can be made to automatically resize to fit its content.

            ================================================ FILE: public/packages/codemirror-3.19/demo/runmode.html ================================================ CodeMirror: Mode Runner Demo

            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).
            ================================================ FILE: public/packages/codemirror-3.19/demo/search.html ================================================ CodeMirror: Search/Replace Demo

            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.

            ================================================ FILE: public/packages/codemirror-3.19/demo/spanaffectswrapping_shim.html ================================================ CodeMirror: Automatically derive odd wrapping behavior for your browser

            Automatically derive odd wrapping behavior for your browser

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

            
            
                
              
            ================================================ FILE: public/packages/codemirror-3.19/demo/tern.html ================================================ CodeMirror: Tern Demo

            Tern Demo

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

            Ctrl-Space
            Autocomplete
            Ctrl-I
            Find type at cursor
            Alt-.
            Jump to definition (Alt-, to jump back)
            Ctrl-Q
            Rename variable

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/theme.html ================================================ CodeMirror: Theme Demo

            Theme Demo

            Select a theme:

            ================================================ FILE: public/packages/codemirror-3.19/demo/trailingspace.html ================================================ CodeMirror: Trailing Whitespace Demo

            Trailing Whitespace Demo

            Uses the trailingspace addon to highlight trailing whitespace.

            ================================================ FILE: public/packages/codemirror-3.19/demo/variableheight.html ================================================ CodeMirror: Variable Height Demo

            Variable Height Demo

            ================================================ FILE: public/packages/codemirror-3.19/demo/vim.html ================================================ CodeMirror: Vim bindings demo

            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.

            ================================================ FILE: public/packages/codemirror-3.19/demo/visibletabs.html ================================================ CodeMirror: Visible tabs demo

            Visible tabs demo

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/widget.html ================================================ CodeMirror: Inline Widget Demo

            Inline Widget Demo

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

            ================================================ FILE: public/packages/codemirror-3.19/demo/xmlcomplete.html ================================================ CodeMirror: XML Autocomplete Demo

            XML Autocomplete Demo

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

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

            ================================================ FILE: public/packages/codemirror-3.19/doc/activebookmark.js ================================================ (function() { var pending = false, prevVal = null; function updateSoon() { if (!pending) { pending = true; setTimeout(update, 250); } } function update() { pending = false; var marks = document.getElementById("nav").getElementsByTagName("a"), found; for (var i = 0; i < marks.length; ++i) { var mark = marks[i], m; if (mark.getAttribute("data-default")) { if (found == null) found = i; } else if (m = mark.href.match(/#(.*)/)) { var ref = document.getElementById(m[1]); if (ref && ref.getBoundingClientRect().top < 50) found = i; } } if (found != null && found != prevVal) { prevVal = found; var lis = document.getElementById("nav").getElementsByTagName("li"); for (var i = 0; i < lis.length; ++i) lis[i].className = ""; for (var i = 0; i < marks.length; ++i) { if (found == i) { marks[i].className = "active"; for (var n = marks[i]; n; n = n.parentNode) if (n.nodeName == "LI") n.className = "active"; } else { marks[i].className = ""; } } } } window.addEventListener("scroll", updateSoon); window.addEventListener("load", updateSoon); })(); ================================================ FILE: public/packages/codemirror-3.19/doc/compress.html ================================================ CodeMirror: Compression Helper

            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:

            ================================================ FILE: public/packages/codemirror-3.19/doc/docs.css ================================================ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; src: local('Source Sans Pro'), local('SourceSansPro-Regular'), url(http://themes.googleusercontent.com/static/fonts/sourcesanspro/v5/ODelI1aHBYDBqgeIAH2zlBM0YzuT7MdOe03otPbuUS0.woff) format('woff'); } body, html { margin: 0; padding: 0; height: 100%; } section, article { display: block; padding: 0; } body { background: #f8f8f8; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; line-height: 1.5; } p { margin-top: 0; } h2, h3 { font-weight: normal; text-decoration: underline; margin-bottom: .7em; } h2 { font-size: 120%; } h3 { font-size: 110%; } article > h2:first-child, section:first-child > h2 { margin-top: 0; } a, a:visited, a:link, .quasilink { color: #A21313; text-decoration: none; } em { padding-right: 2px; } .quasilink { cursor: pointer; } article { max-width: 700px; margin: 0 auto; border-left: 2px solid #E30808; border-right: 1px solid #ddd; padding: 30px 50px 100px 50px; background: white; z-index: 2; position: relative; min-height: 100%; box-sizing: border-box; -moz-box-sizing: border-box; } #nav { position: fixed; top: 30px; right: 50%; padding-right: 350px; text-align: right; z-index: 1; } @media screen and (max-width: 1000px) { article { margin: 0 0 0 160px; } #nav { left: 0; right: none; width: 160px; } } #nav ul { display: block; margin: 0; padding: 0; margin-bottom: 32px; } #nav li { display: block; margin-bottom: 4px; } #nav li ul { font-size: 80%; margin-bottom: 0; display: none; } #nav li.active ul { display: block; } #nav li li a { padding-right: 20px; } #nav ul a { color: black; padding: 0 7px 1px 11px; } #nav ul a.active, #nav ul a:hover { border-bottom: 1px solid #E30808; color: #E30808; } #logo { border: 0; margin-right: 7px; margin-bottom: 25px; } section { border-top: 1px solid #E30808; margin: 1.5em 0; } section.first { border: none; margin-top: 0; } #demo { position: relative; } #demolist { position: absolute; right: 5px; top: 5px; z-index: 25; } #bankinfo { text-align: left; display: none; padding: 0 .5em; position: absolute; border: 2px solid #aaa; border-radius: 5px; background: #eee; top: 10px; left: 30px; } #bankinfo_close { position: absolute; top: 0; right: 6px; font-weight: bold; cursor: pointer; } .bigbutton { cursor: pointer; text-align: center; padding: 0 1em; display: inline-block; color: white; position: relative; line-height: 1.9; color: white !important; background: #A21313; } .bigbutton.right { border-bottom-left-radius: 100px; border-top-left-radius: 100px; } .bigbutton.left { border-bottom-right-radius: 100px; border-top-right-radius: 100px; } .bigbutton:hover { background: #E30808; } th { text-decoration: underline; font-weight: normal; text-align: left; } #features ul { list-style: none; margin: 0 0 1em; padding: 0 0 0 1.2em; } #features li:before { content: "-"; width: 1em; display: inline-block; padding: 0; margin: 0; margin-left: -1em; } .rel { margin-bottom: 0; } .rel-note { margin-top: 0; color: #555; } pre { padding-left: 15px; border-left: 2px solid #ddd; } code { padding: 0 2px; } strong { text-decoration: underline; font-weight: normal; } .field { border: 1px solid #A21313; } ================================================ FILE: public/packages/codemirror-3.19/doc/internals.html ================================================ CodeMirror: Internals

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

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

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

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

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

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

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

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

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

            General Approach

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

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

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

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

            Input

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

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

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

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

            Selection

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

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

            But not something that the browser selection APIs expose.

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

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

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

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

            Intelligent Updating

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

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

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

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

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

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

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

            Parsers can be Simple

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

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

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

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

            What Gives?

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

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

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

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

            Content Representation

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

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

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

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

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

            Keymaps

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

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

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

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

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

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

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

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

            ================================================ FILE: public/packages/codemirror-3.19/doc/manual.html ================================================ CodeMirror: User Manual

            User manual and reference guide

            CodeMirror is a code-editor component that can be embedded in Web pages. The core library provides only the editor component, no accompanying buttons, auto-completion, or other IDE functionality. It does provide a rich API on top of which such functionality can be straightforwardly implemented. See the addons included in the distribution, and the list of externally hosted addons, for reusable implementations of extra features.

            CodeMirror works with language-specific modes. Modes are JavaScript programs that help color (and optionally indent) text written in a given language. The distribution comes with a number of modes (see the mode/ directory), and it isn't hard to write new ones for other languages.

            Basic Usage

            The easiest way to use CodeMirror is to simply load the script and style sheet found under lib/ in the distribution, plus a mode script from one of the mode/ directories. (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|CodeMirror.Doc
            The starting value of the editor. Can be a string, or a document object.
            mode: string|object
            The mode to use. When not given, this will default to the first mode that was loaded. It may be a string, which either simply names the mode or is a MIME type associated with the mode. Alternatively, it may be an object containing configuration options for the mode, with a name property that names the mode (for example {name: "javascript", json: true}). The demo pages for each mode contain information about what configuration parameters the mode supports. You can ask CodeMirror which modes and MIME types have been defined by inspecting the CodeMirror.modes and CodeMirror.mimeModes objects. The first maps mode names to their constructors, and the second maps MIME types to mode specs.
            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(line: integer) → string
            A function used to format line numbers. The function is passed the line number, and should return a string that will be shown in the gutter.
            gutters: array<string>
            Can be used to add extra gutters (beyond or instead of the line number gutter). Should be an array of CSS class names, each of which defines a width (and optionally a background), and which will be used to draw the background of the gutters. May include the CodeMirror-linenumbers class, in order to explicitly set the position of the line number gutter (it will default to be to the right of all other gutters). These class names are the keys passed to setGutterMarker.
            fixedGutter: boolean
            Determines whether the gutter scrolls along with the content horizontally (false) or whether it stays fixed during horizontal scrolling (true, the default).
            coverGutterNextToScrollbar: boolean
            When fixedGutter is on, and there is a horizontal scrollbar, by default the gutter will be visible to the left of this scrollbar. If this option is set to true, it will be covered by an element with class CodeMirror-gutter-filler.
            readOnly: boolean|string
            This disables editing of the editor content by the user. If the special value "nocursor" is given (instead of simply true), focusing of the editor is also disallowed.
            showCursorWhenSelecting: boolean
            Whether the cursor should be drawn when a selection is active. Defaults to false.
            undoDepth: integer
            The maximum number of undo levels that the editor stores. Defaults to 40.
            historyEventDelay: integer
            The period of inactivity (in milliseconds) that will cause a new history event to be started when typing or deleting. Defaults to 500.
            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(instance: CodeMirror, event: Event) → boolean
            Deprecated! See these event handlers for the current recommended approach.
            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(instance: CodeMirror, event: Event) → boolean
            Deprecated! See these event handlers for the current recommended approach.
            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. By setting this to zero, blinking can be disabled.
            cursorScrollMargin: number
            How much extra space to always keep above and below the cursor when approaching the top or bottom of the visible view in a scrollable document. Default is 0.
            cursorHeight: number
            Determines the height of the cursor. Default is 1, meaning it spans the whole height of the line. For some fonts (and by some tastes) a smaller height (for example 0.85), which causes the cursor to not reach all the way to the bottom of the line, looks better
            resetSelectionOnContextMenu: boolean
            Controls whether, when the context menu is opened with a click outside of the current selection, the cursor is moved to the point of the click. Defaults to true.
            workTime, workDelay: number
            Highlighting is done by a pseudo background-thread that will work for workTime milliseconds, and then use timeout to sleep for workDelay milliseconds. The defaults are 200 and 300, you can change these options to make the highlighting more or less aggressive.
            workDelay: number
            See workTime.
            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.
            maxHighlightLength: number
            When highlighting long lines, in order to stay responsive, the editor will give up and simply style the rest of the line as plain text when it reaches a certain position. The default is 10 000. You can set this to Infinity to turn off this behavior.
            crudeMeasuringFrom: number
            When measuring the character positions in long lines, any line longer than this number (default is 10 000), when line wrapping is off, will simply be assumed to consist of same-sized characters. This means that, on the one hand, measuring will be inaccurate when characters of varying size, right-to-left text, markers, or other irregular elements are present. On the other hand, it means that having such a line won't freeze the user interface because of the expensiveness of the measurements.
            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

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

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

            "change" (instance: CodeMirror, changeObj: object)
            Fires every time the content of the editor is changed. The changeObj is a {from, to, text, removed, 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). removed is the text that used to be between from and to, which is overwritten by this change. 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: CodeMirror, changeObj: object)
            This event is fired before a change is applied, and its handler may choose to modify or cancel the change. The changeObj object has from, to, and text properties, as with the "change" event, but never a next property, since this is fired for each individual change, and not batched per operation. It also has a cancel() method, which can be called to cancel the change, and, if the change isn't coming from an undo or redo event, an update(from, to, text) method, which may be used to modify the change. Undo or redo changes can't be modified, because they hold some metainformation for restoring old marked ranges that is only valid for that specific change. All three arguments to update are optional, and can be left off to leave the existing value for that field intact. Note: you may not do anything from a "beforeChange" handler that would cause changes to the document or its visualization. Doing so will, since this handler is called directly from the bowels of the CodeMirror implementation, probably cause the editor to become corrupted.
            "cursorActivity" (instance: CodeMirror)
            Will be fired when the cursor or selection moves, or any change is made to the editor content.
            "keyHandled" (instance: CodeMirror, name: string, event: Event)
            Fired after a key is handled through a keymap. name is the name of the handled key (for example "Ctrl-X" or "'q'"), and event is the DOM keydown or keypress event.
            "inputRead" (instance: CodeMirror, changeObj: object)
            Fired whenever new input is read from the hidden textarea (typed or pasted by the user).
            "beforeSelectionChange" (instance: CodeMirror, selection: {head, anchor})
            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: CodeMirror, from: number, to: number)
            Fires whenever the view port of the editor changes (due to scrolling, editing, or any other factor). The from and to arguments give the new start and end of the viewport.
            "swapDoc" (instance: CodeMirror, oldDoc: Doc)
            This is signalled when the editor's document is replaced using the swapDoc method.
            "gutterClick" (instance: CodeMirror, line: integer, gutter: string, clickEvent: Event)
            Fires when the editor gutter (the line-number area) is clicked. Will pass the editor instance as first argument, the (zero-based) number of the line that was clicked as second argument, the CSS class of the gutter that was clicked as third argument, and the raw mousedown event object as fourth argument.
            "gutterContextMenu" (instance: CodeMirror, line: integer, gutter: string, contextMenu: Event: Event)
            Fires when the editor gutter (the line-number area) receives a contextmenu event. Will pass the editor instance as first argument, the (zero-based) number of the line that was clicked as second argument, the CSS class of the gutter that was clicked as third argument, and the raw contextmenu mouse event object as fourth argument. You can preventDefault the event, to signal that CodeMirror should do no further handling.
            "focus" (instance: CodeMirror)
            Fires whenever the editor is focused.
            "blur" (instance: CodeMirror)
            Fires whenever the editor is unfocused.
            "scroll" (instance: CodeMirror)
            Fires when the editor is scrolled.
            "update" (instance: CodeMirror)
            Will be fired whenever CodeMirror updates its DOM display.
            "renderLine" (instance: CodeMirror, line: LineHandle, element: Element)
            Fired whenever a line is (re-)rendered to the DOM. Fired right after the DOM element is built, before it is added to the document. The handler may mess with the style of the resulting element, or add event handlers, but should not try to change the state of the editor.
            "mousedown", "dblclick", "contextmenu", "keydown", "keypress", "keyup", "dragstart", "dragenter", "dragover", "drop" (instance: CodeMirror, event: Event)
            Fired when CodeMirror is handling a DOM event of this type. You can preventDefault the event, or give it a truthy codemirrorIgnore property, to signal that CodeMirror should do no further handling.

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

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

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

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

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

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

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

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

            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.

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

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

            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). When the disableInput property is set to true, the default effect of inserting a character will be suppressed when the keymap is active as the top-level map.

            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 addons) if you want to expose them to your users.

            Whenever points in the document are represented, the API uses objects with line and ch properties. Both are zero-based. CodeMirror makes sure to 'clip' any positions passed by client code so that they fit inside the document, so you shouldn't worry too much about sanitizing your coordinates. If you give ch a value of null, or don't specify it, it will be replaced with the length of the specified line.

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

            Constructor

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

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

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

            Content manipulation methods

            doc.getValue(?separator: string) → string
            Get the current editor content. You can pass it an optional argument to specify the string to be used to separate lines (defaults to "\n").
            doc.setValue(content: string)
            Set the editor content.
            doc.getRange(from: {line, ch}, to: {line, ch}, ?separator: string) → string
            Get the text between the given points in the editor, which should be {line, ch} objects. An optional third argument can be given to indicate the line separator string to use (defaults to "\n").
            doc.replaceRange(replacement: string, from: {line, ch}, to: {line, ch})
            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: integer) → string
            Get the content of line n.
            doc.setLine(n: integer, text: string)
            Set the content of line n.
            doc.removeLine(n: integer)
            Remove the given line from the document.
            doc.lineCount() → integer
            Get the number of lines in the editor.
            doc.firstLine() → integer
            Get the first line of the editor. This will usually be zero but for linked sub-views, or documents instantiated with a non-zero first line, it might return other values.
            doc.lastLine() → integer
            Get the last line of the editor. This will usually be doc.lineCount() - 1, but for linked sub-views, it might return other values.
            doc.getLineHandle(num: integer) → LineHandle
            Fetches the line handle for the given line number.
            doc.getLineNumber(handle: LineHandle) → integer
            Given a line handle, returns the current position of that line (or null when it is no longer in the document).
            doc.eachLine(f: (line: LineHandle))
            doc.eachLine(start: integer, end: integer, f: (line: LineHandle))
            Iterate over the whole document, or if start and end line numbers are given, the range from start up to (not including) end, and call f for each line, passing the line handle. This is a faster way to visit a range of line handlers than calling getLineHandle for each of them. Note that line handles have a text property containing the line's content (as a string).
            doc.markClean()
            Set the editor content as 'clean', a flag that it will retain until it is edited, and which will be set again when such an edit is undone again. Useful to track whether the content needs to be saved. This function is deprecated in favor of changeGeneration, which allows multiple subsystems to track different notions of cleanness without interfering.
            doc.changeGeneration() → integer
            Returns a number that can later be passed to isClean to test whether any edits were made (and not undone) in the meantime.
            doc.isClean(?generation: integer) → boolean
            Returns whether the document is currently clean — not modified since initialization or the last call to markClean if no argument is passed, or since the matching call to changeGeneration if a generation value is given.

            Cursor and selection methods

            doc.getSelection() → string
            Get the currently selected code.
            doc.replaceSelection(replacement: string, ?collapse: string)
            Replace the selection with the given string. By default, the new selection will span the inserted text. The optional collapse argument can be used to change this—passing "start" or "end" will collapse the selection to the start or end of the inserted text.
            doc.getCursor(?start: string) → {line, ch}
            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: {line, ch})
            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: {line, ch}, ?head: {line, ch})
            Set the selection range. anchor and head should be {line, ch} objects. head defaults to anchor when not given.
            doc.extendSelection(from: {line, ch}, ?to: {line, ch})
            Similar to setSelection, but will, if shift is held or the extending flag is set, move the head of the selection while leaving the anchor at its current place. to is optional, and can be passed to ensure a region (for example a word or paragraph) will end up selected (in addition to whatever lies between that region and the current anchor).
            doc.setExtending(value: boolean)
            Sets or clears the 'extending' flag, which acts similar to the shift key, in that it will cause cursor movement and calls to extendSelection to leave the selection anchor in place.
            cm.hasFocus() → boolean
            Tells you whether the editor currently has focus.
            cm.findPosH(start: {line, ch}, amount: integer, unit: string, visually: boolean) → {line, ch, ?hitSide: boolean}
            Used to find the target position for horizontal cursor motion. start is a {line, ch} object, amount an integer (may be negative), and unit one of the string "char", "column", or "word". Will return a position that is produced by moving amount times the distance specified by unit. When visually is true, motion in right-to-left text will be visual rather than logical. When the motion was clipped by hitting the end or start of the document, the returned value will have a hitSide property set to true.
            cm.findPosV(start: {line, ch}, amount: integer, unit: string) → {line, ch, ?hitSide: boolean}
            Similar to findPosH, but used for vertical motion. unit may be "line" or "page". The other arguments and the returned value have the same interpretation as they have in findPosH.

            Configuration methods

            cm.setOption(option: string, value: any)
            Change the configuration of the editor. option should the name of an option, and value should be a valid value for that option.
            cm.getOption(option: string) → any
            Retrieves the current value of the given option for this editor instance.
            cm.addKeyMap(map: object, bottom: boolean)
            Attach an additional keymap to the editor. This is mostly useful for addons that need to register some key handlers without trampling on the extraKeys option. Maps added in this way have a higher precedence than the extraKeys and keyMap options, and between them, the maps added earlier have a lower precedence than those added later, unless the bottom argument was passed, in which case they end up below other keymaps added with this method.
            cm.removeKeyMap(map: object)
            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: string|object, ?options: object)
            Enable a highlighting overlay. This is a stateless mini-mode that can be used to add extra highlighting. For example, the search addon uses it to highlight the term that's currently being searched. mode can be a mode spec or a mode object (an object with a token method). The options parameter is optional. If given, it should be an object. 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: string|object)
            Pass this the exact value passed for the mode parameter to addOverlay, or a string that corresponds to the name propery of that value, to remove an overlay again.
            cm.on(type: string, func: (...args))
            Register an event handler for the given event type (a string) on the editor instance. There is also a CodeMirror.on(object, type, func) version that allows registering of events on any object.
            cm.off(type: string, func: (...args))
            Remove an event handler on the editor instance. An equivalent CodeMirror.off(object, type, func) also exists.

            Document management methods

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

            History-related methods

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

            Text-marking methods

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

            Widget, gutter, and decoration methods

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

            Sizing, scrolling and positioning methods

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

            Mode, state, and token-related methods

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

            doc.getMode() → object
            Gets the (outer) mode object for the editor. Note that this is distinct from getOption("mode"), which gives you the mode specification, rather than the resolved, instantiated mode object.
            doc.getModeAt(pos: {line, ch}) → object
            Gets the inner mode at a given position. This will return the same as getMode for simple modes, but will return an inner mode for nesting modes (such as htmlmixed).
            cm.getTokenAt(pos: {line, ch}, ?precise: boolean) → object
            Retrieves information about the token the current mode found before the given position (a {line, ch} object). The returned object has the following properties:
            start
            The character (on the given line) at which the token starts.
            end
            The character at which the token ends.
            string
            The token's string.
            type
            The token type the mode assigned to the token, such as "keyword" or "comment" (may also be null).
            state
            The mode's state at the end of this token.
            If precise is true, the token will be guaranteed to be accurate based on recent edits. If false or not specified, the token will use cached state information, which will be faster but might not be accurate if edits were recently made and highlighting has not yet completed.
            cm.getTokenTypeAt(pos: {line, ch}) → string
            This is a (much) cheaper version of getTokenAt useful for when you just need the type of the token at a given position, and no other information. Will return null for unstyled tokens, and a string, potentially containing multiple space-separated style names, otherwise.
            cm.getHelper(pos: {line, ch}, type: string) → helper
            Fetch appropriate helper for the given position. Helpers provide a way to look up functionality appropriate for a mode. The type argument provides the helper namespace (see also registerHelper), in which the value will be looked up. The key that is used depends on the mode active at the given position. If the mode object contains a property with the same name as the type argument, that is tried first. Next, the mode's helperType, if any, is tried. And finally, the mode's name.
            cm.getStateAfter(?line: integer, ?precise: boolean) → object
            Returns the mode's parser state, if any, at the end of the given line number. If no line number is given, the state at the end of the document is returned. This can be useful for storing parsing errors in the state, or getting other kinds of contextual information for a line. precise is defined as in getTokenAt().

            Miscellaneous methods

            cm.operation(func: () → any) → any
            CodeMirror internally buffers changes and only updates its DOM structure after it has finished performing some operation. If you need to perform a lot of operations on a CodeMirror instance, you can call this method with a function argument. It will call the function, buffering up all changes, and only doing the expensive update after the function returns. This can be a lot faster. The return value from this method will be the return value of your function.
            cm.indentLine(line: integer, ?dir: string|integer)
            Adjust the indentation of the given line. The second argument (which defaults to "smart") may be one of:
            "prev"
            Base indentation on the indentation of the previous line.
            "smart"
            Use the mode's smart indentation if available, behave like "prev" otherwise.
            "add"
            Increase the indentation of the line by one indent unit.
            "subtract"
            Reduce the indentation of the line.
            <integer>
            Add (positive number) or reduce (negative number) the indentation by the given amount of spaces.
            cm.toggleOverwrite(?value: bool)
            Switches between overwrite and normal insert mode (when not given an argument), or sets the overwrite mode to a specific state (when given an argument).
            doc.posFromIndex(index: integer) → {line, ch}
            Calculates and returns a {line, ch} object for a zero-based index who's value is relative to the start of the editor's text. If the index is out of range of the text then the returned object is clipped to start or end of the text respectively.
            doc.indexFromPos(object: {line, ch}) → integer
            The reverse of posFromIndex.
            cm.focus()
            Give the editor focus.
            cm.getInputField() → TextAreaElement
            Returns the hidden textarea used to read input.
            cm.getWrapperElement() → Element
            Returns the DOM node that represents the editor, and controls its size. Remove this from your tree to delete an editor instance.
            cm.getScrollerElement() → Element
            Returns the DOM node that is responsible for the scrolling of the editor.
            cm.getGutterElement() → Element
            Fetches the DOM node that contains the editor gutters.

            Static properties

            The CodeMirror object itself provides several useful properties.

            CodeMirror.version: string
            It contains a string that indicates the version of the library. This is a triple of integers "major.minor.patch", where patch is zero for releases, and something else (usually one) for dev snapshots.
            CodeMirror.fromTextArea(textArea: TextAreaElement, ?config: object)
            The 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() → TextAreaElement
            Returns the textarea that the instance was based on.
            CodeMirror.defaults: object
            An object containing default values for all options. You can assign to its properties to modify defaults (though this won't affect editors that have already been created).
            CodeMirror.defineExtension(name: string, value: any)
            If you want to define extra methods in terms of the CodeMirror API, it is possible to use defineExtension. This will cause the given value (usually a method) to be added to all CodeMirror instances created from then on.
            CodeMirror.defineDocExtension(name: string, value: any)
            Like defineExtension, but the method will be added to the interface for Doc objects instead.
            CodeMirror.defineOption(name: string, default: any, updateFunc: function)
            Similarly, defineOption can be used to define new options for CodeMirror. The updateFunc will be called with the editor instance and the new value when an editor is initialized, and whenever the option is modified through setOption.
            CodeMirror.defineInitHook(func: function)
            If your 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.
            CodeMirror.registerHelper(type: string, name: string, value: helper)
            Registers a helper value with the given name in the given namespace (type). This is used to define functionality that may be looked up by mode. Will create (if it doesn't already exist) a property on the CodeMirror object for the given type, pointing to an object that maps names to values. I.e. after doing CodeMirror.registerHelper("hint", "foo", myFoo), the value CodeMirror.hint.foo will point to myFoo.
            CodeMirror.Pos(line: integer, ?ch: integer)
            A constructor for the {line, ch} objects that are used to represent positions in editor documents.
            CodeMirror.changeEnd(change: object) → {line, ch}
            Utility function that computes an end position from a change (an object with from, to, and text properties, as passed to various event handlers). The returned position will be the end of the changed range, after the change is applied.

            Addons

            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() → boolean
            findPrevious() → boolean
            Search forward or backward from the current position. The return value indicates whether a match was found. If matching a regular expression, the return value will be the array returned by the match method, in case you want to extract matched groups.
            from() → {line, ch}
            to() → {line, ch}
            These are only valid when the last call to findNext or findPrevious did not return false. They will return {line, ch} objects pointing at the start and end of the match.
            replace(text: string)
            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), or an object with pairs and optionally explode properties to customize it. explode should be a similar string that gives the pairs of characters that, when enter is pressed between them, should have the second character also moved to its own line. Demo here.
            edit/matchtags.js
            Defines an option matchTags that, when enabled, will cause the tags around the cursor to be highlighted (using the CodeMirror-matchingtag class). Also defines a command toMatchingTag, which you can bind a key to in order to jump to the tag mathing the one under the cursor. Depends on the addon/fold/xml-fold.js addon. Demo here.
            edit/trailingspace.js
            Adds an option showTrailingSpace which, when enabled, adds the CSS class cm-trailingspace to stretches of whitespace at the end of lines. The demo has a nice squiggly underline style for this class.
            edit/closetag.js
            Provides utility functions for adding automatic tag closing to XML modes. See the demo.
            edit/continuelist.js
            Markdown specific. Defines a "newlineAndIndentContinueMarkdownList" command command that can be bound to enter to automatically insert the leading characters for continuing a list. See the Markdown mode demo.
            comment/comment.js
            Addon for commenting and uncommenting code. Adds three methods to CodeMirror instances:
            lineComment(from: {line, ch}, to: {line, ch}, ?options: object)
            Set the lines in the given range to be line comments. Will fall back to blockComment when no line comment style is defined for the mode.
            blockComment(from: {line, ch}, to: {line, ch}, ?options: object)
            Wrap the code in the given range in a block comment. Will fall back to lineComment when no block comment style is defined for the mode.
            uncomment(from: {line, ch}, to: {line, ch}, ?options: object) → boolean
            Try to uncomment the given range. Returns true if a comment range was found and removed, false otherwise.
            The options object accepted by these methods may have the following properties:
            blockCommentStart, blockCommentEnd, blockCommentLead, lineComment: string
            Override the comment string properties of the mode with custom comment strings.
            padding: string
            A string that will be inserted after opening and before closing comment markers. Defaults to a single space.
            commentBlankLines: boolean
            Whether, when adding line comments, to also comment lines that contain only whitespace.
            indent: boolean
            When adding line comments and this is turned on, it will align the comment block to the current indentation of the first line of the block.
            fullLines: boolean
            When block commenting, this controls whether the whole lines are indented, or only the precise range that is given. Defaults to true.
            The addon also defines a toggleComment command, which will try to uncomment the current selection, and if that fails, line-comments it.
            fold/foldcode.js
            Helps with code folding. Adds a foldCode method to editor instances, which will try to do a code fold starting at the given line, or unfold the fold that is already present. The method takes as first argument the position that should be folded (may be a line number or a Pos), and as second optional argument either a range-finder function, or an options object, supporting the following properties:
            rangeFinder: fn(CodeMirror, Pos)
            The function that is used to find foldable ranges. If this is not directly passed, it will call getHelper with a "fold" type to find one that's appropriate for the mode. There are files in the addon/fold/ directory providing CodeMirror.fold.brace, which finds blocks in brace languages (JavaScript, C, Java, etc), CodeMirror.fold.indent, for languages where indentation determines block structure (Python, Haskell), and CodeMirror.fold.xml, for XML-style languages, and CodeMirror.fold.comment, for folding comment blocks.
            widget: string|Element
            The widget to show for folded ranges. Can be either a string, in which case it'll become a span with class CodeMirror-foldmarker, or a DOM node.
            scanUp: boolean
            When true (default is false), the addon will try to find foldable ranges on the lines above the current one if there isn't an eligible one on the given line.
            minFoldSize: integer
            The minimum amount of lines that a fold should span to be accepted. Defaults to 0, which also allows single-line folds.
            See the demo for an example.
            fold/foldgutter.js
            Provides an option foldGutter, which can be used to create a gutter with markers indicating the blocks that can be folded. Create a gutter using the gutters option, giving it the class CodeMirror-foldgutter or something else if you configure the addon to use a different class, and this addon will show markers next to folded and foldable blocks, and handle clicks in this gutter. Note that CSS styles should be applied to make the gutter, and the fold markers within it, visible. A default set of CSS styles are available in: addon/fold/foldgutter.css . The option can be either set to true, or an object containing the following optional option fields:
            gutter: string
            The CSS class of the gutter. Defaults to "CodeMirror-foldgutter". You will have to style this yourself to give it a width (and possibly a background). See the default gutter style rules above.
            indicatorOpen: string | Element
            A CSS class or DOM element to be used as the marker for open, foldable blocks. Defaults to "CodeMirror-foldgutter-open".
            indicatorFolded: string | Element
            A CSS class or DOM element to be used as the marker for folded blocks. Defaults to "CodeMirror-foldgutter-folded".
            rangeFinder: fn(CodeMirror, Pos)
            The range-finder function to use when determining whether something can be folded. When not given, getHelper will be used to determine a default.
            Demo here.
            runmode/runmode.js
            Can be used to run a CodeMirror mode over text without actually opening an editor instance. See the demo for an example. There are alternate versions of the file avaible for running stand-alone (without including all of CodeMirror) and for running under node.js.
            runmode/colorize.js
            Provides a convenient way to syntax-highlight code snippets in a webpage. Depends on the runmode addon (or its standalone variant). Provides a CodeMirror.colorize function that can be called with an array (or other array-ish collection) of DOM nodes that represent the code snippets. By default, it'll get all pre tags. Will read the data-lang attribute of these nodes to figure out their language, and syntax-color their content using the relevant CodeMirror mode (you'll have to load the scripts for the relevant modes yourself). A second argument may be provided to give a default mode, used when no language attribute is found for a node. Used in this manual to highlight example code.
            mode/overlay.js
            Mode combinator that can be used to extend a mode with an 'overlay' — a secondary mode is run over the stream, along with the base mode, and can color specific pieces of text without interfering with the base mode. Defines CodeMirror.overlayMode, which is used to create such a mode. See this demo for a detailed example.
            mode/multiplex.js
            Mode combinator that can be used to easily 'multiplex' between several modes. Defines CodeMirror.multiplexingMode which, when given as first argument a mode object, and as other arguments any number of {open, close, mode [, delimStyle, innerStyle]} 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.
            • When innerStyle is specified, it will be the token style added for each inner mode token.
            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, a hinting function, and optionally an options object, and pops up a widget that allows the user to select a completion. Hinting functions are function that take an editor instance and an optional options object, and return a {list, from, to} object, where list is an array of strings or objects (the completions), and from and to give the start and end of the token that is being completed as {line, ch} objects. If no hinting function is given, the addon will try to use getHelper with the "hint" type to find one. When completions aren't simple strings, they should be objects with the folowing properties:
            text: string
            The completion text. This is the only required property.
            displayText: string
            The text that should be displayed in the menu.
            className: string
            A CSS class name to apply to the completion's line in the menu.
            render: fn(Element, self, data)
            A method used to create the DOM structure for showing the completion by appending it to its first argument.
            hint: fn(CodeMirror, self, data)
            A method used to actually apply the completion, instead of the default behavior.
            The plugin understands the following options (the options object will also be passed along to the hinting function, which may understand additional options):
            async: boolean
            When set to true, the hinting function's signature should be (cm, callback, ?options), and the completion interface will only be popped up when the hinting function calls the callback, passing it the object holding the completions.
            completeSingle: boolean
            Determines whether, when only a single completion is available, it is completed without showing the dialog. Defaults to true.
            alignWithWord: boolean
            Whether the pop-up should be horizontally aligned with the start of the word (true, default), or with the cursor (false).
            closeOnUnfocus: boolean
            When enabled (which is the default), the pop-up will close when the editor is unfocused.
            customKeys: keymap
            Allows you to provide a custom keymap of keys to be active when the pop-up is active. The handlers will be called with an extra argument, a handle to the completion menu, which has moveFocus(n), setFocus(n), pick(), and close() methods (see the source for details), that can be used to change the focused element, pick the current element or close the menu.
            extraKeys: keymap
            Like customKeys above, but the bindings will be added to the set of default bindings, instead of replacing them.
            The following events will be fired on the completions object during completion:
            "shown" ()
            Fired when the pop-up is shown.
            "select" (completion, Element)
            Fired when a completion is selected. Passed the completion value (string or object) and the DOM node that represents it in the menu.
            "close" ()
            Fired when the completion is finished.
            This addon depends styles from addon/hint/show-hint.css. Check out the demo for an example.
            hint/javascript-hint.js
            Defines a simple hinting function for JavaScript (CodeMirror.hint.javascript) and CoffeeScript (CodeMirror.hint.coffeescript) code. This will simply use the JavaScript environment that the editor runs in as a source of information about objects and their properties.
            hint/xml-hint.js
            Defines CodeMirror.hint.xml, which produces hints for XML tagnames, attribute names, and attribute values, guided by a schemaInfo option (a property of the second argument passed to the hinting function, or the third argument passed to CodeMirror.showHint).
            The schema info should be an object mapping tag names to information about these tags, with optionally a "!top" property containing a list of the names of valid top-level tags. The values of the properties should be objects with optional properties children (an array of valid child element names, omit to simply allow all tags to appear) and attrs (an object mapping attribute names to null for free-form attributes, and an array of valid values for restricted attributes). Demo here.
            hint/html-hint.js
            Provides schema info to the xml-hint addon for HTML documents. Defines a schema object CodeMirror.htmlSchema that you can pass to as a schemaInfo option, and a CodeMirror.hint.html hinting function that automatically calls CodeMirror.hint.xml with this schema data. See the demo.
            hint/css-hint.js
            A minimal hinting function for CSS code. Defines CodeMirror.hint.css.
            hint/python-hint.js
            A very simple hinting function for Python code. Defines CodeMirror.hint.python.
            hint/anyword-hint.js
            A very simple hinting function (CodeMirror.hint.anyword) that simply looks for words in the nearby code and completes to those. Takes two optional options, word, a regular expression that matches words (sequences of one or more character), and range, which defines how many lines the addon should scan when completing (defaults to 500).
            hint/sql-hint.js
            A simple SQL hinter. Defines CodeMirror.hint.sql.
            hint/pig-hint.js
            A simple hinter for Pig Latin. Defines CodeMirror.hint.pig.
            search/match-highlighter.js
            Adds a highlightSelectionMatches option that can be enabled to highlight all instances of a currently selected word. Can be set either to true or to an object containing the following options: minChars, for the minimum amount of selected characters that triggers a highlight (default 2), style, for the style to be used to highlight the matches (default "matchhighlight", which will correspond to CSS class cm-matchhighlight), and showToken which can be set to true or to a regexp matching the characters that make up a word. When enabled, it causes the current word to be highlighted when nothing is selected (defaults to off). Demo here.
            lint/lint.js
            Defines an interface component for showing linting warnings, with pluggable warning sources (see json-lint.js, javascript-lint.js, and css-lint.js in the same directory). Defines a lint option that can be set to a warning source (for example CodeMirror.lint.javascript), or to true, in which case getHelper with type "lint" is used to determined a validator function. 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.
            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.
            comment/continuecomment.js
            Adds an continueComments option, which can be set to true to have the editor prefix new lines inside C-like block comments with an asterisk when Enter is pressed. It can also be set to a string in order to bind this functionality to a specific key..
            display/placeholder.js
            Adds a placeholder option that can be used to make text appear in the editor when it is empty and not focused. Also gives the editor a CodeMirror-empty CSS class whenever it doesn't contain any text. See the demo.
            display/fullscreen.js
            Defines an option fullScreen that, when set to true, will make the editor full-screen (as in, taking up the whole browser window). Depends on fullscreen.css. Demo here.
            wrap/hardwrap.js
            Addon to perform hard line wrapping/breaking for paragraphs of text. Adds these methods to editor instances:
            wrapParagraph(?pos: {line, ch}, ?options: object)
            Wraps the paragraph at the given position. If pos is not given, it defaults to the cursor position.
            wrapRange(from: {line, ch}, to: {line, ch}, ?options: object)
            Wraps the given range as one big paragraph.
            wrapParagraphsInRange(from: {line, ch}, to: {line, ch}, ?options: object)
            Wrapps the paragraphs in (and overlapping with) the given range individually.
            The following options are recognized:
            paragraphStart, paragraphEnd: RegExp
            Blank lines are always considered paragraph boundaries. These options can be used to specify a pattern that causes lines to be considered the start or end of a paragraph.
            column: number
            The column to wrap at. Defaults to 80.
            wrapOn: RegExp
            A regular expression that matches only those two-character strings that allow wrapping. By default, the addon wraps on whitespace and after dash characters.
            killTrailingSpace: boolean
            Whether trailing space caused by wrapping should be preserved, or deleted. Defaults to true.
            A demo of the addon is available here.
            merge/merge.js
            Implements an interface for merging changes, using either a 2-way or a 3-way view. The CodeMirror.MergeView constructor takes arguments similar to the CodeMirror constructor, first a node to append the interface to, and then an options object. Two extra optional options are recognized, origLeft and origRight, which may be strings that provide original versions of the document, which will be shown to the left and right of the editor in non-editable CodeMirror instances. The merge interface will highlight changes between the editable document and the original(s) (demo).
            tern/tern.js
            Provides integration with the Tern JavaScript analysis engine, for completion, definition finding, and minor refactoring help. See the demo for a very simple integration. For more involved scenarios, see the comments at the top of the addon and the implementation of the (multi-file) demonstration on the Tern website.

            Writing CodeMirror Modes

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

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

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

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

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

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

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

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

            eol() → boolean
            Returns true only if the stream is at the end of the line.
            sol() → boolean
            Returns true only if the stream is at the start of the line.
            peek() → string
            Returns the next character in the stream without advancing it. Will return an null at the end of the line.
            next() → string
            Returns the next character in the stream and advances it. Also returns null when no more characters are available.
            eat(match: string|regexp|function(char: string) → boolean) → string
            match can be a character, a regular expression, or a function that takes a character and returns a boolean. If the next character in the stream 'matches' the given argument, it is consumed and returned. Otherwise, undefined is returned.
            eatWhile(match: string|regexp|function(char: string) → boolean) → boolean
            Repeatedly calls eat with the given argument, until it fails. Returns true if any characters were eaten.
            eatSpace() → boolean
            Shortcut for eatWhile when matching white-space.
            skipToEnd()
            Moves the position to the end of the line.
            skipTo(ch: string) → 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: string, ?consume: boolean, ?caseFold: boolean) → boolean
            match(pattern: regexp, ?consume: boolean) → array<string>
            Act like a multi-character eat—if consume is true or not given—or a look-ahead that doesn't update the stream position—if it is false. pattern can be either a string or a regular expression starting with ^. When it is a string, caseFold can be set to true to make the match case-insensitive. When successfully matching a regular expression, the returned value will be the array returned by match, in case you need to extract matched groups.
            backUp(n: integer)
            Backs up the stream n characters. Backing it up further than the start of the current token will cause things to break, so be careful.
            column() → integer
            Returns the column (taking into account tabs) at which the current token starts.
            indentation() → integer
            Tells you how far the current line has been indented, in spaces. Corrects for tab characters.
            current() → string
            Get the string between the start of the current token and the current stream position.

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

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

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

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

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

            Finally, a mode may define 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 method, innerMode which, given a state object, returns a {state, mode} object with the inner mode and its state for the current position. These are used by utility scripts such as the tag closer to get context information. Use the CodeMirror.innerMode helper function to, starting from a mode and a state, recursively walk down to the innermost mode and state.

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

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

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

            ================================================ FILE: public/packages/codemirror-3.19/doc/realworld.html ================================================ CodeMirror: Real-world Uses

            CodeMirror real-world uses

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

            ================================================ FILE: public/packages/codemirror-3.19/doc/releases.html ================================================ CodeMirror: Release History

            Release notes and version history

            Version 3.x

            21-10-2013: Version 3.19:

            23-09-2013: Version 3.18:

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

            23-09-2013: Version 3.17:

            21-08-2013: Version 3.16:

            29-07-2013: Version 3.15:

            20-06-2013: Version 3.14:

            20-05-2013: Version 3.13:

            19-04-2013: Version 3.12:

            20-03-2013: Version 3.11:

            21-02-2013: Version 3.1:

            25-01-2013: Version 3.02:

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

            21-01-2013: Version 3.01:

            10-12-2012: Version 3.0:

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

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

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

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

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

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

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

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

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

            Version 2.x

            21-01-2013: Version 2.38:

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

            20-12-2012: Version 2.37:

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

            20-11-2012: Version 2.36:

            22-10-2012: Version 2.35:

            19-09-2012: Version 2.34:

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

            23-08-2012: Version 2.33:

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

            23-07-2012: Version 2.32:

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

            20-07-2012: Version 2.31:

            22-06-2012: Version 2.3:

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

            23-05-2012: Version 2.25:

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

            23-04-2012: Version 2.24:

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

            26-03-2012: Version 2.23:

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

            27-02-2012: Version 2.22:

            27-01-2012: Version 2.21:

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

            20-12-2011: Version 2.2:

            21-11-2011: Version 2.18:

            Fixes TextMarker.clear, which is broken in 2.17.

            21-11-2011: Version 2.17:

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

            27-10-2011: Version 2.16:

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

            26-09-2011: Version 2.15:

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

            26-09-2011: Version 2.14:

            23-08-2011: Version 2.13:

            25-07-2011: Version 2.12:

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

            04-07-2011: Version 2.11:

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

            07-06-2011: Version 2.1:

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

            07-06-2011: Version 2.02:

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

            26-05-2011: Version 2.01:

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

            28-03-2011: Version 2.0:

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

            22-02-2011: Version 2.0 beta 2:

            Somewhat more mature API, lots of bugs shaken out.

            17-02-2011: Version 0.94:

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

            08-02-2011: Version 2.0 beta 1:

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

            19-01-2011: Version 0.93:

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

            Version 0.x

            28-03-2011: Version 1.0:

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

            17-12-2010: Version 0.92:

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

            11-11-2010: Version 0.91:

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

            02-10-2010: Version 0.9:

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

            22-07-2010: Version 0.8:

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

            27-04-2010: Version 0.67:

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

            01-03-2010: Version 0.66:

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

            12-11-2009: Version 0.65:

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

            23-10-2009: Version 0.64:

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

            31-08-2009: Version 0.63:

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

            30-05-2009: Version 0.62:

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

            ================================================ FILE: public/packages/codemirror-3.19/doc/reporting.html ================================================ CodeMirror: Reporting Bugs

            Reporting bugs effectively

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

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

            Upgrading to v2.2

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

            No more default.css

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

            Different key customization

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

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

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

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

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

              extraKeys: {"Home": "goLineStart"}

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

              extraKeys: {"Enter": false}

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

            Tabs

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

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

            ================================================ FILE: public/packages/codemirror-3.19/doc/upgrade_v3.html ================================================ CodeMirror: Version 3 upgrade guide

            Upgrading to version 3

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

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

            DOM structure

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

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

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

            See the styling section of the manual for more information.

            Gutter model

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

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

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

            Event handling

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

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

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

            markText method arguments

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

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

            Line folding

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

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

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

            Line CSS classes

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

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

            Position properties

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

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

            Bracket matching no longer in core

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

            Mode management

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

            New features

            Some more reasons to upgrade to version 3.

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

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

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

            This is CodeMirror

            DOWNLOAD LATEST RELEASE
            version 3.19 (Release notes)
            DONATE WITH PAYPAL
            or Bank, Gittip, Flattr
            × Bank: Rabobank
            Country: Netherlands
            SWIFT: RABONL2U
            Account: 147850770
            Name: Marijn Haverbeke
            IBAN: NL26 RABO 0147 8507 70

            Features

            Community

            CodeMirror is an open-source project shared under an MIT license. It is the editor used in Light Table, Adobe Brackets, Google Apps Script, Bitbucket, and many other projects.

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

            Discussion around the project is done on a mailing list. There is also the codemirror-announce list, which is only used for major announcements (such as new versions). If needed, you can contact the maintainer directly.

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

            Browser support

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

            Firefoxversion 3 and up
            Chromeany version
            Safariversion 5.2 and up
            Internet Explorerversion 8 and up
            Operaversion 9 and up

            Modern mobile browsers tend to partly work. Bug reports and patches for mobile support are welcome, but the maintainer does not have the time or budget to actually work on it himself.

            ================================================ FILE: public/packages/codemirror-3.19/keymap/emacs.js ================================================ (function() { "use strict"; var Pos = CodeMirror.Pos; function posEq(a, b) { return a.line == b.line && a.ch == b.ch; } // Kill 'ring' var killRing = []; function addToRing(str) { killRing.push(str); if (killRing.length > 50) killRing.shift(); } function growRingTop(str) { if (!killRing.length) return addToRing(str); killRing[killRing.length - 1] += str; } function getFromRing(n) { return killRing[killRing.length - (n ? Math.min(n, 1) : 1)] || ""; } function popFromRing() { if (killRing.length > 1) killRing.pop(); return getFromRing(); } var lastKill = null; function kill(cm, from, to, mayGrow, text) { if (text == null) text = cm.getRange(from, to); if (mayGrow && lastKill && lastKill.cm == cm && posEq(from, lastKill.pos) && cm.isClean(lastKill.gen)) growRingTop(text); else addToRing(text); cm.replaceRange("", from, to, "+delete"); if (mayGrow) lastKill = {cm: cm, pos: from, gen: cm.changeGeneration()}; else lastKill = null; } // Boundaries of various units function byChar(cm, pos, dir) { return cm.findPosH(pos, dir, "char", true); } function byWord(cm, pos, dir) { return cm.findPosH(pos, dir, "word", true); } function byLine(cm, pos, dir) { return cm.findPosV(pos, dir, "line", cm.doc.sel.goalColumn); } function byPage(cm, pos, dir) { return cm.findPosV(pos, dir, "page", cm.doc.sel.goalColumn); } function byParagraph(cm, pos, dir) { var no = pos.line, line = cm.getLine(no); var sawText = /\S/.test(dir < 0 ? line.slice(0, pos.ch) : line.slice(pos.ch)); var fst = cm.firstLine(), lst = cm.lastLine(); for (;;) { no += dir; if (no < fst || no > lst) return cm.clipPos(Pos(no - dir, dir < 0 ? 0 : null)); line = cm.getLine(no); var hasText = /\S/.test(line); if (hasText) sawText = true; else if (sawText) return Pos(no, 0); } } function bySentence(cm, pos, dir) { var line = pos.line, ch = pos.ch; var text = cm.getLine(pos.line), sawWord = false; for (;;) { var next = text.charAt(ch + (dir < 0 ? -1 : 0)); if (!next) { // End/beginning of line reached if (line == (dir < 0 ? cm.firstLine() : cm.lastLine())) return Pos(line, ch); text = cm.getLine(line + dir); if (!/\S/.test(text)) return Pos(line, ch); line += dir; ch = dir < 0 ? text.length : 0; continue; } if (sawWord && /[!?.]/.test(next)) return Pos(line, ch + (dir > 0 ? 1 : 0)); if (!sawWord) sawWord = /\w/.test(next); ch += dir; } } function byExpr(cm, pos, dir) { var wrap; if (cm.findMatchingBracket && (wrap = cm.findMatchingBracket(pos, true)) && wrap.match && (wrap.forward ? 1 : -1) == dir) return dir > 0 ? Pos(wrap.to.line, wrap.to.ch + 1) : wrap.to; for (var first = true;; first = false) { var token = cm.getTokenAt(pos); var after = Pos(pos.line, dir < 0 ? token.start : token.end); if (first && dir > 0 && token.end == pos.ch || !/\w/.test(token.string)) { var newPos = cm.findPosH(after, dir, "char"); if (posEq(after, newPos)) return pos; else pos = newPos; } else { return after; } } } // Prefixes (only crudely supported) function getPrefix(cm, precise) { var digits = cm.state.emacsPrefix; if (!digits) return precise ? null : 1; clearPrefix(cm); return digits == "-" ? -1 : Number(digits); } function repeated(cmd) { var f = typeof cmd == "string" ? function(cm) { cm.execCommand(cmd); } : cmd; return function(cm) { var prefix = getPrefix(cm); f(cm); for (var i = 1; i < prefix; ++i) f(cm); }; } function findEnd(cm, by, dir) { var pos = cm.getCursor(), prefix = getPrefix(cm); if (prefix < 0) { dir = -dir; prefix = -prefix; } for (var i = 0; i < prefix; ++i) { var newPos = by(cm, pos, dir); if (posEq(newPos, pos)) break; pos = newPos; } return pos; } function move(by, dir) { var f = function(cm) { cm.extendSelection(findEnd(cm, by, dir)); }; f.motion = true; return f; } function killTo(cm, by, dir) { kill(cm, cm.getCursor(), findEnd(cm, by, dir), true); } function addPrefix(cm, digit) { if (cm.state.emacsPrefix) { if (digit != "-") cm.state.emacsPrefix += digit; return; } // Not active yet cm.state.emacsPrefix = digit; cm.on("keyHandled", maybeClearPrefix); cm.on("inputRead", maybeDuplicateInput); } var prefixPreservingKeys = {"Alt-G": true, "Ctrl-X": true, "Ctrl-Q": true, "Ctrl-U": true}; function maybeClearPrefix(cm, arg) { if (!cm.state.emacsPrefixMap && !prefixPreservingKeys.hasOwnProperty(arg)) clearPrefix(cm); } function clearPrefix(cm) { cm.state.emacsPrefix = null; cm.off("keyHandled", maybeClearPrefix); cm.off("inputRead", maybeDuplicateInput); } function maybeDuplicateInput(cm, event) { var dup = getPrefix(cm); if (dup > 1 && event.origin == "+input") { var one = event.text.join("\n"), txt = ""; for (var i = 1; i < dup; ++i) txt += one; cm.replaceSelection(txt, "end", "+input"); } } function addPrefixMap(cm) { cm.state.emacsPrefixMap = true; cm.addKeyMap(prefixMap); cm.on("keyHandled", maybeRemovePrefixMap); cm.on("inputRead", maybeRemovePrefixMap); } function maybeRemovePrefixMap(cm, arg) { if (typeof arg == "string" && (/^\d$/.test(arg) || arg == "Ctrl-U")) return; cm.removeKeyMap(prefixMap); cm.state.emacsPrefixMap = false; cm.off("keyHandled", maybeRemovePrefixMap); cm.off("inputRead", maybeRemovePrefixMap); } // Utilities function setMark(cm) { cm.setCursor(cm.getCursor()); cm.setExtending(true); cm.on("change", function() { cm.setExtending(false); }); } function getInput(cm, msg, f) { if (cm.openDialog) cm.openDialog(msg + ": ", f, {bottom: true}); else f(prompt(msg, "")); } function operateOnWord(cm, op) { var start = cm.getCursor(), end = cm.findPosH(start, 1, "word"); cm.replaceRange(op(cm.getRange(start, end)), start, end); cm.setCursor(end); } function toEnclosingExpr(cm) { var pos = cm.getCursor(), line = pos.line, ch = pos.ch; var stack = []; while (line >= cm.firstLine()) { var text = cm.getLine(line); for (var i = ch == null ? text.length : ch; i > 0;) { var ch = text.charAt(--i); if (ch == ")") stack.push("("); else if (ch == "]") stack.push("["); else if (ch == "}") stack.push("{"); else if (/[\(\{\[]/.test(ch) && (!stack.length || stack.pop() != ch)) return cm.extendSelection(Pos(line, i)); } --line; ch = null; } } // Actual keymap var keyMap = CodeMirror.keyMap.emacs = { "Ctrl-W": function(cm) {kill(cm, cm.getCursor("start"), cm.getCursor("end"));}, "Ctrl-K": repeated(function(cm) { var start = cm.getCursor(), end = cm.clipPos(Pos(start.line)); var text = cm.getRange(start, end); if (!/\S/.test(text)) { text += "\n"; end = Pos(start.line + 1, 0); } kill(cm, start, end, true, text); }), "Alt-W": function(cm) { addToRing(cm.getSelection()); }, "Ctrl-Y": function(cm) { var start = cm.getCursor(); cm.replaceRange(getFromRing(getPrefix(cm)), start, start, "paste"); cm.setSelection(start, cm.getCursor()); }, "Alt-Y": function(cm) {cm.replaceSelection(popFromRing());}, "Ctrl-Space": setMark, "Ctrl-Shift-2": setMark, "Ctrl-F": move(byChar, 1), "Ctrl-B": move(byChar, -1), "Right": move(byChar, 1), "Left": move(byChar, -1), "Ctrl-D": function(cm) { killTo(cm, byChar, 1); }, "Delete": function(cm) { killTo(cm, byChar, 1); }, "Ctrl-H": function(cm) { killTo(cm, byChar, -1); }, "Backspace": function(cm) { killTo(cm, byChar, -1); }, "Alt-F": move(byWord, 1), "Alt-B": move(byWord, -1), "Alt-D": function(cm) { killTo(cm, byWord, 1); }, "Alt-Backspace": function(cm) { killTo(cm, byWord, -1); }, "Ctrl-N": move(byLine, 1), "Ctrl-P": move(byLine, -1), "Down": move(byLine, 1), "Up": move(byLine, -1), "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "End": "goLineEnd", "Home": "goLineStart", "Alt-V": move(byPage, -1), "Ctrl-V": move(byPage, 1), "PageUp": move(byPage, -1), "PageDown": move(byPage, 1), "Ctrl-Up": move(byParagraph, -1), "Ctrl-Down": move(byParagraph, 1), "Alt-A": move(bySentence, -1), "Alt-E": move(bySentence, 1), "Alt-K": function(cm) { killTo(cm, bySentence, 1); }, "Ctrl-Alt-K": function(cm) { killTo(cm, byExpr, 1); }, "Ctrl-Alt-Backspace": function(cm) { killTo(cm, byExpr, -1); }, "Ctrl-Alt-F": move(byExpr, 1), "Ctrl-Alt-B": move(byExpr, -1), "Shift-Ctrl-Alt-2": function(cm) { cm.setSelection(findEnd(cm, byExpr, 1), cm.getCursor()); }, "Ctrl-Alt-T": function(cm) { var leftStart = byExpr(cm, cm.getCursor(), -1), leftEnd = byExpr(cm, leftStart, 1); var rightEnd = byExpr(cm, leftEnd, 1), rightStart = byExpr(cm, rightEnd, -1); cm.replaceRange(cm.getRange(rightStart, rightEnd) + cm.getRange(leftEnd, rightStart) + cm.getRange(leftStart, leftEnd), leftStart, rightEnd); }, "Ctrl-Alt-U": repeated(toEnclosingExpr), "Alt-Space": function(cm) { var pos = cm.getCursor(), from = pos.ch, to = pos.ch, text = cm.getLine(pos.line); while (from && /\s/.test(text.charAt(from - 1))) --from; while (to < text.length && /\s/.test(text.charAt(to))) ++to; cm.replaceRange(" ", Pos(pos.line, from), Pos(pos.line, to)); }, "Ctrl-O": repeated(function(cm) { cm.replaceSelection("\n", "start"); }), "Ctrl-T": repeated(function(cm) { var pos = cm.getCursor(); if (pos.ch < cm.getLine(pos.line).length) pos = Pos(pos.line, pos.ch + 1); var from = cm.findPosH(pos, -2, "char"); var range = cm.getRange(from, pos); if (range.length != 2) return; cm.setSelection(from, pos); cm.replaceSelection(range.charAt(1) + range.charAt(0), "end"); }), "Alt-C": repeated(function(cm) { operateOnWord(cm, function(w) { var letter = w.search(/\w/); if (letter == -1) return w; return w.slice(0, letter) + w.charAt(letter).toUpperCase() + w.slice(letter + 1).toLowerCase(); }); }), "Alt-U": repeated(function(cm) { operateOnWord(cm, function(w) { return w.toUpperCase(); }); }), "Alt-L": repeated(function(cm) { operateOnWord(cm, function(w) { return w.toLowerCase(); }); }), "Alt-;": "toggleComment", "Ctrl-/": repeated("undo"), "Shift-Ctrl--": repeated("undo"), "Ctrl-Z": repeated("undo"), "Cmd-Z": repeated("undo"), "Shift-Alt-,": "goDocStart", "Shift-Alt-.": "goDocEnd", "Ctrl-S": "findNext", "Ctrl-R": "findPrev", "Ctrl-G": "clearSearch", "Shift-Alt-5": "replace", "Alt-/": "autocomplete", "Ctrl-J": "newlineAndIndent", "Enter": false, "Tab": "indentAuto", "Alt-G": function(cm) {cm.setOption("keyMap", "emacs-Alt-G");}, "Ctrl-X": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-X");}, "Ctrl-Q": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-Q");}, "Ctrl-U": addPrefixMap }; CodeMirror.keyMap["emacs-Ctrl-X"] = { "Tab": function(cm) { cm.indentSelection(getPrefix(cm, true) || cm.getOption("indentUnit")); }, "Ctrl-X": function(cm) { cm.setSelection(cm.getCursor("head"), cm.getCursor("anchor")); }, "Ctrl-S": "save", "Ctrl-W": "save", "S": "saveAll", "F": "open", "U": repeated("undo"), "K": "close", "Delete": function(cm) { kill(cm, cm.getCursor(), bySentence(cm, cm.getCursor(), 1), true); }, auto: "emacs", nofallthrough: true, disableInput: true }; CodeMirror.keyMap["emacs-Alt-G"] = { "G": function(cm) { var prefix = getPrefix(cm, true); if (prefix != null && prefix > 0) return cm.setCursor(prefix - 1); getInput(cm, "Goto line", function(str) { var num; if (str && !isNaN(num = Number(str)) && num == num|0 && num > 0) cm.setCursor(num - 1); }); }, auto: "emacs", nofallthrough: true, disableInput: true }; CodeMirror.keyMap["emacs-Ctrl-Q"] = { "Tab": repeated("insertTab"), auto: "emacs", nofallthrough: true }; var prefixMap = {"Ctrl-G": clearPrefix}; function regPrefix(d) { prefixMap[d] = function(cm) { addPrefix(cm, d); }; keyMap["Ctrl-" + d] = function(cm) { addPrefix(cm, d); }; prefixPreservingKeys["Ctrl-" + d] = true; } for (var i = 0; i < 10; ++i) regPrefix(String(i)); regPrefix("-"); })(); ================================================ FILE: public/packages/codemirror-3.19/keymap/extra.js ================================================ // A number of additional default bindings that are too obscure to // include in the core codemirror.js file. (function() { "use strict"; var Pos = CodeMirror.Pos; function moveLines(cm, start, end, dist) { if (!dist || start > end) return 0; var from = cm.clipPos(Pos(start, 0)), to = cm.clipPos(Pos(end)); var text = cm.getRange(from, to); if (start <= cm.firstLine()) cm.replaceRange("", from, Pos(to.line + 1, 0)); else cm.replaceRange("", Pos(from.line - 1), to); var target = from.line + dist; if (target <= cm.firstLine()) { cm.replaceRange(text + "\n", Pos(target, 0)); return cm.firstLine() - from.line; } else { var targetPos = cm.clipPos(Pos(target - 1)); cm.replaceRange("\n" + text, targetPos); return targetPos.line + 1 - from.line; } } function moveSelectedLines(cm, dist) { var head = cm.getCursor("head"), anchor = cm.getCursor("anchor"); cm.operation(function() { var moved = moveLines(cm, Math.min(head.line, anchor.line), Math.max(head.line, anchor.line), dist); cm.setSelection(Pos(anchor.line + moved, anchor.ch), Pos(head.line + moved, head.ch)); }); } CodeMirror.commands.moveLinesUp = function(cm) { moveSelectedLines(cm, -1); }; CodeMirror.commands.moveLinesDown = function(cm) { moveSelectedLines(cm, 1); }; CodeMirror.keyMap["default"]["Alt-Up"] = "moveLinesUp"; CodeMirror.keyMap["default"]["Alt-Down"] = "moveLinesDown"; })(); ================================================ FILE: public/packages/codemirror-3.19/keymap/vim.js ================================================ /** * 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. * * Events: * 'vim-mode-change' - raised on the editor anytime the current mode changes, * Event object: {mode: "visual", subMode: "linewise"} * * Code structure: * 1. Default keymap * 2. Variable declarations and short basic helpers * 3. Instance (External API) implementation * 4. Internal state tracking objects (input state, counter) implementation * and 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: [''], type: 'keyToKey', toKeys: ['h'] }, { keys: [''], type: 'keyToKey', toKeys: ['l'] }, { keys: [''], type: 'keyToKey', toKeys: ['k'] }, { keys: [''], type: 'keyToKey', toKeys: ['j'] }, { keys: [''], type: 'keyToKey', toKeys: ['l'] }, { keys: [''], type: 'keyToKey', toKeys: ['h'] }, { keys: [''], type: 'keyToKey', toKeys: ['W'] }, { keys: [''], type: 'keyToKey', toKeys: ['B'] }, { keys: [''], type: 'keyToKey', toKeys: ['w'] }, { keys: [''], type: 'keyToKey', toKeys: ['b'] }, { keys: [''], type: 'keyToKey', toKeys: ['j'] }, { keys: [''], type: 'keyToKey', toKeys: ['k'] }, { keys: ['C-['], type: 'keyToKey', toKeys: [''] }, { keys: [''], type: 'keyToKey', toKeys: [''] }, { keys: ['s'], type: 'keyToKey', toKeys: ['c', 'l'], context: 'normal' }, { keys: ['s'], type: 'keyToKey', toKeys: ['x', 'i'], context: 'visual'}, { keys: ['S'], type: 'keyToKey', toKeys: ['c', 'c'], context: 'normal' }, { keys: ['S'], type: 'keyToKey', toKeys: ['d', 'c', 'c'], context: 'visual' }, { keys: [''], type: 'keyToKey', toKeys: ['0'] }, { keys: [''], type: 'keyToKey', toKeys: ['$'] }, { keys: [''], type: 'keyToKey', toKeys: [''] }, { keys: [''], type: 'keyToKey', toKeys: [''] }, // Motions { keys: ['H'], type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }}, { keys: ['M'], type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }}, { keys: ['L'], type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }}, { keys: ['h'], type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }}, { keys: ['l'], type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }}, { keys: ['j'], type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }}, { keys: ['k'], type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }}, { keys: ['g','j'], type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }}, { keys: ['g','k'], type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }}, { keys: ['w'], type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }}, { keys: ['W'], type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }}, { keys: ['e'], type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }}, { keys: ['E'], type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }}, { keys: ['b'], type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }}, { keys: ['B'], type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }}, { keys: ['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, toJumplist: true }}, { keys: ['}'], type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }}, { keys: [''], type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }}, { keys: [''], type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }}, { keys: [''], type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }}, { keys: [''], type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }}, { keys: ['g', 'g'], type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }}, { keys: ['G'], type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }}, { keys: ['0'], type: 'motion', motion: 'moveToStartOfLine' }, { keys: ['^'], type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' }, { keys: ['+'], type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }}, { keys: ['-'], type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }}, { keys: ['_'], type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }}, { keys: ['$'], type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }}, { keys: ['%'], type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }}, { keys: ['f', '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: [';'], type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }}, { keys: [','], type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }}, { keys: ['\'', 'character'], type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}}, { keys: ['`', 'character'], type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}}, { keys: [']', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } }, { keys: ['[', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } }, { keys: [']', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } }, { keys: ['[', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } }, { keys: [']', 'character'], type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}}, { keys: ['[', 'character'], type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}}, { 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' }, { 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', motionArgs: { forward: true, toJumplist: true }}, { keys: ['N'], type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }}, // Operator-Motion dual commands { keys: ['x'], type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }}, { keys: ['X'], type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }}, { keys: ['D'], type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, operatorMotionArgs: { visualLine: true }}, { keys: ['Y'], type: 'operatorMotion', operator: 'yank', motion: 'moveToEol', motionArgs: { inclusive: true }, operatorMotionArgs: { visualLine: true }}, { keys: ['C'], type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, operatorMotionArgs: { visualLine: true }}, { keys: ['~'], type: 'operatorMotion', operator: 'swapcase', operatorArgs: { shouldMoveCursor: true }, motion: 'moveByCharacters', motionArgs: { forward: true }}, // Actions { keys: [''], type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }}, { keys: [''], type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }}, { keys: ['a'], type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }}, { keys: ['A'], type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }}, { keys: ['i'], type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }}, { keys: ['I'], type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank' }}, { keys: ['o'], type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }}, { keys: ['O'], type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }}, { keys: ['v'], type: 'action', action: 'toggleVisualMode' }, { keys: ['V'], type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }}, { keys: ['J'], type: 'action', action: 'joinLines', isEdit: true }, { keys: ['p'], type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }}, { keys: ['P'], type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }}, { keys: ['r', 'character'], type: 'action', action: 'replace', isEdit: true }, { keys: ['@', 'character'], type: 'action', action: 'replayMacro' }, { keys: ['q', 'character'], type: 'action', action: 'enterMacroRecordMode' }, // Handle Replace-mode as a special case of insert mode. { keys: ['R'], type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }}, { keys: ['u'], type: 'action', action: 'undo' }, { keys: [''], 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', ''], 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' }, { keys: ['.'], type: 'action', action: 'repeatLastEdit' }, { keys: [''], type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}}, { keys: [''], type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}}, // 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', toJumplist: true }}, { keys: ['?'], type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }}, { keys: ['*'], type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }}, { keys: ['#'], type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }}, // Ex command { keys: [':'], type: 'ex' } ]; var Vim = function() { CodeMirror.defineOption('vimMode', false, function(cm, val) { if (val) { cm.setOption('keyMap', 'vim'); CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); cm.on('beforeSelectionChange', beforeSelectionChange); maybeInitVimState(cm); } else if (cm.state.vim) { cm.setOption('keyMap', 'default'); cm.off('beforeSelectionChange', beforeSelectionChange); cm.state.vim = null; } }); function beforeSelectionChange(cm, cur) { var vim = cm.state.vim; if (vim.insertMode || vim.exMode) return; var head = cur.head; if (head.ch && head.ch == cm.doc.getLine(head.line).length) { head.ch--; } } var numberRegex = /[\d]/; 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 specialSymbols = '~`!@#$%^&*()_-+=[{}]\\|/?.,<>:;"\''.split(''); var specialKeys = ['Left', 'Right', 'Up', 'Down', 'Space', 'Backspace', 'Esc', 'Home', 'End', 'PageUp', 'PageDown', 'Enter']; var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']); var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"']); function isLine(cm, line) { return line >= cm.firstLine() && line <= cm.lastLine(); } function isLowerCase(k) { return (/^[a-z]$/).test(k); } function isMatchableSymbol(k) { return '()[]{}'.indexOf(k) != -1; } function isNumber(k) { return numberRegex.test(k); } function isUpperCase(k) { return (/^[A-Z]$/).test(k); } function isWhiteSpaceString(k) { return (/^\s*$/).test(k); } function inArray(val, arr) { for (var i = 0; i < arr.length; i++) { if (arr[i] == val) { return true; } } return false; } var createCircularJumpList = function() { var size = 100; var pointer = -1; var head = 0; var tail = 0; var buffer = new Array(size); function add(cm, oldCur, newCur) { var current = pointer % size; var curMark = buffer[current]; function useNextSlot(cursor) { var next = ++pointer % size; var trashMark = buffer[next]; if (trashMark) { trashMark.clear(); } buffer[next] = cm.setBookmark(cursor); } if (curMark) { var markPos = curMark.find(); // avoid recording redundant cursor position if (markPos && !cursorEqual(markPos, oldCur)) { useNextSlot(oldCur); } } else { useNextSlot(oldCur); } useNextSlot(newCur); head = pointer; tail = pointer - size + 1; if (tail < 0) { tail = 0; } } function move(cm, offset) { pointer += offset; if (pointer > head) { pointer = head; } else if (pointer < tail) { pointer = tail; } var mark = buffer[(size + pointer) % size]; // skip marks that are temporarily removed from text buffer if (mark && !mark.find()) { var inc = offset > 0 ? 1 : -1; var newCur; var oldCur = cm.getCursor(); do { pointer += inc; mark = buffer[(size + pointer) % size]; // skip marks that are the same as current position if (mark && (newCur = mark.find()) && !cursorEqual(oldCur, newCur)) { break; } } while (pointer < head && pointer > tail); } return mark; } return { cachedCursor: undefined, //used for # and * jumps add: add, move: move }; }; var createMacroState = function() { return { macroKeyBuffer: [], latestRegister: undefined, inReplay: false, lastInsertModeChanges: { changes: [], // Change list expectCursorActivityForChange: false // Set to true on change, false on cursorActivity. }, enteredMacroMode: undefined, isMacroPlaying: false, toggle: function(cm, registerName) { if (this.enteredMacroMode) { //onExit this.enteredMacroMode(); // close dialog this.enteredMacroMode = undefined; } else { //onEnter this.latestRegister = registerName; this.enteredMacroMode = cm.openDialog( '(recording)['+registerName+']', null, {bottom:true}); } } }; }; function maybeInitVimState(cm) { if (!cm.state.vim) { // Store instance state in the CodeMirror object. cm.state.vim = { inputState: new InputState(), // Vim's input state that triggered the last edit, used to repeat // motions and operators with '.'. lastEditInputState: undefined, // Vim's action command before the last edit, used to repeat actions // with '.' and insert mode repeat. lastEditActionCommand: undefined, // When using jk for navigation, if you move from a longer line to a // shorter line, the cursor may clip to the end of the shorter line. // If j is pressed again and cursor goes to the next line, the // cursor should go back to its horizontal position on the longer // line if it can. This is to keep track of the horizontal position. lastHPos: -1, // Doing the same with screen-position for gj/gk lastHSPos: -1, // The last motion command run. Cleared if a non-motion command gets // executed in between. lastMotion: null, marks: {}, insertMode: false, // Repeat count for changes made in insert mode, triggered by key // sequences like 3,i. Only exists when insertMode is true. insertModeRepeat: undefined, visualMode: false, // If we are in visual line mode. No effect if visualMode is false. visualLine: false }; } return cm.state.vim; } var vimGlobalState; function resetVimGlobalState() { vimGlobalState = { // The current search query. searchQuery: null, // Whether we are searching backwards. searchIsReversed: false, jumpList: createCircularJumpList(), macroModeState: createMacroState(), // Recording latest f, t, F or T motion command. lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''}, registerController: new RegisterController({}) }; } var vimApi= { buildKeyMap: function() { // TODO: Convert keymap into dictionary format for fast lookup. }, // Testing hook, though it might be useful to expose the register // controller anyways. getRegisterController: function() { return vimGlobalState.registerController; }, // Testing hook. resetVimGlobalState_: resetVimGlobalState, // Testing hook. getVimGlobalState_: function() { return vimGlobalState; }, // Testing hook. maybeInitVimState_: maybeInitVimState, InsertModeKey: InsertModeKey, map: function(lhs, rhs) { // Add user defined key bindings. exCommandDispatcher.map(lhs, rhs); }, defineEx: function(name, prefix, func){ if (name.indexOf(prefix) !== 0) { throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered'); } exCommands[name]=func; exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'}; }, // 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 = maybeInitVimState(cm); var macroModeState = vimGlobalState.macroModeState; if (macroModeState.enteredMacroMode) { if (key == 'q') { actions.exitMacroRecordMode(); vim.inputState = new InputState(); return; } } if (key == '') { // Clear input state and get back to normal mode. vim.inputState = new InputState(); if (vim.visualMode) { exitVisualMode(cm); } return; } // Enter visual mode when the mouse selects text. if (!vim.visualMode && !cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) { vim.visualMode = true; vim.visualLine = false; CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"}); cm.on('mousedown', exitVisualMode); } 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 { if (macroModeState.enteredMacroMode) { logKey(macroModeState, key); } commandDispatcher.processCommand(cm, vim, command); } }, handleEx: function(cm, input) { exCommandDispatcher.processCommand(cm, input); } }; // Represents the current input state. function InputState() { this.prefixRepeat = []; this.motionRepeat = []; this.operator = null; this.operatorArgs = null; this.motion = null; this.motionArgs = null; this.keyBuffer = []; // For matching multi-key commands. this.registerName = null; // Defaults to the 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) { if (linewise && text.charAt(0) == '\n') { text = text.slice(1) + '\n'; } if(linewise && text.charAt(text.length - 1) !== '\n'){ text += '\n'; } // Lowercase and uppercase registers refer to the same register. // Uppercase just means append. var register = this.isValidRegister(registerName) ? this.getRegister(registerName) : null; // if no register/an invalid register was specified, things go to the // default registers if (!register) { switch (operator) { case 'yank': // The 0 register contains the text from the most recent yank. this.registers['0'] = new Register(text, linewise); 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); } }, setRegisterText: function(name, text, linewise) { this.getRegister(name).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); var matchedCommands = []; var selectedCharacter; for (var i = 0; i < keyMap.length; i++) { var command = keyMap[i]; if (matchKeysPartial(keys, command.keys)) { 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; } // Match commands that take as an argument. if (command.keys[keys.length - 1] == 'character') { selectedCharacter = keys[keys.length - 1]; if(selectedCharacter.length>1){ switch(selectedCharacter){ case '': selectedCharacter='\n'; break; case '': selectedCharacter=' '; break; default: continue; } } } // Add the command to the list of matched commands. Choose the best // command later. matchedCommands.push(command); } } // Returns the command if it is a full match, or null if not. function getFullyMatchedCommandOrNull(command) { 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 (command.keys[keys.length - 1] == 'character') { inputState.selectedCharacter = selectedCharacter; } // Clear the buffer since a full match was found. inputState.keyBuffer = []; return command; } } if (!matchedCommands.length) { // Clear the buffer since there were no matches. inputState.keyBuffer = []; return null; } else if (matchedCommands.length == 1) { return getFullyMatchedCommandOrNull(matchedCommands[0]); } else { // Find the best match in the list of matchedCommands. var context = vim.visualMode ? 'visual' : 'normal'; var bestMatch = matchedCommands[0]; // Default to first in the list. for (var i = 0; i < matchedCommands.length; i++) { if (matchedCommands[i].context == context) { bestMatch = matchedCommands[i]; break; } } return getFullyMatchedCommandOrNull(bestMatch); } }, processCommand: function(cm, vim, command) { vim.inputState.repeatOverride = command.repeatOverride; switch (command.type) { case 'motion': this.processMotion(cm, vim, command); break; case 'operator': this.processOperator(cm, vim, command); break; case 'operatorMotion': this.processOperatorMotion(cm, vim, command); break; case 'action': this.processAction(cm, vim, command); break; case 'search': this.processSearch(cm, vim, command); break; case 'ex': case 'keyToEx': this.processEx(cm, vim, command); break; default: break; } }, processMotion: function(cm, vim, command) { vim.inputState.motion = command.motion; vim.inputState.motionArgs = copyArgs(command.motionArgs); this.evalInput(cm, vim); }, processOperator: function(cm, vim, command) { var inputState = vim.inputState; if (inputState.operator) { if (inputState.operator == command.operator) { // Typing an operator twice like 'dd' makes the operator operate // linewise inputState.motion = 'expandToLine'; inputState.motionArgs = { linewise: true }; this.evalInput(cm, vim); return; } else { // 2 different operators in a row doesn't make sense. vim.inputState = new InputState(); } } 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; vim.inputState = new InputState(); vim.lastMotion = null; if (command.isEdit) { this.recordLastEdit(vim, inputState, command); } actions[command.action](cm, actionArgs, vim); }, processSearch: function(cm, vim, command) { if (!cm.getSearchCursor) { // Search depends on SearchCursor. return; } var forward = command.searchArgs.forward; getSearchState(cm).setReversed(!forward); var promptPrefix = (forward) ? '/' : '?'; var originalQuery = getSearchState(cm).getQuery(); var originalScrollPos = cm.getScrollInfo(); function handleQuery(query, ignoreCase, smartCase) { try { updateSearchQuery(cm, query, ignoreCase, smartCase); } catch (e) { showConfirm(cm, 'Invalid regex: ' + query); return; } commandDispatcher.processMotion(cm, vim, { type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist } }); } function onPromptClose(query) { cm.scrollTo(originalScrollPos.left, originalScrollPos.top); handleQuery(query, true /** ignoreCase */, true /** smartCase */); } function onPromptKeyUp(_e, query) { var parsedQuery; try { parsedQuery = updateSearchQuery(cm, query, true /** ignoreCase */, true /** smartCase */); } catch (e) { // Swallow bad regexes for incremental search. } if (parsedQuery) { cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30); } else { clearSearchHighlight(cm); cm.scrollTo(originalScrollPos.left, originalScrollPos.top); } } function onPromptKeyDown(e, _query, close) { var keyName = CodeMirror.keyName(e); if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') { updateSearchQuery(cm, originalQuery); clearSearchHighlight(cm); cm.scrollTo(originalScrollPos.left, originalScrollPos.top); CodeMirror.e_stop(e); close(); cm.focus(); } } switch (command.searchArgs.querySrc) { case 'prompt': showPrompt(cm, { onClose: onPromptClose, prefix: promptPrefix, desc: searchPromptDesc, onKeyUp: onPromptKeyUp, onKeyDown: onPromptKeyDown }); break; case 'wordUnderCursor': var word = expandWordUnderCursor(cm, false /** inclusive */, true /** forward */, false /** bigWord */, true /** noSymbol */); var isKeyword = true; if (!word) { word = expandWordUnderCursor(cm, false /** inclusive */, true /** forward */, false /** bigWord */, false /** noSymbol */); isKeyword = false; } if (!word) { return; } var query = cm.getLine(word.start.line).substring(word.start.ch, word.end.ch); if (isKeyword) { query = '\\b' + query + '\\b'; } else { query = escapeRegex(query); } // cachedCursor is used to save the old position of the cursor // when * or # causes vim to seek for the nearest word and shift // the cursor before entering the motion. vimGlobalState.jumpList.cachedCursor = cm.getCursor(); cm.setCursor(word.start); handleQuery(query, true /** ignoreCase */, false /** smartCase */); break; } }, processEx: function(cm, vim, command) { function onPromptClose(input) { // Give the prompt some time to close so that if processCommand shows // an error, the elements don't overlap. exCommandDispatcher.processCommand(cm, input); } function onPromptKeyDown(e, _input, close) { var keyName = CodeMirror.keyName(e); if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') { CodeMirror.e_stop(e); close(); cm.focus(); } } if (command.type == 'keyToEx') { // Handle user defined Ex to Ex mappings exCommandDispatcher.processCommand(cm, command.exArgs.input); } else { if (vim.visualMode) { showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>', onKeyDown: onPromptKeyDown}); } else { showPrompt(cm, { onClose: onPromptClose, prefix: ':', onKeyDown: onPromptKeyDown}); } } }, 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 (operator) { this.recordLastEdit(vim, inputState); } if (inputState.repeatOverride !== undefined) { // If repeatOverride is specified, that takes precedence over the // input state's repeat. Used by Ex mode and can be user defined. repeat = inputState.repeatOverride; } else { repeat = inputState.getRepeat(); } if (repeat > 0 && motionArgs.explicitRepeat) { motionArgs.repeatIsExplicit = true; } else if (motionArgs.noRepeat || (!motionArgs.explicitRepeat && repeat === 0)) { repeat = 1; motionArgs.repeatIsExplicit = false; } if (inputState.selectedCharacter) { // If there is a character input, stick it in all of the arg arrays. motionArgs.selectedCharacter = operatorArgs.selectedCharacter = inputState.selectedCharacter; } motionArgs.repeat = repeat; vim.inputState = new InputState(); if (motion) { var motionResult = motions[motion](cm, motionArgs, vim); vim.lastMotion = motions[motion]; if (!motionResult) { return; } if (motionArgs.toJumplist) { var jumpList = vimGlobalState.jumpList; // if the current motion is # or *, use cachedCursor var cachedCursor = jumpList.cachedCursor; if (cachedCursor) { recordJumpPosition(cm, cachedCursor, motionResult); delete jumpList.cachedCursor; } else { recordJumpPosition(cm, curOriginal, motionResult); } } 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; var lastLine = cm.lastLine(); if (selectionEnd.line > lastLine) { selectionEnd.line = lastLine; } 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 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); } } }, recordLastEdit: function(vim, inputState, actionCommand) { var macroModeState = vimGlobalState.macroModeState; if (macroModeState.inReplay) { return; } vim.lastEditInputState = inputState; vim.lastEditActionCommand = actionCommand; macroModeState.lastInsertModeChanges.changes = []; macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false; } }; /** * typedef {Object{line:number,ch:number}} Cursor An object containing the * position of the cursor. */ // All of the functions below return Cursor objects. var motions = { moveToTopLine: function(cm, motionArgs) { var line = getUserVisibleLines(cm).top + motionArgs.repeat -1; return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) }; }, moveToMiddleLine: function(cm) { var range = getUserVisibleLines(cm); var line = Math.floor((range.top + range.bottom) * 0.5); return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) }; }, moveToBottomLine: function(cm, motionArgs) { var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1; return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) }; }, 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) { var state = getSearchState(cm); var query = state.getQuery(); if (!query) { return; } var prev = !motionArgs.forward; // If search is initiated with ? instead of /, negate direction. prev = (state.isReversed()) ? !prev : prev; highlightSearchMatches(cm, query); return findNext(cm, prev/** prev */, query, motionArgs.repeat); }, goToMark: function(_cm, motionArgs, vim) { var mark = vim.marks[motionArgs.selectedCharacter]; if (mark) { return mark.find(); } return null; }, jumpToMark: function(cm, motionArgs, vim) { var best = cm.getCursor(); for (var i = 0; i < motionArgs.repeat; i++) { var cursor = best; for (var key in vim.marks) { if (!isLowerCase(key)) { continue; } var mark = vim.marks[key].find(); var isWrongDirection = (motionArgs.forward) ? cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark); if (isWrongDirection) { continue; } if (motionArgs.linewise && (mark.line == cursor.line)) { continue; } var equal = cursorEqual(cursor, best); var between = (motionArgs.forward) ? cusrorIsBetween(cursor, mark, best) : cusrorIsBetween(best, mark, cursor); if (equal || between) { best = mark; } } } if (motionArgs.linewise) { // Vim places the cursor on the first non-whitespace character of // the line if there is one, else it places the cursor at the end // of the line, regardless of whether a mark was found. best.ch = findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)); } return best; }, 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.moveByScroll: case this.moveToColumn: case this.moveToEol: endCh = vim.lastHPos; break; default: vim.lastHPos = endCh; } var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0); var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat; var first = cm.firstLine(); var last = cm.lastLine(); // Vim cancels linewise motions that start on an edge and move beyond // that edge. It does not cancel motions that do not start on an edge. if ((line < first && cur.line == first) || (line > last && cur.line == last)) { return; } if(motionArgs.toFirstChar){ endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line)); vim.lastHPos = endCh; } 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.moveByScroll: case this.moveByLines: case this.moveToColumn: case this.moveToEol: break; default: vim.lastHSPos = cm.charCoords(cur,'div').left; } var repeat = motionArgs.repeat; var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos); if (res.hitSide) { if (motionArgs.forward) { var lastCharCoords = cm.charCoords(res, 'div'); var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos }; var res = cm.coordsChar(goalCoords, 'div'); } else { var resCoords = cm.charCoords({ line: cm.firstLine(), ch: 0}, 'div'); resCoords.left = vim.lastHSPos; res = cm.coordsChar(resCoords, 'div'); } } 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 }; }, moveByScroll: function(cm, motionArgs, vim) { var scrollbox = cm.getScrollInfo(); var curEnd = null; var repeat = motionArgs.repeat; if (!repeat) { repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight()); } var orig = cm.charCoords(cm.getCursor(), 'local'); motionArgs.repeat = repeat; var curEnd = motions.moveByDisplayLines(cm, motionArgs, vim); if (!curEnd) { return null; } var dest = cm.charCoords(curEnd, 'local'); cm.scrollTo(null, scrollbox.top + dest.top - orig.top); return curEnd; }, moveByWords: function(cm, 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; recordLastCharacterSearch(increment, motionArgs); if(!curEnd)return cm.getCursor(); curEnd.ch += increment; return curEnd; }, moveToCharacter: function(cm, motionArgs) { var repeat = motionArgs.repeat; recordLastCharacterSearch(0, motionArgs); return moveToCharacter(cm, repeat, motionArgs.forward, motionArgs.selectedCharacter) || cm.getCursor(); }, moveToSymbol: function(cm, motionArgs) { var repeat = motionArgs.repeat; return findSymbol(cm, repeat, motionArgs.forward, motionArgs.selectedCharacter) || cm.getCursor(); }, 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(); return { line: cursor.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)) }; }, moveToMatchedSymbol: function(cm) { var cursor = cm.getCursor(); var line = cursor.line; var ch = cursor.ch; var lineText = cm.getLine(line); var symbol; var startContext = cm.getTokenAt(cursor).type; var startCtxLevel = getContextLevel(startContext); do { symbol = lineText.charAt(ch++); if (symbol && isMatchableSymbol(symbol)) { var endContext = cm.getTokenAt({line:line, ch:ch}).type; var endCtxLevel = getContextLevel(endContext); if (startCtxLevel >= endCtxLevel) { break; } } } while (symbol); if (symbol) { return findMatchedSymbol(cm, {line:line, ch:ch-1}, 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]; }, repeatLastCharacterSearch: function(cm, motionArgs) { var lastSearch = vimGlobalState.lastChararacterSearch; var repeat = motionArgs.repeat; var forward = motionArgs.forward === lastSearch.forward; var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1); cm.moveH(-increment, 'char'); motionArgs.inclusive = forward ? true : false; var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter); if (!curEnd) { cm.moveH(increment, 'char'); return cm.getCursor(); } curEnd.ch += increment; return curEnd; } }; var operators = { change: function(cm, operatorArgs, _vim, curStart, curEnd) { vimGlobalState.registerController.pushText( operatorArgs.registerName, 'change', cm.getRange(curStart, curEnd), operatorArgs.linewise); if (operatorArgs.linewise) { // Push the next line back down, if there is a next line. var replacement = curEnd.line > cm.lastLine() ? '' : '\n'; cm.replaceRange(replacement, curStart, curEnd); cm.indentLine(curStart.line, 'smart'); // null ch so setCursor moves to end of line. curStart.ch = null; } else { // Exclude trailing whitespace if the range is not all whitespace. var text = cm.getRange(curStart, curEnd); if (!isWhiteSpaceString(text)) { var match = (/\s+$/).exec(text); if (match) { curEnd = offsetCursor(curEnd, 0, - match[0].length); } } cm.replaceRange('', curStart, curEnd); } actions.enterInsertMode(cm, {}, cm.state.vim); cm.setCursor(curStart); }, // delete is a javascript keyword. 'delete': function(cm, operatorArgs, _vim, curStart, curEnd) { // If the ending line is past the last line, inclusive, instead of // including the trailing \n, include the \n before the starting line if (operatorArgs.linewise && curEnd.line > cm.lastLine() && curStart.line > cm.firstLine()) { curStart.line--; curStart.ch = lineLength(cm, curStart.line); } vimGlobalState.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); if (!operatorArgs.shouldMoveCursor) { cm.setCursor(curOriginal); } }, yank: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) { vimGlobalState.registerController.pushText( operatorArgs.registerName, 'yank', cm.getRange(curStart, curEnd), operatorArgs.linewise); cm.setCursor(curOriginal); } }; var actions = { jumpListWalk: function(cm, actionArgs, vim) { if (vim.visualMode) { return; } var repeat = actionArgs.repeat; var forward = actionArgs.forward; var jumpList = vimGlobalState.jumpList; var mark = jumpList.move(cm, forward ? repeat : -repeat); var markPos = mark ? mark.find() : undefined; markPos = markPos ? markPos : cm.getCursor(); cm.setCursor(markPos); }, scrollToCursor: function(cm, actionArgs) { var lineNum = cm.getCursor().line; var charCoords = cm.charCoords({line: lineNum, ch: 0}, 'local'); var height = cm.getScrollInfo().clientHeight; var y = charCoords.top; var lineHeight = charCoords.bottom - y; switch (actionArgs.position) { case 'center': y = y - (height / 2) + lineHeight; break; case 'bottom': y = y - height + lineHeight*1.4; break; case 'top': y = y + lineHeight*0.4; break; } cm.scrollTo(null, y); }, replayMacro: function(cm, actionArgs) { var registerName = actionArgs.selectedCharacter; var repeat = actionArgs.repeat; var macroModeState = vimGlobalState.macroModeState; if (registerName == '@') { registerName = macroModeState.latestRegister; } var keyBuffer = parseRegisterToKeyBuffer(macroModeState, registerName); while(repeat--){ executeMacroKeyBuffer(cm, macroModeState, keyBuffer); } }, exitMacroRecordMode: function() { var macroModeState = vimGlobalState.macroModeState; macroModeState.toggle(); parseKeyBufferToRegister(macroModeState.latestRegister, macroModeState.macroKeyBuffer); }, enterMacroRecordMode: function(cm, actionArgs) { var macroModeState = vimGlobalState.macroModeState; var registerName = actionArgs.selectedCharacter; macroModeState.toggle(cm, registerName); emptyMacroKeyBuffer(macroModeState); }, enterInsertMode: function(cm, actionArgs, vim) { if (cm.getOption('readOnly')) { return; } vim.insertMode = true; vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1; var insertAt = (actionArgs) ? actionArgs.insertAt : null; 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)); } else if (insertAt == 'firstNonBlank') { cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm)); } cm.setOption('keyMap', 'vim-insert'); if (actionArgs && actionArgs.replace) { // Handle Replace-mode as a special case of insert mode. cm.toggleOverwrite(true); cm.setOption('keyMap', 'vim-replace'); CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"}); } else { cm.setOption('keyMap', 'vim-insert'); CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"}); } if (!vimGlobalState.macroModeState.inReplay) { // Only record if not replaying. cm.on('change', onChange); cm.on('cursorActivity', onCursorActivity); CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown); } }, 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) { cm.on('mousedown', exitVisualMode); 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); } CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : ""}); } 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); CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: "linewise"}); } 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; CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"}); } else { exitVisualMode(cm); } } 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, vim) { vim.insertMode = true; 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, { repeat: actionArgs.repeat }, vim); }, paste: function(cm, actionArgs) { var cur = cm.getCursor(); var register = vimGlobalState.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) { cm.operation(function() { repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)(); cm.setCursor(cm.getCursor('anchor')); }); }, redo: function(cm, actionArgs) { repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)(); }, setRegister: function(_cm, actionArgs, vim) { vim.inputState.registerName = actionArgs.selectedCharacter; }, setMark: function(cm, actionArgs, vim) { var markName = actionArgs.selectedCharacter; updateMark(cm, vim, markName, cm.getCursor()); }, replace: function(cm, actionArgs, vim) { var replaceWith = actionArgs.selectedCharacter; var curStart = cm.getCursor(); var replaceTo; var curEnd; if(vim.visualMode){ curStart=cm.getCursor('start'); curEnd=cm.getCursor('end'); // workaround to catch the character under the cursor // existing workaround doesn't cover actions curEnd=cm.clipPos({line: curEnd.line, ch: curEnd.ch+1}); }else{ var line = cm.getLine(curStart.line); replaceTo = curStart.ch + actionArgs.repeat; if (replaceTo > line.length) { replaceTo=line.length; } curEnd = { line: curStart.line, ch: replaceTo }; } if(replaceWith=='\n'){ if(!vim.visualMode) cm.replaceRange('', curStart, curEnd); // special case, where vim help says to replace by just one line-break (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm); }else { var replaceWithStr=cm.getRange(curStart, curEnd); //replace all characters in range by selected, but keep linebreaks replaceWithStr=replaceWithStr.replace(/[^\n]/g,replaceWith); cm.replaceRange(replaceWithStr, curStart, curEnd); if(vim.visualMode){ cm.setCursor(curStart); exitVisualMode(cm); }else{ cm.setCursor(offsetCursor(curEnd, 0, -1)); } } }, incrementNumberToken: function(cm, actionArgs) { var cur = cm.getCursor(); var lineStr = cm.getLine(cur.line); var re = /-?\d+/g; var match; var start; var end; var numberStr; var token; while ((match = re.exec(lineStr)) !== null) { token = match[0]; start = match.index; end = start + token.length; if(cur.ch < end)break; } if(!actionArgs.backtrack && (end <= cur.ch))return; if (token) { var increment = actionArgs.increase ? 1 : -1; var number = parseInt(token) + (increment * actionArgs.repeat); var from = {ch:start, line:cur.line}; var to = {ch:end, line:cur.line}; numberStr = number.toString(); cm.replaceRange(numberStr, from, to); } else { return; } cm.setCursor({line: cur.line, ch: start + numberStr.length - 1}); }, repeatLastEdit: function(cm, actionArgs, vim) { var lastEditInputState = vim.lastEditInputState; if (!lastEditInputState) { return; } var repeat = actionArgs.repeat; if (repeat && actionArgs.repeatIsExplicit) { vim.lastEditInputState.repeatOverride = repeat; } else { repeat = vim.lastEditInputState.repeatOverride || repeat; } repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */); } }; 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 }; } 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 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 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; } if (cur1.line == cur2.line && cur1.ch < cur2.ch) { return true; } return false; } function cusrorIsBetween(cur1, cur2, cur3) { // returns true if cur2 is between cur1 and cur3. var cur1before2 = cursorIsBefore(cur1, cur2); var cur2before3 = cursorIsBefore(cur2, cur3); return cur1before2 && cur2before3; } function lineLength(cm, lineNum) { return cm.getLine(lineNum).length; } function reverse(s){ return s.split('').reverse().join(''); } function trim(s) { if (s.trim) { return s.trim(); } return s.replace(/^\s+|\s+$/g, ''); } function escapeRegex(s) { return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1'); } function exitVisualMode(cm) { cm.off('mousedown', exitVisualMode); var vim = cm.state.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)); } CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); } // Remove any trailing newlines from the selection. For // example, with the caret at the start of the last word on the line, // 'dw' should word, but not the newline, while 'w' should advance the // caret to the first character of the next line. function clipToLine(cm, curStart, curEnd) { var selection = cm.getRange(curStart, curEnd); // Only clip if the selection ends with trailing newline + whitespace if (/\n\s*$/.test(selection)) { var lines = selection.split('\n'); // We know this is all whitepsace. lines.pop(); // Cases: // 1. Last word is an empty line - do not clip the trailing '\n' // 2. Last word is not an empty line - clip the trailing '\n' var line; // Find the line containing the last word, and clip all whitespace up // to it. for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) { curEnd.line--; curEnd.ch = 0; } // If the last word is not an empty line, clip an additional newline if (line) { curEnd.line--; curEnd.ch = lineLength(cm, curEnd.line); } else { curEnd.ch = 0; } } } // Expand the selection to line ends. function expandSelectionToLine(_cm, curStart, curEnd) { curStart.ch = 0; curEnd.ch = 0; curEnd.line++; } function findFirstNonWhiteSpaceCharacter(text) { if (!text) { return 0; } var firstNonWS = text.search(/\S/); return firstNonWS == -1 ? text.length : firstNonWS; } function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) { var cur = 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; // TODO: Find a better way to do this. It will be slow on very long lines. var revTextBeforeIdx = reverse(textBeforeIdx); var wordBeforeRegex = matchRegex.exec(revTextBeforeIdx); if (wordBeforeRegex) { wordStart -= wordBeforeRegex[0].length; } if (inclusive) { // If present, trim all whitespace after word. // Otherwise, trim all whitespace before word. var textAfterWordEnd = line.substring(wordEnd); var whitespacesAfterWord = textAfterWordEnd.match(/^\s*/)[0].length; if (whitespacesAfterWord > 0) { wordEnd += whitespacesAfterWord; } else { var revTrim = revTextBeforeIdx.length - wordStart; var textBeforeWordStart = revTextBeforeIdx.substring(revTrim); var whitespacesBeforeWord = textBeforeWordStart.match(/^\s*/)[0].length; wordStart -= whitespacesBeforeWord; } } return { start: { line: cur.line, ch: wordStart }, end: { line: cur.line, ch: wordEnd }}; } function recordJumpPosition(cm, oldCur, newCur) { if(!cursorEqual(oldCur, newCur)) { vimGlobalState.jumpList.add(cm, oldCur, newCur); } } function recordLastCharacterSearch(increment, args) { vimGlobalState.lastChararacterSearch.increment = increment; vimGlobalState.lastChararacterSearch.forward = args.forward; vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter; } var symbolToMode = { '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket', '[': 'section', ']': 'section', '*': 'comment', '/': 'comment', 'm': 'method', 'M': 'method', '#': 'preprocess' }; var findSymbolModes = { bracket: { isComplete: function(state) { if (state.nextCh === state.symb) { state.depth++; if(state.depth >= 1)return true; } else if (state.nextCh === state.reverseSymb) { state.depth--; } return false; } }, section: { init: function(state) { state.curMoveThrough = true; state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}'; }, isComplete: function(state) { return state.index === 0 && state.nextCh === state.symb; } }, comment: { isComplete: function(state) { var found = state.lastCh === '*' && state.nextCh === '/'; state.lastCh = state.nextCh; return found; } }, // TODO: The original Vim implementation only operates on level 1 and 2. // The current implementation doesn't check for code block level and // therefore it operates on any levels. method: { init: function(state) { state.symb = (state.symb === 'm' ? '{' : '}'); state.reverseSymb = state.symb === '{' ? '}' : '{'; }, isComplete: function(state) { if(state.nextCh === state.symb)return true; return false; } }, preprocess: { init: function(state) { state.index = 0; }, isComplete: function(state) { if (state.nextCh === '#') { var token = state.lineText.match(/#(\w+)/)[1]; if (token === 'endif') { if (state.forward && state.depth === 0) { return true; } state.depth++; } else if (token === 'if') { if (!state.forward && state.depth === 0) { return true; } state.depth--; } if(token === 'else' && state.depth === 0)return true; } return false; } } }; function findSymbol(cm, repeat, forward, symb) { var cur = cm.getCursor(); var increment = forward ? 1 : -1; var endLine = forward ? cm.lineCount() : -1; var curCh = cur.ch; var line = cur.line; var lineText = cm.getLine(line); var state = { lineText: lineText, nextCh: lineText.charAt(curCh), lastCh: null, index: curCh, symb: symb, reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb], forward: forward, depth: 0, curMoveThrough: false }; var mode = symbolToMode[symb]; if(!mode)return cur; var init = findSymbolModes[mode].init; var isComplete = findSymbolModes[mode].isComplete; if(init)init(state); while (line !== endLine && repeat) { state.index += increment; state.nextCh = state.lineText.charAt(state.index); if (!state.nextCh) { line += increment; state.lineText = cm.getLine(line) || ''; if (increment > 0) { state.index = 0; } else { var lineLen = state.lineText.length; state.index = (lineLen > 0) ? (lineLen-1) : 0; } state.nextCh = state.lineText.charAt(state.index); } if (isComplete(state)) { cur.line = line; cur.ch = state.index; repeat--; } } if (state.nextCh || state.curMoveThrough) { return { line: line, ch: state.index }; } return cur; } /* * Returns the boundaries of the next word. If the cursor in the middle of * the word, then returns the boundaries of the current word, starting at * the cursor. If the cursor is at the start/end of a word, and we are going * forward/backward, respectively, find the boundaries of the next word. * * @param {CodeMirror} cm CodeMirror object. * @param {Cursor} cur The cursor position. * @param {boolean} forward True to search forward. False to search * backward. * @param {boolean} bigWord True if punctuation count as part of the word. * False if only [a-zA-Z0-9] characters count as part of the word. * @param {boolean} emptyLineIsWord True if empty lines should be treated * as words. * @return {Object{from:number, to:number, line: number}} The boundaries of * the word, or null if there are no more words. */ function findWord(cm, cur, forward, bigWord, emptyLineIsWord) { var lineNum = cur.line; var pos = cur.ch; var line = cm.getLine(lineNum); var dir = forward ? 1 : -1; var regexps = bigWord ? bigWordRegexp : wordRegexp; if (emptyLineIsWord && line == '') { lineNum += dir; line = cm.getLine(lineNum); if (!isLine(cm, lineNum)) { return null; } pos = (forward) ? 0 : line.length; } while (true) { if (emptyLineIsWord && line == '') { return { from: 0, to: 0, line: lineNum }; } var stop = (dir > 0) ? line.length : -1; var wordStart = stop, wordEnd = stop; // Find bounds of next word. while (pos != stop) { var foundWord = false; for (var i = 0; i < 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 new Error('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(); var curStart = copyCursor(cur); var words = []; if (forward && !wordEnd || !forward && wordEnd) { repeat++; } // For 'e', empty lines are not considered words, go figure. var emptyLineIsWord = !(forward && wordEnd); for (var i = 0; i < repeat; i++) { var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord); if (!word) { var eodCh = lineLength(cm, cm.lastLine()); words.push(forward ? {line: cm.lastLine(), from: eodCh, to: eodCh} : {line: 0, from: 0, to: 0}); break; } words.push(word); cur = {line: word.line, ch: forward ? (word.to - 1) : word.from}; } var shortCircuit = words.length != repeat; var firstWord = words[0]; var lastWord = words.pop(); if (forward && !wordEnd) { // w if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) { // We did not start in the middle of a word. Discard the extra word at the end. lastWord = words.pop(); } return {line: lastWord.line, ch: lastWord.from}; } else if (forward && wordEnd) { return {line: lastWord.line, ch: lastWord.to - 1}; } else if (!forward && wordEnd) { // ge if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) { // We did not start in the middle of a word. Discard the extra word at the end. lastWord = words.pop(); } return {line: lastWord.line, ch: lastWord.to}; } else { // b return {line: lastWord.line, ch: lastWord.from}; } } function moveToCharacter(cm, repeat, forward, character) { var cur = cm.getCursor(); var start = cur.ch; var idx; for (var i = 0; i < repeat; i ++) { var line = cm.getLine(cur.line); idx = charIdxInLine(start, line, character, forward, true); if (idx == -1) { return null; } start = idx; } return { 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 getContextLevel(ctx) { return (ctx === 'string' || ctx === 'comment') ? 1 : 0; } function findMatchedSymbol(cm, cur, symb) { var line = cur.line; var ch = cur.ch; symb = symb ? symb : cm.getLine(line).charAt(ch); var symbContext = cm.getTokenAt({line:line, ch:ch+1}).type; var symbCtxLevel = getContextLevel(symbContext); 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 endLine = increment === 1 ? cm.lineCount() : -1; var depth = 1, nextCh = symb, index = 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 (line !== endLine && 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); } var revSymbContext = cm.getTokenAt({line:line, ch:index+1}).type; var revSymbCtxLevel = getContextLevel(revSymbContext); if (symbCtxLevel >= revSymbCtxLevel) { 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 }; } // 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() {} SearchState.prototype = { getQuery: function() { return vimGlobalState.query; }, setQuery: function(query) { vimGlobalState.query = query; }, getOverlay: function() { return this.searchOverlay; }, setOverlay: function(overlay) { this.searchOverlay = overlay; }, isReversed: function() { return vimGlobalState.isReversed; }, setReversed: function(reversed) { vimGlobalState.isReversed = reversed; } }; function getSearchState(cm) { var vim = cm.state.vim; return vim.searchState_ || (vim.searchState_ = new SearchState()); } function dialog(cm, template, shortText, onClose, options) { if (cm.openDialog) { cm.openDialog(template, onClose, { bottom: true, value: options.value, onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp }); } else { onClose(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(query, ignoreCase, smartCase) { // Check if the query is already a regex. if (query instanceof RegExp) { return query; } // First try to extract regex + flags from the input. If no flags found, // extract just the regex. IE does not accept flags directly defined in // the regex string in the form /regex/flags var slashes = findUnescapedSlashes(query); var regexPart; var forceIgnoreCase; if (!slashes.length) { // Query looks like 'regexp' regexPart = query; } else { // Query looks like 'regexp/...' regexPart = query.substring(0, slashes[0]); var flagsPart = query.substring(slashes[0]); forceIgnoreCase = (flagsPart.indexOf('i') != -1); } if (!regexPart) { return null; } if (smartCase) { ignoreCase = (/^[^A-Z]*$/).test(regexPart); } var regexp = new RegExp(regexPart, (ignoreCase || forceIgnoreCase) ? 'i' : undefined); return regexp; } 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, options) { var shortText = (options.prefix || '') + ' ' + (options.desc || ''); var prompt = makePrompt(options.prefix, options.desc); dialog(cm, prompt, shortText, options.onClose, options); } function regexEqual(r1, r2) { if (r1 instanceof RegExp && r2 instanceof RegExp) { var props = ['global', 'multiline', 'ignoreCase', 'source']; for (var i = 0; i < props.length; i++) { var prop = props[i]; if (r1[prop] !== r2[prop]) { return false; } } return true; } return false; } // Returns true if the query is valid. function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) { if (!rawQuery) { return; } var state = getSearchState(cm); var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase); if (!query) { return; } highlightSearchMatches(cm, query); if (regexEqual(query, state.getQuery())) { return query; } state.setQuery(query); return query; } function searchOverlay(query) { if (query.source.charAt(0) == '^') { var matchSol = true; } return { token: function(stream) { if (matchSol && !stream.sol()) { stream.skipToEnd(); return; } var match = stream.match(query, false); if (match) { if (match[0].length == 0) { // Matched empty string, skip to next. stream.next(); return 'searching'; } if (!stream.sol()) { // Backtrack 1 to match \b stream.backUp(1); if (!query.exec(stream.next() + match[0])) { stream.next(); return null; } } stream.match(query); return 'searching'; } while (!stream.eol()) { stream.next(); if (stream.match(query, false)) break; } }, query: query }; } function highlightSearchMatches(cm, query) { var overlay = getSearchState(cm).getOverlay(); if (!overlay || query != overlay.query) { if (overlay) { cm.removeOverlay(overlay); } overlay = searchOverlay(query); cm.addOverlay(overlay); getSearchState(cm).setOverlay(overlay); } } function findNext(cm, prev, query, repeat) { if (repeat === undefined) { repeat = 1; } return cm.operation(function() { var pos = cm.getCursor(); var cursor = cm.getSearchCursor(query, pos); for (var i = 0; i < repeat; i++) { var found = cursor.find(prev); if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); } if (!found) { // SearchCursor may have returned null because it hit EOF, wrap // around and try again. cursor = cm.getSearchCursor(query, (prev) ? { line: cm.lastLine() } : {line: cm.firstLine(), ch: 0} ); if (!cursor.find(prev)) { return; } } } return cursor.from(); }); } function clearSearchHighlight(cm) { cm.removeOverlay(getSearchState(cm).getOverlay()); getSearchState(cm).setOverlay(null); } /** * Check if pos is in the specified range, INCLUSIVE. * Range can be specified with 1 or 2 arguments. * If the first range argument is an array, treat it as an array of line * numbers. Match pos against any of the lines. * If the first range argument is a number, * if there is only 1 range argument, check if pos has the same line * number * if there are 2 range arguments, then check if pos is in between the two * range arguments. */ function isInRange(pos, start, end) { if (typeof pos != 'number') { // Assume it is a cursor position. Get the line number. pos = pos.line; } if (start instanceof Array) { return inArray(pos, start); } else { if (end) { return (pos >= start && pos <= end); } else { return pos == start; } } } function getUserVisibleLines(cm) { var scrollInfo = cm.getScrollInfo(); var occludeToleranceTop = 6; var occludeToleranceBottom = 10; var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local'); var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top; var to = cm.coordsChar({left:0, top: bottomY}, 'local'); return {top: from.line, bottom: to.line}; } // 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: 'sort', shortName: 'sor', type: 'builtIn'}, { name: 'substitute', shortName: 's', type: 'builtIn'}, { name: 'nohlsearch', shortName: 'noh', type: 'builtIn'}, { name: 'delmarks', shortName: 'delm', type: 'builtin'} ]; Vim.ExCommandDispatcher = function() { this.buildCommandMap_(); }; Vim.ExCommandDispatcher.prototype = { processCommand: function(cm, input) { var vim = cm.state.vim; if (vim.visualMode) { exitVisualMode(cm); } 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++) { CodeMirror.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; } try { exCommands[commandName](cm, params); } catch(e) { showConfirm(cm, e); } }, parseInput_: function(cm, inputStream, result) { inputStream.eatWhile(':'); // Parse range. if (inputStream.eat('%')) { result.line = cm.firstLine(); result.lineEnd = cm.lastLine(); } else { result.line = this.parseLineSpec_(cm, inputStream); if (result.line !== undefined && inputStream.eat(',')) { result.lineEnd = this.parseLineSpec_(cm, inputStream); } } // Parse command name. var commandMatch = inputStream.match(/^(\w+)/); if (commandMatch) { result.commandName = commandMatch[1]; } else { result.commandName = inputStream.match(/.*/)[0]; } return result; }, parseLineSpec_: function(cm, inputStream) { var numberMatch = inputStream.match(/^(\d+)/); if (numberMatch) { return parseInt(numberMatch[1], 10) - 1; } switch (inputStream.next()) { case '.': return cm.getCursor().line; case '$': return cm.lastLine(); case '\'': var mark = cm.state.vim.marks[inputStream.next()]; if (mark && mark.find()) { return mark.find().line; } throw new Error('Mark not set'); default: inputStream.backUp(1); return undefined; } }, 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 key, match; var keys = []; while (str) { match = (/<\w+-.+?>|<\w+>|./).exec(str); if(match === null)break; key = match[0]; str = str.substring(match.index + key.length); keys.push(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.processCommand(cm, cm.state.vim, { type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true }, repeatOverride: params.line+1}); }, sort: function(cm, params) { var reverse, ignoreCase, unique, number; function parseArgs() { if (params.argString) { var args = new CodeMirror.StringStream(params.argString); if (args.eat('!')) { reverse = true; } if (args.eol()) { return; } if (!args.eatSpace()) { throw new Error('invalid arguments ' + args.match(/.*/)[0]); } var opts = args.match(/[a-z]+/); if (opts) { opts = opts[0]; ignoreCase = opts.indexOf('i') != -1; unique = opts.indexOf('u') != -1; var decimal = opts.indexOf('d') != -1 && 1; var hex = opts.indexOf('x') != -1 && 1; var octal = opts.indexOf('o') != -1 && 1; if (decimal + hex + octal > 1) { throw new Error('invalid arguments'); } number = decimal && 'decimal' || hex && 'hex' || octal && 'octal'; } if (args.eatSpace() && args.match(/\/.*\//)) { throw new Error('patterns not supported'); } } } parseArgs(); var lineStart = params.line || cm.firstLine(); var lineEnd = params.lineEnd || params.line || cm.lastLine(); if (lineStart == lineEnd) { return; } var curStart = { line: lineStart, ch: 0 }; var curEnd = { line: lineEnd, ch: lineLength(cm, lineEnd) }; var text = cm.getRange(curStart, curEnd).split('\n'); var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ : (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i : (number == 'octal') ? /([0-7]+)/ : null; var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null; var numPart = [], textPart = []; if (number) { for (var i = 0; i < text.length; i++) { if (numberRegex.exec(text[i])) { numPart.push(text[i]); } else { textPart.push(text[i]); } } } else { textPart = text; } function compareFn(a, b) { if (reverse) { var tmp; tmp = a; a = b; b = tmp; } if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); } var anum = number && numberRegex.exec(a); var bnum = number && numberRegex.exec(b); if (!anum) { return a < b ? -1 : 1; } anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix); bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix); return anum - bnum; } numPart.sort(compareFn); textPart.sort(compareFn); text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart); if (unique) { // Remove duplicate lines var textOld = text; var lastLine; text = []; for (var i = 0; i < textOld.length; i++) { if (textOld[i] != lastLine) { text.push(textOld[i]); } lastLine = textOld[i]; } } cm.replaceRange(text.join('\n'), curStart, curEnd); }, substitute: function(cm, params) { if (!cm.getSearchCursor) { throw new Error('Search feature not available. Requires searchcursor.js or ' + 'any other getSearchCursor implementation.'); } var argString = params.argString; var 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; var confirm = false; // Whether to confirm each replace. 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) { if (flagsPart.indexOf('c') != -1) { confirm = true; flagsPart.replace('c', ''); } regexPart = regexPart + '/' + flagsPart; } if (regexPart) { // If regex part is empty, then use the previous query. Otherwise use // the regex part as the new query. try { updateSearchQuery(cm, regexPart, true /** ignoreCase */, true /** smartCase */); } catch (e) { showConfirm(cm, 'Invalid regex: ' + regexPart); return; } } var state = getSearchState(cm); var query = state.getQuery(); var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line; var lineEnd = params.lineEnd || lineStart; if (count) { lineStart = lineEnd; lineEnd = lineStart + count - 1; } var startPos = clipCursorToContent(cm, { line: lineStart, ch: 0 }); var cursor = cm.getSearchCursor(query, startPos); doReplace(cm, confirm, lineStart, lineEnd, cursor, query, replacePart); }, 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); }, delmarks: function(cm, params) { if (!params.argString || !params.argString.trim()) { showConfirm(cm, 'Argument required'); return; } var state = cm.state.vim; var stream = new CodeMirror.StringStream(params.argString.trim()); while (!stream.eol()) { stream.eatSpace(); // Record the streams position at the beginning of the loop for use // in error messages. var count = stream.pos; if (!stream.match(/[a-zA-Z]/, false)) { showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); return; } var sym = stream.next(); // Check if this symbol is part of a range if (stream.match('-', true)) { // This symbol is part of a range. // The range must terminate at an alphabetic character. if (!stream.match(/[a-zA-Z]/, false)) { showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); return; } var startMark = sym; var finishMark = stream.next(); // The range must terminate at an alphabetic character which // shares the same case as the start of the range. if (isLowerCase(startMark) && isLowerCase(finishMark) || isUpperCase(startMark) && isUpperCase(finishMark)) { var start = startMark.charCodeAt(0); var finish = finishMark.charCodeAt(0); if (start >= finish) { showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); return; } // Because marks are always ASCII values, and we have // determined that they are the same case, we can use // their char codes to iterate through the defined range. for (var j = 0; j <= finish - start; j++) { var mark = String.fromCharCode(start + j); delete state.marks[mark]; } } else { showConfirm(cm, 'Invalid argument: ' + startMark + '-'); return; } } else { // This symbol is a valid mark, and is not part of a range. delete state.marks[sym]; } } } }; var exCommandDispatcher = new Vim.ExCommandDispatcher(); /** * @param {CodeMirror} cm CodeMirror instance we are in. * @param {boolean} confirm Whether to confirm each replace. * @param {Cursor} lineStart Line to start replacing from. * @param {Cursor} lineEnd Line to stop replacing at. * @param {RegExp} query Query for performing matches with. * @param {string} replaceWith Text to replace matches with. May contain $1, * $2, etc for replacing captured groups using Javascript replace. */ function doReplace(cm, confirm, lineStart, lineEnd, searchCursor, query, replaceWith) { // Set up all the functions. cm.state.vim.exMode = true; var done = false; var lastPos = searchCursor.from(); function replaceAll() { cm.operation(function() { while (!done) { replace(); next(); } stop(); }); } function replace() { var text = cm.getRange(searchCursor.from(), searchCursor.to()); var newText = text.replace(query, replaceWith); searchCursor.replace(newText); } function next() { var found = searchCursor.findNext(); if (!found) { done = true; } else if (isInRange(searchCursor.from(), lineStart, lineEnd)) { cm.scrollIntoView(searchCursor.from(), 30); cm.setSelection(searchCursor.from(), searchCursor.to()); lastPos = searchCursor.from(); done = false; } else { done = true; } } function stop(close) { if (close) { close(); } cm.focus(); if (lastPos) { cm.setCursor(lastPos); var vim = cm.state.vim; vim.exMode = false; vim.lastHPos = vim.lastHSPos = lastPos.ch; } } function onPromptKeyDown(e, _value, close) { // Swallow all keys. CodeMirror.e_stop(e); var keyName = CodeMirror.keyName(e); switch (keyName) { case 'Y': replace(); next(); break; case 'N': next(); break; case 'A': cm.operation(replaceAll); break; case 'L': replace(); // fall through and exit. case 'Q': case 'Esc': case 'Ctrl-C': case 'Ctrl-[': stop(close); break; } if (done) { stop(close); } } // Actually do replace. next(); if (done) { throw new Error('No matches for ' + query.source); } if (!confirm) { replaceAll(); return; } showPrompt(cm, { prefix: 'replace with ' + replaceWith + ' (y/n/a/q/l)', onKeyDown: onPromptKeyDown }); } // 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 cmKeyToVimKey(key, modifier) { var vimKey = key; if (isUpperCase(vimKey)) { // 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 { vimKey = vimKey.toLowerCase(); } } if (modifier) { // Vim will parse modifier+key combination as a single key. vimKey = modifier.charAt(0) + '-' + vimKey; } var specialKey = ({Enter:'CR',Backspace:'BS',Delete:'Del'})[vimKey]; vimKey = specialKey ? specialKey : vimKey; vimKey = vimKey.length > 1 ? '<'+ vimKey + '>' : vimKey; return vimKey; } // Closure to bind CodeMirror, key, modifier. function keyMapper(vimKey) { return function(cm) { CodeMirror.Vim.handleKey(cm, vimKey); }; } var cmToVimKeymap = { 'nofallthrough': true, 'disableInput': 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 + "'"; } var vimKey = cmKeyToVimKey(keys[i], modifier); var cmKey = modifier ? modifier + '-' + key : key; cmToVimKeymap[cmKey] = keyMapper(vimKey); } } bindKeys(upperCaseAlphabet); bindKeys(upperCaseAlphabet, 'Shift'); bindKeys(upperCaseAlphabet, 'Ctrl'); bindKeys(specialSymbols); bindKeys(specialSymbols, 'Ctrl'); bindKeys(numbers); bindKeys(numbers, 'Ctrl'); bindKeys(specialKeys); bindKeys(specialKeys, 'Ctrl'); return cmToVimKeymap; } CodeMirror.keyMap.vim = buildVimKeyMap(); function exitInsertMode(cm) { var vim = cm.state.vim; var inReplay = vimGlobalState.macroModeState.inReplay; if (!inReplay) { cm.off('change', onChange); cm.off('cursorActivity', onCursorActivity); CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown); } if (!inReplay && vim.insertModeRepeat > 1) { // Perform insert mode repeat for commands like 3,a and 3,o. repeatLastEdit(cm, vim, vim.insertModeRepeat - 1, true /** repeatForInsert */); vim.lastEditInputState.repeatOverride = vim.insertModeRepeat; } delete vim.insertModeRepeat; cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1, true); vim.insertMode = false; cm.setOption('keyMap', 'vim'); cm.toggleOverwrite(false); // exit replace mode if we were in it. CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); } 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'] }; CodeMirror.keyMap['vim-replace'] = { 'Backspace': 'goCharLeft', fallthrough: ['vim-insert'] }; function parseRegisterToKeyBuffer(macroModeState, registerName) { var match, key; var register = vimGlobalState.registerController.getRegister(registerName); var text = register.toString(); var macroKeyBuffer = macroModeState.macroKeyBuffer; emptyMacroKeyBuffer(macroModeState); do { match = (/<\w+-.+?>|<\w+>|./).exec(text); if(match === null)break; key = match[0]; text = text.substring(match.index + key.length); macroKeyBuffer.push(key); } while (text); return macroKeyBuffer; } function parseKeyBufferToRegister(registerName, keyBuffer) { var text = keyBuffer.join(''); vimGlobalState.registerController.setRegisterText(registerName, text); } function emptyMacroKeyBuffer(macroModeState) { if(macroModeState.isMacroPlaying)return; var macroKeyBuffer = macroModeState.macroKeyBuffer; macroKeyBuffer.length = 0; } function executeMacroKeyBuffer(cm, macroModeState, keyBuffer) { macroModeState.isMacroPlaying = true; for (var i = 0, len = keyBuffer.length; i < len; i++) { CodeMirror.Vim.handleKey(cm, keyBuffer[i]); }; macroModeState.isMacroPlaying = false; } function logKey(macroModeState, key) { if(macroModeState.isMacroPlaying)return; var macroKeyBuffer = macroModeState.macroKeyBuffer; macroKeyBuffer.push(key); } /** * Listens for changes made in insert mode. * Should only be active in insert mode. */ function onChange(_cm, changeObj) { var macroModeState = vimGlobalState.macroModeState; var lastChange = macroModeState.lastInsertModeChanges; while (changeObj) { lastChange.expectCursorActivityForChange = true; if (changeObj.origin == '+input' || changeObj.origin == 'paste' || changeObj.origin === undefined /* only in testing */) { var text = changeObj.text.join('\n'); lastChange.changes.push(text); } // Change objects may be chained with next. changeObj = changeObj.next; } } /** * Listens for any kind of cursor activity on CodeMirror. * - For tracking cursor activity in insert mode. * - Should only be active in insert mode. */ function onCursorActivity() { var macroModeState = vimGlobalState.macroModeState; var lastChange = macroModeState.lastInsertModeChanges; if (lastChange.expectCursorActivityForChange) { lastChange.expectCursorActivityForChange = false; } else { // Cursor moved outside the context of an edit. Reset the change. lastChange.changes = []; } } /** Wrapper for special keys pressed in insert mode */ function InsertModeKey(keyName) { this.keyName = keyName; } /** * Handles raw key down events from the text area. * - Should only be active in insert mode. * - For recording deletes in insert mode. */ function onKeyEventTargetKeyDown(e) { var macroModeState = vimGlobalState.macroModeState; var lastChange = macroModeState.lastInsertModeChanges; var keyName = CodeMirror.keyName(e); function onKeyFound() { lastChange.changes.push(new InsertModeKey(keyName)); return true; } if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) { CodeMirror.lookupKey(keyName, ['vim-insert'], onKeyFound); } } /** * Repeats the last edit, which includes exactly 1 command and at most 1 * insert. Operator and motion commands are read from lastEditInputState, * while action commands are read from lastEditActionCommand. * * If repeatForInsert is true, then the function was called by * exitInsertMode to repeat the insert mode changes the user just made. The * corresponding enterInsertMode call was made with a count. */ function repeatLastEdit(cm, vim, repeat, repeatForInsert) { var macroModeState = vimGlobalState.macroModeState; macroModeState.inReplay = true; var isAction = !!vim.lastEditActionCommand; var cachedInputState = vim.inputState; function repeatCommand() { if (isAction) { commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand); } else { commandDispatcher.evalInput(cm, vim); } } function repeatInsert(repeat) { if (macroModeState.lastInsertModeChanges.changes.length > 0) { // For some reason, repeat cw in desktop VIM will does not repeat // insert mode changes. Will conform to that behavior. repeat = !vim.lastEditActionCommand ? 1 : repeat; repeatLastInsertModeChanges(cm, repeat, macroModeState); } } vim.inputState = vim.lastEditInputState; if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) { // o and O repeat have to be interlaced with insert repeats so that the // insertions appear on separate lines instead of the last line. for (var i = 0; i < repeat; i++) { repeatCommand(); repeatInsert(1); } } else { if (!repeatForInsert) { // Hack to get the cursor to end up at the right place. If I is // repeated in insert mode repeat, cursor will be 1 insert // change set left of where it should be. repeatCommand(); } repeatInsert(repeat); } vim.inputState = cachedInputState; if (vim.insertMode && !repeatForInsert) { // Don't exit insert mode twice. If repeatForInsert is set, then we // were called by an exitInsertMode call lower on the stack. exitInsertMode(cm); } macroModeState.inReplay = false; }; function repeatLastInsertModeChanges(cm, repeat, macroModeState) { var lastChange = macroModeState.lastInsertModeChanges; function keyHandler(binding) { if (typeof binding == 'string') { CodeMirror.commands[binding](cm); } else { binding(cm); } return true; } for (var i = 0; i < repeat; i++) { for (var j = 0; j < lastChange.changes.length; j++) { var change = lastChange.changes[j]; if (change instanceof InsertModeKey) { CodeMirror.lookupKey(change.keyName, ['vim-insert'], keyHandler); } else { var cur = cm.getCursor(); cm.replaceRange(change, cur, cur); } } } } resetVimGlobalState(); return vimApi; }; // Initialize Vim and make it available as an API. CodeMirror.Vim = Vim(); } )(); ================================================ FILE: public/packages/codemirror-3.19/lib/codemirror.css ================================================ /* BASICS */ .CodeMirror { /* Set height, width, borders, and global font properties here */ font-family: monospace; height: 300px; } .CodeMirror-scroll { /* Set scrolling behaviour here */ overflow: auto; } /* 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; } /* CURSOR */ .CodeMirror div.CodeMirror-cursor { border-left: 1px solid black; z-index: 3; } /* Shown when moving in bi-directional text */ .CodeMirror div.CodeMirror-secondarycursor { border-left: 1px solid silver; } .CodeMirror.cm-keymap-fat-cursor div.CodeMirror-cursor { width: auto; border: 0; background: #7e7; z-index: 1; } /* Can style cursor different in overwrite (non-insert) mode */ .CodeMirror div.CodeMirror-cursor.CodeMirror-overwrite {} .cm-tab { display: inline-block; } /* DEFAULT THEME */ .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 {color: black;} .cm-s-default .cm-variable-2 {color: #05a;} .cm-s-default .cm-variable-3 {color: #085;} .cm-s-default .cm-property {color: black;} .cm-s-default .cm-operator {color: black;} .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-header {color: blue;} .cm-s-default .cm-quote {color: #090;} .cm-s-default .cm-hr {color: #999;} .cm-s-default .cm-link {color: #00c;} .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-s-default .cm-error {color: #f00;} .cm-invalidchar {color: #f00;} div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} .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 { line-height: 1; position: relative; overflow: hidden; background: white; color: black; } .CodeMirror-scroll { /* 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; padding-right: 30px; height: 100%; outline: none; /* Prevent dragging from highlighting the element */ position: relative; -moz-box-sizing: content-box; box-sizing: content-box; } .CodeMirror-sizer { position: relative; } /* The fake, visible scrollbars. Used to force redraw during scrolling before actuall 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; padding-bottom: 30px; z-index: 3; } .CodeMirror-gutter { white-space: normal; height: 100%; -moz-box-sizing: content-box; box-sizing: content-box; padding-bottom: 30px; margin-bottom: -32px; display: inline-block; /* Hack to make IE7 behave */ *zoom:1; *display:inline; } .CodeMirror-gutter-elt { position: absolute; cursor: default; z-index: 4; } .CodeMirror-lines { cursor: text; } .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; } .CodeMirror-wrap pre { word-wrap: break-word; white-space: pre-wrap; word-break: normal; } .CodeMirror-code pre { border-right: 30px solid transparent; width: -webkit-fit-content; width: -moz-fit-content; width: fit-content; } .CodeMirror-wrap .CodeMirror-code pre { border-right: none; width: auto; } .CodeMirror-linebackground { position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: 0; } .CodeMirror-linewidget { position: relative; z-index: 2; overflow: auto; } .CodeMirror-widget {} .CodeMirror-wrap .CodeMirror-scroll { overflow-x: hidden; } .CodeMirror-measure { position: absolute; width: 100%; height: 0; overflow: hidden; visibility: hidden; } .CodeMirror-measure pre { position: static; } .CodeMirror div.CodeMirror-cursor { position: absolute; visibility: hidden; border-right: none; width: 0; } .CodeMirror-focused div.CodeMirror-cursor { visibility: visible; } .CodeMirror-selected { background: #d9d9d9; } .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } .cm-searching { background: #ffa; background: rgba(255, 255, 0, .4); } /* IE7 hack to prevent it from returning funny offsetTops on the spans */ .CodeMirror span { *vertical-align: text-bottom; } @media print { /* Hide the cursor when printing */ .CodeMirror div.CodeMirror-cursor { visibility: hidden; } } ================================================ FILE: public/packages/codemirror-3.19/lib/codemirror.js ================================================ // CodeMirror version 3.19 // // CodeMirror is the only global var we claim window.CodeMirror = (function() { "use strict"; // BROWSER SNIFFING // Crude, but necessary to handle a number of hard-to-feature-detect // bugs and behavior differences. var gecko = /gecko\/\d/i.test(navigator.userAgent); var ie = /MSIE \d/.test(navigator.userAgent); var ie_lt8 = ie && (document.documentMode == null || document.documentMode < 8); var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9); var webkit = /WebKit\//.test(navigator.userAgent); var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); var chrome = /Chrome\//.test(navigator.userAgent); var opera = /Opera\//.test(navigator.userAgent); var safari = /Apple Computer/.test(navigator.vendor); var khtml = /KHTML\//.test(navigator.userAgent); var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent); var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); var phantom = /PhantomJS/.test(navigator.userAgent); var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); // This is woefully incomplete. Suggestions for alternative methods welcome. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent); var mac = ios || /Mac/.test(navigator.platform); var windows = /win/i.test(navigator.platform); var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/); if (opera_version) opera_version = Number(opera_version[1]); if (opera_version && opera_version >= 15) { opera = false; webkit = true; } // Some browsers use the wrong event properties to signal cmd/ctrl on OS X var flipCtrlCmd = mac && (qtwebkit || opera && (opera_version == null || opera_version < 12.11)); var captureMiddleClick = gecko || (ie && !ie_lt9); // Optimize some code when these features are not used var sawReadOnlySpans = false, sawCollapsedSpans = false; // CONSTRUCTOR function CodeMirror(place, options) { if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); this.options = options = options || {}; // Determine effective options based on given values and defaults. for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt)) options[opt] = defaults[opt]; setGuttersForLineNumbers(options); var docStart = typeof options.value == "string" ? 0 : options.value.first; var display = this.display = makeDisplay(place, docStart); display.wrapper.CodeMirror = this; updateGutters(this); if (options.autofocus && !mobile) focusInput(this); this.state = {keyMaps: [], overlays: [], modeGen: 0, overwrite: false, focused: false, suppressEdits: false, pasteIncoming: false, draggingText: false, highlight: new Delayed()}; themeChanged(this); if (options.lineWrapping) this.display.wrapper.className += " CodeMirror-wrap"; var doc = options.value; if (typeof doc == "string") doc = new Doc(options.value, options.mode); operation(this, attachDoc)(this, doc); // Override magic textarea content restore that IE sometimes does // on our hidden textarea on reload if (ie) setTimeout(bind(resetInput, this, true), 20); registerEventHandlers(this); // IE throws unspecified error in certain cases, when // trying to access activeElement before onload var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { } if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20); else onBlur(this); operation(this, function() { for (var opt in optionHandlers) if (optionHandlers.propertyIsEnumerable(opt)) optionHandlers[opt](this, options[opt], Init); for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); })(); } // DISPLAY CONSTRUCTOR function makeDisplay(place, docStart) { var d = {}; var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none; font-size: 4px;"); if (webkit) input.style.width = "1000px"; else input.setAttribute("wrap", "off"); // if border: 0; -- iOS fails to open keyboard (issue #1287) if (ios) input.style.border = "1px solid black"; input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false"); // Wraps and hides input textarea d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); // The actual fake scrollbars. d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar"); d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar"); d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); // DIVs containing the selection and the actual code d.lineDiv = elt("div", null, "CodeMirror-code"); d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); // Blinky cursor, and element used to ensure cursor fits at the end of a line d.cursor = elt("div", "\u00a0", "CodeMirror-cursor"); // Secondary cursor, shown when on a 'jump' in bi-directional text d.otherCursor = elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"); // Used to measure text size d.measure = elt("div", null, "CodeMirror-measure"); // Wraps everything that needs to exist inside the vertically-padded coordinate system d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor], null, "position: relative; outline: none"); // Moved around its parent to cover visible view d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); // Set to the height of the text, causes scrolling d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;"); // Will contain the gutters, if any d.gutters = elt("div", null, "CodeMirror-gutters"); d.lineGutter = null; // Provides scrolling 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.inputDiv, d.scrollbarH, d.scrollbarV, d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); // Work around IE7 z-index bug if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper); // Needed to hide big blue blinking cursor on Mobile Safari if (ios) input.style.width = "0px"; if (!webkit) d.scroller.draggable = true; // Needed to handle Tab key in KHTML if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; } // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px"; // Current visible range (may be bigger than the view window). d.viewOffset = d.lastSizeC = 0; d.showingFrom = d.showingTo = docStart; // 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; // See readInput and resetInput d.prevInput = ""; // Set to true when a non-horizontal-scrolling widget is added. As // an optimization, widget aligning is skipped when d is false. d.alignWidgets = false; // Flag that indicates whether we currently expect input to appear // (after some event like 'keypress' or 'input') and are polling // intensively. d.pollingFast = false; // Self-resetting timeout for the poller d.poll = new Delayed(); d.cachedCharWidth = d.cachedTextHeight = null; d.measureLineCache = []; d.measureLineCachePos = 0; // Tracks when resetInput has punted to just putting a short // string instead of the (large) selection. d.inaccurateSelection = false; // 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; return d; } // STATE UPDATES // Used to get the editor into a consistent state again when options change. function loadMode(cm) { cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); cm.doc.iter(function(line) { if (line.stateAfter) line.stateAfter = null; if (line.styles) line.styles = null; }); cm.doc.frontier = cm.doc.first; startWorker(cm, 100); cm.state.modeGen++; if (cm.curOp) regChange(cm); } function wrappingChanged(cm) { if (cm.options.lineWrapping) { cm.display.wrapper.className += " CodeMirror-wrap"; cm.display.sizer.style.minWidth = ""; } else { cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", ""); computeMaxLength(cm); } estimateLineHeights(cm); regChange(cm); clearCaches(cm); setTimeout(function(){updateScrollbars(cm);}, 100); } 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; else if (wrapping) return (Math.ceil(line.text.length / perLine) || 1) * th; else return 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); }); } function keyMapChanged(cm) { var map = keyMap[cm.options.keyMap], style = map.style; cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") + (style ? " cm-keymap-" + style : ""); cm.state.disableInput = map.disableInput; } 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); } function guttersChanged(cm) { updateGutters(cm); regChange(cm); setTimeout(function(){alignHorizontally(cm);}, 20); } function updateGutters(cm) { var gutters = cm.display.gutters, specs = cm.options.gutters; removeChildren(gutters); for (var i = 0; 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"; } function lineLength(doc, line) { if (line.height == 0) return 0; var len = line.text.length, merged, cur = line; while (merged = collapsedSpanAtStart(cur)) { var found = merged.find(); cur = getLine(doc, found.from.line); len += found.from.ch - found.to.ch; } cur = line; while (merged = collapsedSpanAtEnd(cur)) { var found = merged.find(); len -= cur.text.length - found.from.ch; cur = getLine(doc, found.to.line); len += cur.text.length - found.to.ch; } return len; } function computeMaxLength(cm) { var d = cm.display, doc = cm.doc; d.maxLine = getLine(doc, doc.first); d.maxLineLength = lineLength(doc, d.maxLine); d.maxLineChanged = true; doc.iter(function(line) { var len = lineLength(doc, line); if (len > d.maxLineLength) { d.maxLineLength = len; d.maxLine = line; } }); } // 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); } } // SCROLLBARS // Re-synchronize the fake scrollbars with the actual size of the // content. Optionally force a scrollTop. function updateScrollbars(cm) { var d = cm.display, docHeight = cm.doc.height; var totalHeight = docHeight + paddingVert(d); d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px"; d.gutters.style.height = Math.max(totalHeight, d.scroller.clientHeight - scrollerCutOff) + "px"; var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight); var needsH = d.scroller.scrollWidth > (d.scroller.clientWidth + 1); var needsV = scrollHeight > (d.scroller.clientHeight + 1); if (needsV) { d.scrollbarV.style.display = "block"; d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0"; d.scrollbarV.firstChild.style.height = (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px"; } else { d.scrollbarV.style.display = ""; d.scrollbarV.firstChild.style.height = "0"; } if (needsH) { d.scrollbarH.style.display = "block"; d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0"; d.scrollbarH.firstChild.style.width = (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px"; } else { d.scrollbarH.style.display = ""; d.scrollbarH.firstChild.style.width = "0"; } if (needsH && needsV) { d.scrollbarFiller.style.display = "block"; d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px"; } else d.scrollbarFiller.style.display = ""; if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { d.gutterFiller.style.display = "block"; d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px"; d.gutterFiller.style.width = d.gutters.offsetWidth + "px"; } else d.gutterFiller.style.display = ""; if (mac_geLion && scrollbarWidth(d.measure) === 0) { d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px"; d.scrollbarV.style.pointerEvents = d.scrollbarH.style.pointerEvents = "none"; } } function visibleLines(display, doc, viewPort) { var top = display.scroller.scrollTop, height = display.wrapper.clientHeight; if (typeof viewPort == "number") top = viewPort; else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;} top = Math.floor(top - paddingTop(display)); var bottom = Math.ceil(top + height); return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)}; } // LINE NUMBERS function alignHorizontally(cm) { var display = cm.display; 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, l = comp + "px"; for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) { for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l; } if (cm.options.fixedGutter) display.gutters.style.left = (comp + gutterW) + "px"; } 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); display.lineNumWidth = display.lineNumInnerWidth + padding; display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; display.lineGutter.style.width = display.lineNumWidth + "px"; return true; } return false; } function lineNumberFor(options, i) { return String(options.lineNumberFormatter(i + options.firstLineNumber)); } function compensateForHScroll(display) { return getRect(display.scroller).left - getRect(display.sizer).left; } // DISPLAY DRAWING function updateDisplay(cm, changes, viewPort, forced) { var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo, updated; var visible = visibleLines(cm.display, cm.doc, viewPort); for (var first = true;; first = false) { var oldWidth = cm.display.scroller.clientWidth; if (!updateDisplayInner(cm, changes, visible, forced)) break; updated = true; changes = []; updateSelection(cm); updateScrollbars(cm); if (first && cm.options.lineWrapping && oldWidth != cm.display.scroller.clientWidth) { forced = true; continue; } forced = false; // Clip forced viewport to actual scrollable area if (viewPort) viewPort = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, typeof viewPort == "number" ? viewPort : viewPort.top); visible = visibleLines(cm.display, cm.doc, viewPort); if (visible.from >= cm.display.showingFrom && visible.to <= cm.display.showingTo) break; } if (updated) { signalLater(cm, "update", cm); if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo) signalLater(cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo); } return updated; } // Uses a set of changes plus the current scroll position to // determine which DOM updates have to be made, and makes the // updates. function updateDisplayInner(cm, changes, visible, forced) { var display = cm.display, doc = cm.doc; if (!display.wrapper.clientWidth) { display.showingFrom = display.showingTo = doc.first; display.viewOffset = 0; return; } // Bail out if the visible area is already rendered and nothing changed. if (!forced && changes.length == 0 && visible.from > display.showingFrom && visible.to < display.showingTo) return; if (maybeUpdateLineNumberWidth(cm)) changes = [{from: doc.first, to: doc.first + doc.size}]; var gutterW = display.sizer.style.marginLeft = display.gutters.offsetWidth + "px"; display.scrollbarH.style.left = cm.options.fixedGutter ? gutterW : "0"; // Used to determine which lines need their line numbers updated var positionsChangedFrom = Infinity; if (cm.options.lineNumbers) for (var i = 0; i < changes.length; ++i) if (changes[i].diff && changes[i].from < positionsChangedFrom) { positionsChangedFrom = changes[i].from; } var end = doc.first + doc.size; var from = Math.max(visible.from - cm.options.viewportMargin, doc.first); var to = Math.min(end, visible.to + cm.options.viewportMargin); if (display.showingFrom < from && from - display.showingFrom < 20) from = Math.max(doc.first, display.showingFrom); if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(end, display.showingTo); if (sawCollapsedSpans) { from = lineNo(visualLine(doc, getLine(doc, from))); while (to < end && lineIsHidden(doc, getLine(doc, to))) ++to; } // Create a range of theoretically intact lines, and punch holes // in that using the change info. var intact = [{from: Math.max(display.showingFrom, doc.first), to: Math.min(display.showingTo, end)}]; if (intact[0].from >= intact[0].to) intact = []; else intact = computeIntact(intact, changes); // When merged lines are present, we might have to reduce the // intact ranges because changes in continued fragments of the // intact lines do require the lines to be redrawn. if (sawCollapsedSpans) for (var i = 0; i < intact.length; ++i) { var range = intact[i], merged; while (merged = collapsedSpanAtEnd(getLine(doc, range.to - 1))) { var newTo = merged.find().from.line; if (newTo > range.from) range.to = newTo; else { intact.splice(i--, 1); break; } } } // Clip off the parts that won't be visible var intactLines = 0; for (var i = 0; i < intact.length; ++i) { var range = intact[i]; if (range.from < from) range.from = from; if (range.to > to) range.to = to; if (range.from >= range.to) intact.splice(i--, 1); else intactLines += range.to - range.from; } if (!forced && intactLines == to - from && from == display.showingFrom && to == display.showingTo) { updateViewOffset(cm); return; } intact.sort(function(a, b) {return a.from - b.from;}); // Avoid crashing on IE's "unspecified error" when in iframes try { var focused = document.activeElement; } catch(e) {} if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none"; patchDisplay(cm, from, to, intact, positionsChangedFrom); display.lineDiv.style.display = ""; if (focused && document.activeElement != focused && focused.offsetHeight) focused.focus(); var different = from != display.showingFrom || to != display.showingTo || display.lastSizeC != display.wrapper.clientHeight; // This is just a bogus formula that detects when the editor is // resized or the font size changes. if (different) { display.lastSizeC = display.wrapper.clientHeight; startWorker(cm, 400); } display.showingFrom = from; display.showingTo = to; updateHeightsInViewport(cm); updateViewOffset(cm); return true; } function updateHeightsInViewport(cm) { var display = cm.display; var prevBottom = display.lineDiv.offsetTop; for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) { if (ie_lt8) { var bot = node.offsetTop + node.offsetHeight; height = bot - prevBottom; prevBottom = bot; } else { var box = getRect(node); height = box.bottom - box.top; } var diff = node.lineObj.height - height; if (height < 2) height = textHeight(display); if (diff > .001 || diff < -.001) { updateLineHeight(node.lineObj, height); var widgets = node.lineObj.widgets; if (widgets) for (var i = 0; i < widgets.length; ++i) widgets[i].height = widgets[i].node.offsetHeight; } } } function updateViewOffset(cm) { var off = cm.display.viewOffset = heightAtLine(cm, getLine(cm.doc, cm.display.showingFrom)); // Position the mover div to align with the current virtual scroll position cm.display.mover.style.top = off + "px"; } function computeIntact(intact, changes) { for (var i = 0, l = changes.length || 0; i < l; ++i) { var change = changes[i], intact2 = [], diff = change.diff || 0; for (var j = 0, l2 = intact.length; j < l2; ++j) { var range = intact[j]; if (change.to <= range.from && change.diff) { intact2.push({from: range.from + diff, to: range.to + diff}); } else if (change.to <= range.from || change.from >= range.to) { intact2.push(range); } else { if (change.from > range.from) intact2.push({from: range.from, to: change.from}); if (change.to < range.to) intact2.push({from: change.to + diff, to: range.to + diff}); } } intact = intact2; } return intact; } function getDimensions(cm) { var d = cm.display, left = {}, width = {}; for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { left[cm.options.gutters[i]] = n.offsetLeft; width[cm.options.gutters[i]] = n.offsetWidth; } return {fixedPos: compensateForHScroll(d), gutterTotalWidth: d.gutters.offsetWidth, gutterLeft: left, gutterWidth: width, wrapperWidth: d.wrapper.clientWidth}; } function patchDisplay(cm, from, to, intact, updateNumbersFrom) { var dims = getDimensions(cm); var display = cm.display, lineNumbers = cm.options.lineNumbers; if (!intact.length && (!webkit || !cm.display.currentWheelTarget)) removeChildren(display.lineDiv); var container = display.lineDiv, cur = container.firstChild; function rm(node) { var next = node.nextSibling; if (webkit && mac && cm.display.currentWheelTarget == node) { node.style.display = "none"; node.lineObj = null; } else { node.parentNode.removeChild(node); } return next; } var nextIntact = intact.shift(), lineN = from; cm.doc.iter(from, to, function(line) { if (nextIntact && nextIntact.to == lineN) nextIntact = intact.shift(); if (lineIsHidden(cm.doc, line)) { if (line.height != 0) updateLineHeight(line, 0); if (line.widgets && cur && cur.previousSibling) for (var i = 0; i < line.widgets.length; ++i) { var w = line.widgets[i]; if (w.showIfHidden) { var prev = cur.previousSibling; if (/pre/i.test(prev.nodeName)) { var wrap = elt("div", null, null, "position: relative"); prev.parentNode.replaceChild(wrap, prev); wrap.appendChild(prev); prev = wrap; } var wnode = prev.appendChild(elt("div", [w.node], "CodeMirror-linewidget")); if (!w.handleMouseEvents) wnode.ignoreEvents = true; positionLineWidget(w, wnode, prev, dims); } } } else if (nextIntact && nextIntact.from <= lineN && nextIntact.to > lineN) { // This line is intact. Skip to the actual node. Update its // line number if needed. while (cur.lineObj != line) cur = rm(cur); if (lineNumbers && updateNumbersFrom <= lineN && cur.lineNumber) setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineN)); cur = cur.nextSibling; } else { // For lines with widgets, make an attempt to find and reuse // the existing element, so that widgets aren't needlessly // removed and re-inserted into the dom if (line.widgets) for (var j = 0, search = cur, reuse; search && j < 20; ++j, search = search.nextSibling) if (search.lineObj == line && /div/i.test(search.nodeName)) { reuse = search; break; } // This line needs to be generated. var lineNode = buildLineElement(cm, line, lineN, dims, reuse); if (lineNode != reuse) { container.insertBefore(lineNode, cur); } else { while (cur != reuse) cur = rm(cur); cur = cur.nextSibling; } lineNode.lineObj = line; } ++lineN; }); while (cur) cur = rm(cur); } function buildLineElement(cm, line, lineNo, dims, reuse) { var built = buildLineContent(cm, line), lineElement = built.pre; var markers = line.gutterMarkers, display = cm.display, wrap; var bgClass = built.bgClass ? built.bgClass + " " + (line.bgClass || "") : line.bgClass; if (!cm.options.lineNumbers && !markers && !bgClass && !line.wrapClass && !line.widgets) return lineElement; // Lines with gutter elements, widgets or a background class need // to be wrapped again, and have the extra elements added to the // wrapper div if (reuse) { reuse.alignable = null; var isOk = true, widgetsSeen = 0, insertBefore = null; for (var n = reuse.firstChild, next; n; n = next) { next = n.nextSibling; if (!/\bCodeMirror-linewidget\b/.test(n.className)) { reuse.removeChild(n); } else { for (var i = 0; i < line.widgets.length; ++i) { var widget = line.widgets[i]; if (widget.node == n.firstChild) { if (!widget.above && !insertBefore) insertBefore = n; positionLineWidget(widget, n, reuse, dims); ++widgetsSeen; break; } } if (i == line.widgets.length) { isOk = false; break; } } } reuse.insertBefore(lineElement, insertBefore); if (isOk && widgetsSeen == line.widgets.length) { wrap = reuse; reuse.className = line.wrapClass || ""; } } if (!wrap) { wrap = elt("div", null, line.wrapClass, "position: relative"); wrap.appendChild(lineElement); } // Kludge to make sure the styled element lies behind the selection (by z-index) if (bgClass) wrap.insertBefore(elt("div", null, bgClass + " CodeMirror-linebackground"), wrap.firstChild); if (cm.options.lineNumbers || markers) { var gutterWrap = wrap.insertBefore(elt("div", null, null, "position: absolute; left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"), wrap.firstChild); if (cm.options.fixedGutter) (wrap.alignable || (wrap.alignable = [])).push(gutterWrap); if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) wrap.lineNumber = gutterWrap.appendChild( elt("div", lineNumberFor(cm.options, lineNo), "CodeMirror-linenumber CodeMirror-gutter-elt", "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + 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")); } } if (ie_lt8) wrap.style.zIndex = 2; if (line.widgets && wrap != reuse) 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.ignoreEvents = true; positionLineWidget(widget, node, wrap, dims); if (widget.above) wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement); else wrap.appendChild(node); signalLater(widget, "redraw"); } return wrap; } function positionLineWidget(widget, node, wrap, dims) { if (widget.noHScroll) { (wrap.alignable || (wrap.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"; } } // SELECTION / CURSOR function updateSelection(cm) { var display = cm.display; var collapsed = posEq(cm.doc.sel.from, cm.doc.sel.to); if (collapsed || cm.options.showCursorWhenSelecting) updateSelectionCursor(cm); else display.cursor.style.display = display.otherCursor.style.display = "none"; if (!collapsed) updateSelectionRange(cm); else display.selectionDiv.style.display = "none"; // Move the hidden textarea near the cursor to prevent scrolling artifacts if (cm.options.moveInputWithCursor) { var headPos = cursorCoords(cm, cm.doc.sel.head, "div"); var wrapOff = getRect(display.wrapper), lineOff = getRect(display.lineDiv); display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top)) + "px"; display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left)) + "px"; } } // No selection, plain cursor function updateSelectionCursor(cm) { var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div"); display.cursor.style.left = pos.left + "px"; display.cursor.style.top = pos.top + "px"; display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; display.cursor.style.display = ""; if (pos.other) { display.otherCursor.style.display = ""; display.otherCursor.style.left = pos.other.left + "px"; display.otherCursor.style.top = pos.other.top + "px"; display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; } else { display.otherCursor.style.display = "none"; } } // Highlight selection function updateSelectionRange(cm) { var display = cm.display, doc = cm.doc, sel = cm.doc.sel; var fragment = document.createDocumentFragment(); var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display); function add(left, top, width, bottom) { if (top < 0) top = 0; fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) + "px; 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); } iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { var leftPos = coords(from, "left"), rightPos, left, right; if (from == to) { rightPos = leftPos; left = right = leftPos.left; } else { rightPos = coords(to - 1, "right"); if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } left = leftPos.left; right = rightPos.right; } if (fromArg == null && from == 0) left = pl; if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part add(left, leftPos.top, null, leftPos.bottom); left = pl; if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); } if (toArg == null && to == lineLen) right = clientWidth; if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) start = leftPos; if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) end = rightPos; if (left < pl + 1) left = pl; add(left, rightPos.top, right - left, rightPos.bottom); }); return {start: start, end: end}; } if (sel.from.line == sel.to.line) { drawForLine(sel.from.line, sel.from.ch, sel.to.ch); } else { var fromLine = getLine(doc, sel.from.line), toLine = getLine(doc, sel.to.line); var singleVLine = visualLine(doc, fromLine) == visualLine(doc, toLine); var leftEnd = drawForLine(sel.from.line, sel.from.ch, singleVLine ? fromLine.text.length : null).end; var rightStart = drawForLine(sel.to.line, singleVLine ? 0 : null, sel.to.ch).start; if (singleVLine) { if (leftEnd.top < rightStart.top - 2) { add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); add(pl, rightStart.top, rightStart.left, rightStart.bottom); } else { add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); } } if (leftEnd.bottom < rightStart.top) add(pl, leftEnd.bottom, null, rightStart.top); } removeChildrenAndAdd(display.selectionDiv, fragment); display.selectionDiv.style.display = ""; } // Cursor-blinking function restartBlink(cm) { if (!cm.state.focused) return; var display = cm.display; clearInterval(display.blinker); var on = true; display.cursor.style.visibility = display.otherCursor.style.visibility = ""; if (cm.options.cursorBlinkRate > 0) display.blinker = setInterval(function() { display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden"; }, cm.options.cursorBlinkRate); } // HIGHLIGHT WORKER function startWorker(cm, time) { if (cm.doc.mode.startState && cm.doc.frontier < cm.display.showingTo) cm.state.highlight.set(time, bind(highlightWorker, cm)); } function highlightWorker(cm) { var doc = cm.doc; if (doc.frontier < doc.first) doc.frontier = doc.first; if (doc.frontier >= cm.display.showingTo) return; var end = +new Date + cm.options.workTime; var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); var changed = [], prevChange; doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo + 500), function(line) { if (doc.frontier >= cm.display.showingFrom) { // Visible var oldStyles = line.styles; line.styles = highlightLine(cm, line, state); var ischange = !oldStyles || oldStyles.length != line.styles.length; for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; if (ischange) { if (prevChange && prevChange.end == doc.frontier) prevChange.end++; else changed.push(prevChange = {start: doc.frontier, end: doc.frontier + 1}); } line.stateAfter = copyState(doc.mode, state); } else { processLine(cm, line, state); line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; } ++doc.frontier; if (+new Date > end) { startWorker(cm, cm.options.workDelay); return true; } }); if (changed.length) operation(cm, function() { for (var i = 0; i < changed.length; ++i) regChange(this, changed[i].start, changed[i].end); })(); } // 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); if (line.stateAfter && (!precise || search <= doc.frontier)) return search; var indented = countColumn(line.text, null, cm.options.tabSize); if (minline == null || minindent > indented) { minline = search - 1; minindent = indented; } } return minline; } function getStateBefore(cm, n, precise) { var doc = cm.doc, display = cm.display; if (!doc.mode.startState) return true; var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter; if (!state) state = startState(doc.mode); else state = copyState(doc.mode, state); doc.iter(pos, n, function(line) { processLine(cm, line, state); var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && pos < display.showingTo; line.stateAfter = save ? copyState(doc.mode, state) : null; ++pos; }); if (precise) doc.frontier = pos; return state; } // POSITION MEASUREMENT function paddingTop(display) {return display.lineSpace.offsetTop;} function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} function paddingLeft(display) { var e = removeChildrenAndAdd(display.measure, elt("pre", null, null, "text-align: left")).appendChild(elt("span", "x")); return e.offsetLeft; } function measureChar(cm, line, ch, data, bias) { var dir = -1; data = data || measureLine(cm, line); if (data.crude) { var left = data.left + ch * data.width; return {left: left, right: left + data.width, top: data.top, bottom: data.bottom}; } for (var pos = ch;; pos += dir) { var r = data[pos]; if (r) break; if (dir < 0 && pos == 0) dir = 1; } bias = pos > ch ? "left" : pos < ch ? "right" : bias; if (bias == "left" && r.leftSide) r = r.leftSide; else if (bias == "right" && r.rightSide) r = r.rightSide; return {left: pos < ch ? r.right : r.left, right: pos > ch ? r.left : r.right, top: r.top, bottom: r.bottom}; } function findCachedMeasurement(cm, line) { var cache = cm.display.measureLineCache; for (var i = 0; i < cache.length; ++i) { var memo = cache[i]; if (memo.text == line.text && memo.markedSpans == line.markedSpans && cm.display.scroller.clientWidth == memo.width && memo.classes == line.textClass + "|" + line.wrapClass) return memo; } } function clearCachedMeasurement(cm, line) { var exists = findCachedMeasurement(cm, line); if (exists) exists.text = exists.measure = exists.markedSpans = null; } function measureLine(cm, line) { // First look in the cache var cached = findCachedMeasurement(cm, line); if (cached) return cached.measure; // Failing that, recompute and store result in cache var measure = measureLineInner(cm, line); var cache = cm.display.measureLineCache; var memo = {text: line.text, width: cm.display.scroller.clientWidth, markedSpans: line.markedSpans, measure: measure, classes: line.textClass + "|" + line.wrapClass}; if (cache.length == 16) cache[++cm.display.measureLineCachePos % 16] = memo; else cache.push(memo); return measure; } function measureLineInner(cm, line) { if (!cm.options.lineWrapping && line.text.length >= cm.options.crudeMeasuringFrom) return crudelyMeasureLine(cm, line); var display = cm.display, measure = emptyArray(line.text.length); var pre = buildLineContent(cm, line, measure, true).pre; // IE does not cache element positions of inline elements between // calls to getBoundingClientRect. This makes the loop below, // which gathers the positions of all the characters on the line, // do an amount of layout work quadratic to the number of // characters. When line wrapping is off, we try to improve things // by first subdividing the line into a bunch of inline blocks, so // that IE can reuse most of the layout information from caches // for those blocks. This does interfere with line wrapping, so it // doesn't work when wrapping is on, but in that case the // situation is slightly better, since IE does cache line-wrapping // information and only recomputes per-line. if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) { var fragment = document.createDocumentFragment(); var chunk = 10, n = pre.childNodes.length; for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) { var wrap = elt("div", null, null, "display: inline-block"); for (var j = 0; j < chunk && n; ++j) { wrap.appendChild(pre.firstChild); --n; } fragment.appendChild(wrap); } pre.appendChild(fragment); } removeChildrenAndAdd(display.measure, pre); var outer = getRect(display.lineDiv); var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight; // Work around an IE7/8 bug where it will sometimes have randomly // replaced our pre with a clone at this point. if (ie_lt9 && display.measure.first != pre) removeChildrenAndAdd(display.measure, pre); function measureRect(rect) { var top = rect.top - outer.top, bot = rect.bottom - outer.top; if (bot > maxBot) bot = maxBot; if (top < 0) top = 0; for (var i = vranges.length - 2; i >= 0; i -= 2) { var rtop = vranges[i], rbot = vranges[i+1]; if (rtop > bot || rbot < top) continue; if (rtop <= top && rbot >= bot || top <= rtop && bot >= rbot || Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) { vranges[i] = Math.min(top, rtop); vranges[i+1] = Math.max(bot, rbot); break; } } if (i < 0) { i = vranges.length; vranges.push(top, bot); } return {left: rect.left - outer.left, right: rect.right - outer.left, top: i, bottom: null}; } function finishRect(rect) { rect.bottom = vranges[rect.top+1]; rect.top = vranges[rect.top]; } for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) { var node = cur, rect = null; // A widget might wrap, needs special care if (/\bCodeMirror-widget\b/.test(cur.className) && cur.getClientRects) { if (cur.firstChild.nodeType == 1) node = cur.firstChild; var rects = node.getClientRects(); if (rects.length > 1) { rect = data[i] = measureRect(rects[0]); rect.rightSide = measureRect(rects[rects.length - 1]); } } if (!rect) rect = data[i] = measureRect(getRect(node)); if (cur.measureRight) rect.right = getRect(cur.measureRight).left; if (cur.leftSide) rect.leftSide = measureRect(getRect(cur.leftSide)); } removeChildren(cm.display.measure); for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) { finishRect(cur); if (cur.leftSide) finishRect(cur.leftSide); if (cur.rightSide) finishRect(cur.rightSide); } return data; } function crudelyMeasureLine(cm, line) { var copy = new Line(line.text.slice(0, 100), null); if (line.textClass) copy.textClass = line.textClass; var measure = measureLineInner(cm, copy); var left = measureChar(cm, copy, 0, measure, "left"); var right = measureChar(cm, copy, 99, measure, "right"); return {crude: true, top: left.top, left: left.left, bottom: left.bottom, width: (right.right - left.left) / 100}; } function measureLineWidth(cm, line) { var hasBadSpan = false; if (line.markedSpans) for (var i = 0; i < line.markedSpans; ++i) { var sp = line.markedSpans[i]; if (sp.collapsed && (sp.to == null || sp.to == line.text.length)) hasBadSpan = true; } var cached = !hasBadSpan && findCachedMeasurement(cm, line); if (cached || line.text.length >= cm.options.crudeMeasuringFrom) return measureChar(cm, line, line.text.length, cached && cached.measure, "right").right; var pre = buildLineContent(cm, line, null, true).pre; var end = pre.appendChild(zeroWidthElement(cm.display.measure)); removeChildrenAndAdd(cm.display.measure, pre); return getRect(end).right - getRect(cm.display.lineDiv).left; } function clearCaches(cm) { cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0; cm.display.cachedCharWidth = cm.display.cachedTextHeight = null; if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; cm.display.lineNumChars = null; } function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page" function intoCoordSystem(cm, lineObj, rect, context) { if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { var size = widgetHeight(lineObj.widgets[i]); rect.top += size; rect.bottom += size; } if (context == "line") return rect; if (!context) context = "local"; var yOff = heightAtLine(cm, lineObj); if (context == "local") yOff += paddingTop(cm.display); else yOff -= cm.display.viewOffset; if (context == "page" || context == "window") { var lOff = getRect(cm.display.lineSpace); 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; } // Context may be "window", "page", "div", or "local"/null // Result is in "div" coords 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 = getRect(cm.display.sizer); left += localBox.left; top += localBox.top; } var lineSpaceBox = getRect(cm.display.lineSpace); 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, null, bias), context); } function cursorCoords(cm, pos, context, lineObj, measurement) { lineObj = lineObj || getLine(cm.doc, pos.line); if (!measurement) measurement = measureLine(cm, lineObj); function get(ch, right) { var m = measureChar(cm, lineObj, ch, measurement, right ? "right" : "left"); if (right) m.left = m.right; else m.right = m.left; return intoCoordSystem(cm, lineObj, m, context); } function getBidi(ch, partPos) { var part = order[partPos], right = part.level % 2; if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { part = order[--partPos]; ch = bidiRight(part) - (part.level % 2 ? 0 : 1); right = true; } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { part = order[++partPos]; ch = bidiLeft(part) - part.level % 2; right = false; } if (right && ch == part.to && ch > part.from) return get(ch - 1); return get(ch, right); } var order = getOrder(lineObj), ch = pos.ch; if (!order) return get(ch); var partPos = getBidiPartAt(order, ch); var val = getBidi(ch, partPos); if (bidiOther != null) val.other = getBidi(ch, bidiOther); return val; } function PosWithInfo(line, ch, outside, xRel) { var pos = new Pos(line, ch); pos.xRel = xRel; if (outside) pos.outside = true; return pos; } // Coords must be lineSpace-local function coordsChar(cm, x, y) { var doc = cm.doc; y += cm.display.viewOffset; if (y < 0) return PosWithInfo(doc.first, 0, true, -1); var lineNo = lineAtHeight(doc, y), last = doc.first + doc.size - 1; if (lineNo > last) return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1); if (x < 0) x = 0; for (;;) { var lineObj = getLine(doc, lineNo); var found = coordsCharInner(cm, lineObj, lineNo, x, y); var merged = collapsedSpanAtEnd(lineObj); var mergedPos = merged && merged.find(); if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) lineNo = mergedPos.to.line; else return found; } } function coordsCharInner(cm, lineObj, lineNo, x, y) { var innerOff = y - heightAtLine(cm, lineObj); var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; var measurement = measureLine(cm, lineObj); function getX(ch) { var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, measurement); wrongLine = true; if (innerOff > sp.bottom) return sp.left - adjust; else if (innerOff < sp.top) return sp.left + adjust; else wrongLine = false; return sp.left; } var bidi = getOrder(lineObj), dist = lineObj.text.length; var from = lineLeft(lineObj), to = lineRight(lineObj); var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); // Do a binary search between these bounds. for (;;) { if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { var ch = x < fromX || x - fromX <= toX - x ? from : to; var xDiff = x - (ch == from ? fromX : toX); while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch; var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, xDiff < 0 ? -1 : xDiff ? 1 : 0); return pos; } var step = Math.ceil(dist / 2), middle = from + step; if (bidi) { middle = from; for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); } var middleX = getX(middle); if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} } } var measureText; 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; } function charWidth(display) { if (display.cachedCharWidth != null) return display.cachedCharWidth; var anchor = elt("span", "x"); var pre = elt("pre", [anchor]); removeChildrenAndAdd(display.measure, pre); var width = anchor.offsetWidth; if (width > 2) display.cachedCharWidth = width; return width || 10; } // OPERATIONS // Operations are used to wrap changes in such a way that each // change won't have to update the cursor and display (which would // be awkward, slow, and error-prone), but instead updates are // batched and then all combined and executed at once. var nextOpId = 0; function startOperation(cm) { cm.curOp = { // An array of ranges of lines that have to be updated. See // updateDisplay. changes: [], forceUpdate: false, updateInput: null, userSelChange: null, textChanged: null, selectionChanged: false, cursorActivity: false, updateMaxLine: false, updateScrollPos: false, id: ++nextOpId }; if (!delayedCallbackDepth++) delayedCallbacks = []; } function endOperation(cm) { var op = cm.curOp, doc = cm.doc, display = cm.display; cm.curOp = null; if (op.updateMaxLine) computeMaxLength(cm); if (display.maxLineChanged && !cm.options.lineWrapping && display.maxLine) { var width = measureLineWidth(cm, display.maxLine); display.sizer.style.minWidth = Math.max(0, width + 3 + scrollerCutOff) + "px"; display.maxLineChanged = false; var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.offsetWidth - display.scroller.clientWidth); if (maxScrollLeft < doc.scrollLeft && !op.updateScrollPos) setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true); } var newScrollPos, updated; if (op.updateScrollPos) { newScrollPos = op.updateScrollPos; } else if (op.selectionChanged && display.scroller.clientHeight) { // don't rescroll if not visible var coords = cursorCoords(cm, doc.sel.head); newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom); } if (op.changes.length || op.forceUpdate || newScrollPos && newScrollPos.scrollTop != null) { updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop, op.forceUpdate); if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop; } if (!updated && op.selectionChanged) updateSelection(cm); if (op.updateScrollPos) { display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = newScrollPos.scrollTop; display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = newScrollPos.scrollLeft; alignHorizontally(cm); if (op.scrollToPos) scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos.from), clipPos(cm.doc, op.scrollToPos.to), op.scrollToPos.margin); } else if (newScrollPos) { scrollCursorIntoView(cm); } if (op.selectionChanged) restartBlink(cm); if (cm.state.focused && op.updateInput) resetInput(cm, op.userSelChange); 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 = 0; i < unhidden.length; ++i) if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); var delayed; if (!--delayedCallbackDepth) { delayed = delayedCallbacks; delayedCallbacks = null; } if (op.textChanged) signal(cm, "change", cm, op.textChanged); if (op.cursorActivity) signal(cm, "cursorActivity", cm); if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i](); } // Wraps a function in an operation. Returns the wrapped function. function operation(cm1, f) { return function() { var cm = cm1 || this, withOp = !cm.curOp; if (withOp) startOperation(cm); try { var result = f.apply(cm, arguments); } finally { if (withOp) endOperation(cm); } return result; }; } function docOperation(f) { return function() { var withOp = this.cm && !this.cm.curOp, result; if (withOp) startOperation(this.cm); try { result = f.apply(this, arguments); } finally { if (withOp) endOperation(this.cm); } return result; }; } function runInOp(cm, f) { var withOp = !cm.curOp, result; if (withOp) startOperation(cm); try { result = f(); } finally { if (withOp) endOperation(cm); } return result; } function regChange(cm, from, to, lendiff) { if (from == null) from = cm.doc.first; if (to == null) to = cm.doc.first + cm.doc.size; cm.curOp.changes.push({from: from, to: to, diff: lendiff}); } // INPUT HANDLING function slowPoll(cm) { if (cm.display.pollingFast) return; cm.display.poll.set(cm.options.pollInterval, function() { readInput(cm); if (cm.state.focused) slowPoll(cm); }); } function fastPoll(cm) { var missed = false; cm.display.pollingFast = true; function p() { var changed = readInput(cm); if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);} else {cm.display.pollingFast = false; slowPoll(cm);} } cm.display.poll.set(20, p); } // prevInput is a hack to work with IME. If we reset the textarea // on every change, that breaks IME. So we look for changes // compared to the previous content instead. (Modern browsers have // events that indicate IME taking place, but these are not widely // supported or compatible enough yet to rely on.) function readInput(cm) { var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc, sel = doc.sel; if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.state.disableInput) return false; if (cm.state.pasteIncoming && cm.state.fakedLastChar) { input.value = input.value.substring(0, input.value.length - 1); cm.state.fakedLastChar = false; } var text = input.value; if (text == prevInput && posEq(sel.from, sel.to)) return false; if (ie && !ie_lt9 && cm.display.inputHasSelection === text) { resetInput(cm, true); return false; } var withOp = !cm.curOp; if (withOp) startOperation(cm); sel.shift = false; var same = 0, l = Math.min(prevInput.length, text.length); while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; var from = sel.from, to = sel.to; if (same < prevInput.length) from = Pos(from.line, from.ch - (prevInput.length - same)); else if (cm.state.overwrite && posEq(from, to) && !cm.state.pasteIncoming) to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + (text.length - same))); var updateInput = cm.curOp.updateInput; var changeEvent = {from: from, to: to, text: splitLines(text.slice(same)), origin: cm.state.pasteIncoming ? "paste" : "+input"}; makeChange(cm.doc, changeEvent, "end"); cm.curOp.updateInput = updateInput; signalLater(cm, "inputRead", cm, changeEvent); if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = ""; else cm.display.prevInput = text; if (withOp) endOperation(cm); cm.state.pasteIncoming = false; return true; } function resetInput(cm, user) { var minimal, selected, doc = cm.doc; if (!posEq(doc.sel.from, doc.sel.to)) { cm.display.prevInput = ""; minimal = hasCopyEvent && (doc.sel.to.line - doc.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000); var content = minimal ? "-" : selected || cm.getSelection(); cm.display.input.value = content; if (cm.state.focused) selectInput(cm.display.input); if (ie && !ie_lt9) cm.display.inputHasSelection = content; } else if (user) { cm.display.prevInput = cm.display.input.value = ""; if (ie && !ie_lt9) cm.display.inputHasSelection = null; } cm.display.inaccurateSelection = minimal; } function focusInput(cm) { if (cm.options.readOnly != "nocursor" && (!mobile || document.activeElement != cm.display.input)) cm.display.input.focus(); } function isReadOnly(cm) { return cm.options.readOnly || cm.doc.cantEdit; } // EVENT HANDLERS function registerEventHandlers(cm) { var d = cm.display; on(d.scroller, "mousedown", operation(cm, onMouseDown)); if (ie) 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 = findWordAt(getLine(cm.doc, pos.line).text, pos); extendSelection(cm.doc, word.from, word.to); })); else on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); }); on(d.lineSpace, "selectstart", function(e) { if (!eventInWidget(d, e)) e_preventDefault(e); }); // Gecko browsers fire contextmenu *after* opening the menu, at // which point we can't mess with it anymore. Context menu is // handled in onMouseDown for Gecko. if (!captureMiddleClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); on(d.scroller, "scroll", function() { if (d.scroller.clientHeight) { setScrollTop(cm, d.scroller.scrollTop); setScrollLeft(cm, d.scroller.scrollLeft, true); signal(cm, "scroll", cm); } }); on(d.scrollbarV, "scroll", function() { if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop); }); on(d.scrollbarH, "scroll", function() { if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft); }); on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); } on(d.scrollbarH, "mousedown", reFocus); on(d.scrollbarV, "mousedown", reFocus); // Prevent wrapper from ever scrolling on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); var resizeTimer; function onResize() { if (resizeTimer == null) resizeTimer = setTimeout(function() { resizeTimer = null; // Might be a text scaling operation, clear size caches. d.cachedCharWidth = d.cachedTextHeight = knownScrollbarWidth = null; clearCaches(cm); runInOp(cm, bind(regChange, cm)); }, 100); } on(window, "resize", onResize); // Above handler holds on to the editor and its data structures. // Here we poll to unregister it when the editor is no longer in // the document, so that it can be garbage-collected. function unregister() { for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {} if (p) setTimeout(unregister, 5000); else off(window, "resize", onResize); } setTimeout(unregister, 5000); on(d.input, "keyup", operation(cm, function(e) { if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; if (e.keyCode == 16) cm.doc.sel.shift = false; })); on(d.input, "input", function() { if (ie && !ie_lt9 && cm.display.inputHasSelection) cm.display.inputHasSelection = null; fastPoll(cm); }); on(d.input, "keydown", operation(cm, onKeyDown)); on(d.input, "keypress", operation(cm, onKeyPress)); on(d.input, "focus", bind(onFocus, cm)); on(d.input, "blur", bind(onBlur, cm)); function drag_(e) { if (signalDOMEvent(cm, e) || cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return; e_stop(e); } if (cm.options.dragDrop) { on(d.scroller, "dragstart", function(e){onDragStart(cm, e);}); on(d.scroller, "dragenter", drag_); on(d.scroller, "dragover", drag_); on(d.scroller, "drop", operation(cm, onDrop)); } on(d.scroller, "paste", function(e) { if (eventInWidget(d, e)) return; focusInput(cm); fastPoll(cm); }); on(d.input, "paste", function() { // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206 // Add a char to the end of textarea before paste occur so that // selection doesn't span to the end of textarea. if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) { var start = d.input.selectionStart, end = d.input.selectionEnd; d.input.value += "$"; d.input.selectionStart = start; d.input.selectionEnd = end; cm.state.fakedLastChar = true; } cm.state.pasteIncoming = true; fastPoll(cm); }); function prepareCopy() { if (d.inaccurateSelection) { d.prevInput = ""; d.inaccurateSelection = false; d.input.value = cm.getSelection(); selectInput(d.input); } } on(d.input, "cut", prepareCopy); on(d.input, "copy", prepareCopy); // Needed to handle Tab key in KHTML if (khtml) on(d.sizer, "mouseup", function() { if (document.activeElement == d.input) d.input.blur(); focusInput(cm); }); } function eventInWidget(display, e) { for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true; } } function posFromMouse(cm, e, liberal) { var display = cm.display; if (!liberal) { var target = e_target(e); if (target == display.scrollbarH || target == display.scrollbarH.firstChild || target == display.scrollbarV || target == display.scrollbarV.firstChild || target == display.scrollbarFiller || target == display.gutterFiller) return null; } var x, y, space = getRect(display.lineSpace); // Fails unpredictably on IE[67] when mouse is dragged around quickly. try { x = e.clientX; y = e.clientY; } catch (e) { return null; } return coordsChar(cm, x - space.left, y - space.top); } var lastClick, lastDoubleClick; function onMouseDown(e) { if (signalDOMEvent(this, e)) return; var cm = this, display = cm.display, doc = cm.doc, sel = doc.sel; sel.shift = e.shiftKey; if (eventInWidget(display, e)) { if (!webkit) { display.scroller.draggable = false; setTimeout(function(){display.scroller.draggable = true;}, 100); } return; } if (clickInGutter(cm, e)) return; var start = posFromMouse(cm, e); switch (e_button(e)) { case 3: if (captureMiddleClick) onContextMenu.call(cm, cm, e); return; case 2: if (webkit) cm.state.lastMiddleDown = +new Date; if (start) extendSelection(cm.doc, start); setTimeout(bind(focusInput, cm), 20); e_preventDefault(e); return; } // For button 1, if it was clicked inside the editor // (posFromMouse returning non-null), we have to adjust the // selection. if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;} if (!cm.state.focused) onFocus(cm); var now = +new Date, type = "single"; if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) { type = "triple"; e_preventDefault(e); setTimeout(bind(focusInput, cm), 20); selectLine(cm, start.line); } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) { type = "double"; lastDoubleClick = {time: now, pos: start}; e_preventDefault(e); var word = findWordAt(getLine(doc, start.line).text, start); extendSelection(cm.doc, word.from, word.to); } else { lastClick = {time: now, pos: start}; } var last = start; if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) && !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") { var dragEnd = operation(cm, function(e2) { if (webkit) display.scroller.draggable = false; cm.state.draggingText = false; off(document, "mouseup", dragEnd); off(display.scroller, "drop", dragEnd); if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { e_preventDefault(e2); extendSelection(cm.doc, start); focusInput(cm); } }); // Let the drag handler handle this. if (webkit) display.scroller.draggable = true; cm.state.draggingText = dragEnd; // IE's approach to draggable if (display.scroller.dragDrop) display.scroller.dragDrop(); on(document, "mouseup", dragEnd); on(display.scroller, "drop", dragEnd); return; } e_preventDefault(e); if (type == "single") extendSelection(cm.doc, clipPos(doc, start)); var startstart = sel.from, startend = sel.to, lastPos = start; function doSelect(cur) { if (posEq(lastPos, cur)) return; lastPos = cur; if (type == "single") { extendSelection(cm.doc, clipPos(doc, start), cur); return; } startstart = clipPos(doc, startstart); startend = clipPos(doc, startend); if (type == "double") { var word = findWordAt(getLine(doc, cur.line).text, cur); if (posLess(cur, startstart)) extendSelection(cm.doc, word.from, startend); else extendSelection(cm.doc, startstart, word.to); } else if (type == "triple") { if (posLess(cur, startstart)) extendSelection(cm.doc, startend, clipPos(doc, Pos(cur.line, 0))); else extendSelection(cm.doc, startstart, clipPos(doc, Pos(cur.line + 1, 0))); } } var editorSize = getRect(display.wrapper); // 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); if (!cur) return; if (!posEq(cur, last)) { if (!cm.state.focused) onFocus(cm); last = cur; doSelect(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) { counter = Infinity; e_preventDefault(e); focusInput(cm); off(document, "mousemove", move); off(document, "mouseup", up); } var move = operation(cm, function(e) { if (!ie && !e_button(e)) done(e); else extend(e); }); var up = operation(cm, done); on(document, "mousemove", move); on(document, "mouseup", up); } function gutterEvent(cm, e, type, prevent, signalfn) { try { var mX = e.clientX, mY = e.clientY; } catch(e) { return false; } if (mX >= Math.floor(getRect(cm.display.gutters).right)) return false; if (prevent) e_preventDefault(e); var display = cm.display; var lineBox = getRect(display.lineDiv); 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 && getRect(g).right >= mX) { var line = lineAtHeight(cm.doc, mY); var gutter = cm.options.gutters[i]; signalfn(cm, type, cm, line, gutter, e); return e_defaultPrevented(e); } } } function contextMenuInGutter(cm, e) { if (!hasHandler(cm, "gutterContextMenu")) return false; return gutterEvent(cm, e, "gutterContextMenu", false, signal); } function clickInGutter(cm, e) { return gutterEvent(cm, e, "gutterClick", true, signalLater); } // 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; if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e) || (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e)))) return; e_preventDefault(e); if (ie) lastDrop = +new Date; var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; if (!pos || isReadOnly(cm)) return; if (files && files.length && window.FileReader && window.File) { var n = files.length, text = Array(n), read = 0; var loadFile = function(file, i) { var reader = new FileReader; reader.onload = function() { text[i] = reader.result; if (++read == n) { pos = clipPos(cm.doc, pos); makeChange(cm.doc, {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}, "around"); } }; reader.readAsText(file); }; for (var i = 0; i < n; ++i) loadFile(files[i], i); } else { // Don't do a replace if the drop happened inside of the selected text. if (cm.state.draggingText && !(posLess(pos, cm.doc.sel.from) || posLess(cm.doc.sel.to, pos))) { cm.state.draggingText(e); // Ensure the editor is re-focused setTimeout(bind(focusInput, cm), 20); return; } try { var text = e.dataTransfer.getData("Text"); if (text) { var curFrom = cm.doc.sel.from, curTo = cm.doc.sel.to; setSelection(cm.doc, pos, pos); if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "paste"); cm.replaceSelection(text, null, "paste"); focusInput(cm); onFocus(cm); } } 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; var txt = cm.getSelection(); e.dataTransfer.setData("Text", txt); // 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 (opera) { 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 (opera) img.parentNode.removeChild(img); } } function setScrollTop(cm, val) { if (Math.abs(cm.doc.scrollTop - val) < 2) return; cm.doc.scrollTop = val; if (!gecko) updateDisplay(cm, [], val); if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val; if (gecko) updateDisplay(cm, []); startWorker(cm, 100); } function setScrollLeft(cm, val, isScroller) { if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); cm.doc.scrollLeft = val; alignHorizontally(cm); if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val; } // Since the delta values reported on mouse wheel events are // unstandardized between browsers and even browser versions, and // generally horribly unpredictable, this code starts by measuring // the scroll effect that the first few mouse wheel events have, // and, from that, detects the way it can convert deltas to pixel // offsets afterwards. // // The reason we want to know the amount a wheel event will scroll // is that it gives us a chance to update the display before the // actual scrolling happens, reducing flickering. var wheelSamples = 0, wheelPixelsPerUnit = null; // Fill in a browser-detected starting value on browsers where we // know one. These don't have to be accurate -- the result of them // being wrong would just be a slight flicker on the first wheel // scroll (if it is large enough). if (ie) wheelPixelsPerUnit = -.53; else if (gecko) wheelPixelsPerUnit = 15; else if (chrome) wheelPixelsPerUnit = -.7; else if (safari) wheelPixelsPerUnit = -1/3; function onScrollWheel(cm, 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; var display = cm.display, scroll = display.scroller; // Quit if there's nothing to scroll here if (!(dx && scroll.scrollWidth > scroll.clientWidth || dy && scroll.scrollHeight > scroll.clientHeight)) 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) { for (var cur = e.target; cur != scroll; cur = cur.parentNode) { if (cur.lineObj) { cm.display.currentWheelTarget = cur; break; } } } // 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 && !opera && wheelPixelsPerUnit != null) { if (dy) setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); e_preventDefault(e); display.wheelStartX = null; // Abort measurement, if in progress return; } 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); updateDisplay(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; } } } 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 if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false; var doc = cm.doc, prevShift = doc.sel.shift, done = false; try { if (isReadOnly(cm)) cm.state.suppressEdits = true; if (dropShift) doc.sel.shift = false; done = bound(cm) != Pass; } finally { doc.sel.shift = prevShift; cm.state.suppressEdits = false; } return done; } function allKeyMaps(cm) { var maps = cm.state.keyMaps.slice(0); if (cm.options.extraKeys) maps.push(cm.options.extraKeys); maps.push(cm.options.keyMap); return maps; } var maybeTransition; function handleKeyBinding(cm, e) { // Handle auto keymap transitions var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto; clearTimeout(maybeTransition); if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { if (getKeyMap(cm.options.keyMap) == startMap) { cm.options.keyMap = (next.call ? next.call(null, cm) : next); keyMapChanged(cm); } }, 50); var name = keyName(e, true), handled = false; if (!name) return false; var keymaps = allKeyMaps(cm); if (e.shiftKey) { // 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-'. handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);}) || lookupKey(name, keymaps, function(b) { if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) return doHandleBinding(cm, b); }); } else { handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); }); } if (handled) { e_preventDefault(e); restartBlink(cm); if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; } signalLater(cm, "keyHandled", cm, name, e); } return handled; } function handleCharBinding(cm, e, ch) { var handled = lookupKey("'" + ch + "'", allKeyMaps(cm), function(b) { return doHandleBinding(cm, b, true); }); if (handled) { e_preventDefault(e); restartBlink(cm); signalLater(cm, "keyHandled", cm, "'" + ch + "'", e); } return handled; } var lastStoppedKey = null; function onKeyDown(e) { var cm = this; if (!cm.state.focused) onFocus(cm); if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; if (ie && e.keyCode == 27) e.returnValue = false; var code = e.keyCode; // IE does strange things with escape. cm.doc.sel.shift = code == 16 || e.shiftKey; // First give onKeyEvent option a chance to handle this. var handled = handleKeyBinding(cm, e); if (opera) { 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(""); } } function onKeyPress(e) { var cm = this; if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; var keyCode = e.keyCode, charCode = e.charCode; if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return; var ch = String.fromCharCode(charCode == null ? keyCode : charCode); if (this.options.electricChars && this.doc.mode.electricChars && this.options.smartIndent && !isReadOnly(this) && this.doc.mode.electricChars.indexOf(ch) > -1) setTimeout(operation(cm, function() {indentLine(cm, cm.doc.sel.to.line, "smart");}), 75); if (handleCharBinding(cm, e, ch)) return; if (ie && !ie_lt9) cm.display.inputHasSelection = null; fastPoll(cm); } function onFocus(cm) { if (cm.options.readOnly == "nocursor") return; if (!cm.state.focused) { signal(cm, "focus", cm); cm.state.focused = true; if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1) cm.display.wrapper.className += " CodeMirror-focused"; if (!cm.curOp) { resetInput(cm, true); if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730 } } slowPoll(cm); restartBlink(cm); } function onBlur(cm) { if (cm.state.focused) { signal(cm, "blur", cm); cm.state.focused = false; cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", ""); } clearInterval(cm.display.blinker); setTimeout(function() {if (!cm.state.focused) cm.doc.sel.shift = false;}, 150); } var detectingSelectAll; function onContextMenu(cm, e) { if (signalDOMEvent(cm, e, "contextmenu")) return; var display = cm.display, sel = cm.doc.sel; if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return; var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; if (!pos || opera) 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 && (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))) operation(cm, setSelection)(cm.doc, pos, pos); var oldCSS = display.input.style.cssText; display.inputDiv.style.position = "absolute"; display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" + "border-width: 0; outline: none; overflow: hidden; opacity: .05; -ms-opacity: .05; filter: alpha(opacity=5);"; focusInput(cm); resetInput(cm, true); // Adds "Select all" to context menu in FF if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " "; function prepareSelectAllHack() { if (display.input.selectionStart != null) { var extval = display.input.value = "\u200b" + (posEq(sel.from, sel.to) ? "" : display.input.value); display.prevInput = "\u200b"; display.input.selectionStart = 1; display.input.selectionEnd = extval.length; } } function rehide() { display.inputDiv.style.position = "relative"; display.input.style.cssText = oldCSS; if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos; slowPoll(cm); // Try to detect the user choosing select-all if (display.input.selectionStart != null) { if (!ie || ie_lt9) prepareSelectAllHack(); clearTimeout(detectingSelectAll); var i = 0, poll = function(){ if (display.prevInput == " " && display.input.selectionStart == 0) operation(cm, commands.selectAll)(cm); else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500); else resetInput(cm); }; detectingSelectAll = setTimeout(poll, 200); } } if (ie && !ie_lt9) prepareSelectAllHack(); if (captureMiddleClick) { e_stop(e); var mouseup = function() { off(window, "mouseup", mouseup); setTimeout(rehide, 20); }; on(window, "mouseup", mouseup); } else { setTimeout(rehide, 50); } } // UPDATING var changeEnd = CodeMirror.changeEnd = function(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)); }; // Make sure a position will be valid after the given change. function clipPostChange(doc, change, pos) { if (!posLess(change.from, pos)) return clipPos(doc, pos); var diff = (change.text.length - 1) - (change.to.line - change.from.line); if (pos.line > change.to.line + diff) { var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1; if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length); return clipToLen(pos, getLine(doc, preLine).text.length); } if (pos.line == change.to.line + diff) return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) + getLine(doc, change.to.line).text.length - change.to.ch); var inside = pos.line - change.from.line; return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch)); } // Hint can be null|"end"|"start"|"around"|{anchor,head} function computeSelAfterChange(doc, change, hint) { if (hint && typeof hint == "object") // Assumed to be {anchor, head} object return {anchor: clipPostChange(doc, change, hint.anchor), head: clipPostChange(doc, change, hint.head)}; if (hint == "start") return {anchor: change.from, head: change.from}; var end = changeEnd(change); if (hint == "around") return {anchor: change.from, head: end}; if (hint == "end") return {anchor: end, head: end}; // hint is null, leave the selection alone as much as possible var adjustPos = function(pos) { if (posLess(pos, change.from)) return pos; if (!posLess(change.to, pos)) return end; var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; if (pos.line == change.to.line) ch += end.ch - change.to.ch; return Pos(line, ch); }; return {anchor: adjustPos(doc.sel.anchor), head: adjustPos(doc.sel.head)}; } function filterChange(doc, change, update) { var obj = { canceled: false, from: change.from, to: change.to, text: change.text, origin: change.origin, cancel: function() { this.canceled = true; } }; if (update) obj.update = function(from, to, text, origin) { if (from) this.from = clipPos(doc, from); if (to) this.to = clipPos(doc, to); if (text) this.text = text; if (origin !== undefined) this.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}; } // Replace the range from from to to by the strings in replacement. // change is a {from, to, text [, origin]} object function makeChange(doc, change, selUpdate, ignoreReadOnly) { if (doc.cm) { if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, selUpdate, 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 >= 1; --i) makeChangeNoReadonly(doc, {from: split[i].from, to: split[i].to, text: [""]}); if (split.length) makeChangeNoReadonly(doc, {from: split[0].from, to: split[0].to, text: change.text}, selUpdate); } else { makeChangeNoReadonly(doc, change, selUpdate); } } function makeChangeNoReadonly(doc, change, selUpdate) { if (change.text.length == 1 && change.text[0] == "" && posEq(change.from, change.to)) return; var selAfter = computeSelAfterChange(doc, change, selUpdate); addToHistory(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)); }); } function makeChangeFromHistory(doc, type) { if (doc.cm && doc.cm.state.suppressEdits) return; var hist = doc.history; var event = (type == "undo" ? hist.done : hist.undone).pop(); if (!event) return; var anti = {changes: [], anchorBefore: event.anchorAfter, headBefore: event.headAfter, anchorAfter: event.anchorBefore, headAfter: event.headBefore, generation: hist.generation}; (type == "undo" ? hist.undone : hist.done).push(anti); hist.generation = event.generation || ++hist.maxGeneration; var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); for (var i = event.changes.length - 1; i >= 0; --i) { var change = event.changes[i]; change.origin = type; if (filter && !filterChange(doc, change, false)) { (type == "undo" ? hist.done : hist.undone).length = 0; return; } anti.changes.push(historyChangeFromChange(doc, change)); var after = i ? computeSelAfterChange(doc, change, null) : {anchor: event.anchorBefore, head: event.headBefore}; makeChangeSingleDoc(doc, change, after, mergeOldSpans(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, mergeOldSpans(doc, change)); }); } } function shiftDoc(doc, distance) { function shiftPos(pos) {return Pos(pos.line + distance, pos.ch);} doc.first += distance; if (doc.cm) regChange(doc.cm, doc.first, doc.first, distance); doc.sel.head = shiftPos(doc.sel.head); doc.sel.anchor = shiftPos(doc.sel.anchor); doc.sel.from = shiftPos(doc.sel.from); doc.sel.to = shiftPos(doc.sel.to); } 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, null); if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans, selAfter); else updateDoc(doc, change, spans, selAfter); } function makeChangeSingleDocInEditor(cm, change, spans, selAfter) { 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(doc, getLine(doc, from.line))); doc.iter(checkWidthStart, to.line + 1, function(line) { if (line == display.maxLine) { recomputeMaxLength = true; return true; } }); } if (!posLess(doc.sel.head, change.from) && !posLess(change.to, doc.sel.head)) cm.curOp.cursorActivity = true; updateDoc(doc, change, spans, selAfter, estimateHeight(cm)); if (!cm.options.lineWrapping) { doc.iter(checkWidthStart, from.line + change.text.length, function(line) { var len = lineLength(doc, line); if (len > display.maxLineLength) { display.maxLine = line; display.maxLineLength = len; display.maxLineChanged = true; recomputeMaxLength = false; } }); if (recomputeMaxLength) cm.curOp.updateMaxLine = true; } // Adjust frontier, schedule worker doc.frontier = Math.min(doc.frontier, from.line); startWorker(cm, 400); var lendiff = change.text.length - (to.line - from.line) - 1; // Remember that these lines changed, for updating the display regChange(cm, from.line, to.line + 1, lendiff); if (hasHandler(cm, "change")) { var changeObj = {from: from, to: to, text: change.text, removed: change.removed, origin: change.origin}; if (cm.curOp.textChanged) { for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {} cur.next = changeObj; } else cm.curOp.textChanged = changeObj; } } function replaceRange(doc, code, from, to, origin) { if (!to) to = from; if (posLess(to, from)) { var tmp = to; to = from; from = tmp; } if (typeof code == "string") code = splitLines(code); makeChange(doc, {from: from, to: to, text: code, origin: origin}, null); } // POSITION OBJECT function Pos(line, ch) { if (!(this instanceof Pos)) return new Pos(line, ch); this.line = line; this.ch = ch; } CodeMirror.Pos = Pos; function posEq(a, b) {return a.line == b.line && a.ch == b.ch;} function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);} function copyPos(x) {return Pos(x.line, x.ch);} // SELECTION 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 isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} // If shift is held, this will move the selection anchor. Otherwise, // it'll set the whole selection. function extendSelection(doc, pos, other, bias) { if (doc.sel.shift || doc.sel.extend) { var anchor = doc.sel.anchor; if (other) { var posBefore = posLess(pos, anchor); if (posBefore != posLess(other, anchor)) { anchor = pos; pos = other; } else if (posBefore != posLess(pos, other)) { pos = other; } } setSelection(doc, anchor, pos, bias); } else { setSelection(doc, pos, other || pos, bias); } if (doc.cm) doc.cm.curOp.userSelChange = true; } function filterSelectionChange(doc, anchor, head) { var obj = {anchor: anchor, head: head}; signal(doc, "beforeSelectionChange", doc, obj); if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); obj.anchor = clipPos(doc, obj.anchor); obj.head = clipPos(doc, obj.head); return obj; } // Update the selection. Last two args are only used by // updateDoc, since they have to be expressed in the line // numbers before the update. function setSelection(doc, anchor, head, bias, checkAtomic) { if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { var filtered = filterSelectionChange(doc, anchor, head); head = filtered.head; anchor = filtered.anchor; } var sel = doc.sel; sel.goalColumn = null; if (bias == null) bias = posLess(head, sel.head) ? -1 : 1; // Skip over atomic spans. if (checkAtomic || !posEq(anchor, sel.anchor)) anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push"); if (checkAtomic || !posEq(head, sel.head)) head = skipAtomic(doc, head, bias, checkAtomic != "push"); if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return; sel.anchor = anchor; sel.head = head; var inv = posLess(head, anchor); sel.from = inv ? head : anchor; sel.to = inv ? anchor : head; if (doc.cm) doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = doc.cm.curOp.cursorActivity = true; signalLater(doc, "cursorActivity", doc); } function reCheckSelection(cm) { setSelection(cm.doc, cm.doc.sel.from, cm.doc.sel.to, null, "push"); } function skipAtomic(doc, pos, bias, mayClear) { var flipped = false, curPos = pos; var dir = bias || 1; doc.cantEdit = false; search: for (;;) { var line = getLine(doc, curPos.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 <= curPos.ch : sp.from < curPos.ch)) && (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { if (mayClear) { signal(m, "beforeCursorEnter"); if (m.explicitlyCleared) { if (!line.markedSpans) break; else {--i; continue;} } } if (!m.atomic) continue; var newPos = m.find()[dir < 0 ? "from" : "to"]; if (posEq(newPos, curPos)) { newPos.ch += dir; if (newPos.ch < 0) { if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1)); else newPos = null; } else if (newPos.ch > line.text.length) { if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0); else newPos = null; } if (!newPos) { if (flipped) { // Driven in a corner -- no valid cursor position found at all // -- try again *with* clearing, if we didn't already if (!mayClear) return skipAtomic(doc, pos, bias, true); // Otherwise, turn off editing until further notice, and return the start of the doc doc.cantEdit = true; return Pos(doc.first, 0); } flipped = true; newPos = pos; dir = -dir; } } curPos = newPos; continue search; } } } return curPos; } } // SCROLLING function scrollCursorIntoView(cm) { var coords = scrollPosIntoView(cm, cm.doc.sel.head, null, cm.options.cursorScrollMargin); if (!cm.state.focused) return; var display = cm.display, box = getRect(display.sizer), doScroll = null; if (coords.top + box.top < 0) doScroll = true; else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; if (doScroll != null && !phantom) { var hidden = display.cursor.style.display == "none"; if (hidden) { display.cursor.style.display = ""; display.cursor.style.left = coords.left + "px"; display.cursor.style.top = (coords.top - display.viewOffset) + "px"; } display.cursor.scrollIntoView(doScroll); if (hidden) display.cursor.style.display = "none"; } } function scrollPosIntoView(cm, pos, end, margin) { if (margin == null) margin = 0; for (;;) { var changed = false, coords = cursorCoords(cm, pos); var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), Math.min(coords.top, endCoords.top) - margin, Math.max(coords.left, endCoords.left), Math.max(coords.bottom, endCoords.bottom) + margin); var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; if (scrollPos.scrollTop != null) { setScrollTop(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) return coords; } } function scrollIntoView(cm, x1, y1, x2, y2) { var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); } function calculateScrollPos(cm, x1, y1, x2, y2) { var display = cm.display, snapMargin = textHeight(cm.display); if (y1 < 0) y1 = 0; var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {}; var docBottom = cm.doc.height + paddingVert(display); var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; if (y1 < screentop) { result.scrollTop = atTop ? 0 : y1; } else if (y2 > screentop + screen) { var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); if (newTop != screentop) result.scrollTop = newTop; } var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft; x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth; var gutterw = display.gutters.offsetWidth; var atLeft = x1 < gutterw + 10; if (x1 < screenleft + gutterw || atLeft) { if (atLeft) x1 = 0; result.scrollLeft = Math.max(0, x1 - 10 - gutterw); } else if (x2 > screenw + screenleft - 3) { result.scrollLeft = x2 + 10 - screenw; } return result; } function updateScrollPos(cm, left, top) { cm.curOp.updateScrollPos = {scrollLeft: left == null ? cm.doc.scrollLeft : left, scrollTop: top == null ? cm.doc.scrollTop : top}; } function addToScrollPos(cm, left, top) { var pos = cm.curOp.updateScrollPos || (cm.curOp.updateScrollPos = {scrollLeft: cm.doc.scrollLeft, scrollTop: cm.doc.scrollTop}); var scroll = cm.display.scroller; pos.scrollTop = Math.max(0, Math.min(scroll.scrollHeight - scroll.clientHeight, pos.scrollTop + top)); pos.scrollLeft = Math.max(0, Math.min(scroll.scrollWidth - scroll.clientWidth, pos.scrollLeft + left)); } // API UTILITIES function indentLine(cm, n, how, aggressive) { var doc = cm.doc; if (how == null) how = "add"; if (how == "smart") { if (!cm.doc.mode.indent) how = "prev"; else var state = getStateBefore(cm, n); } var tabSize = cm.options.tabSize; var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); var curSpaceString = line.text.match(/^\s*/)[0], indentation; if (how == "smart") { indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); if (indentation == Pass) { 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(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); line.stateAfter = null; } function changeLine(cm, handle, op) { var no = handle, line = handle, doc = cm.doc; if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); else no = lineNo(handle); if (no == null) return null; if (op(line, no)) regChange(cm, no, no + 1); else return null; return line; } function findPosH(doc, pos, dir, unit, visually) { var line = pos.line, ch = pos.ch, origDir = dir; var lineObj = getLine(doc, line); var possible = true; function findNextLine() { var l = line + dir; if (l < doc.first || l >= doc.first + doc.size) return (possible = false); line = l; return lineObj = getLine(doc, l); } function moveOnce(boundToLine) { var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); if (next == null) { if (!boundToLine && findNextLine()) { if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); else ch = dir < 0 ? lineObj.text.length : 0; } else return (possible = false); } else ch = 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"; for (var first = true;; first = false) { if (dir < 0 && !moveOnce(!first)) break; var cur = lineObj.text.charAt(ch) || "\n"; var type = isWordChar(cur) ? "w" : !group ? null : /\s/.test(cur) ? null : "p"; if (sawType && sawType != type) { if (dir < 0) {dir = 1; moveOnce();} break; } if (type) sawType = type; if (dir > 0 && !moveOnce(!first)) break; } } var result = skipAtomic(doc, Pos(line, ch), origDir, true); if (!possible) result.hitSide = true; return result; } 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); y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); } else if (unit == "line") { y = dir > 0 ? pos.bottom + 3 : pos.top - 3; } for (;;) { var 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; } function findWordAt(line, pos) { var start = pos.ch, end = pos.ch; if (line) { if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; var startChar = line.charAt(start); var check = isWordChar(startChar) ? isWordChar : /\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 {from: Pos(pos.line, start), to: Pos(pos.line, end)}; } function selectLine(cm, line) { extendSelection(cm.doc, Pos(line, 0), clipPos(cm.doc, Pos(line + 1, 0))); } // PROTOTYPE // The publicly visible API. Note that operation(null, f) means // 'wrap f in an operation, performed on its `this` parameter' CodeMirror.prototype = { constructor: CodeMirror, focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);}, 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); }, getOption: function(option) {return this.options[option];}, getDoc: function() {return this.doc;}, addKeyMap: function(map, bottom) { this.state.keyMaps[bottom ? "push" : "unshift"](map); }, removeKeyMap: function(map) { var maps = this.state.keyMaps; for (var i = 0; i < maps.length; ++i) if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map)) { maps.splice(i, 1); return true; } }, addOverlay: operation(null, function(spec, options) { var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); if (mode.startState) throw new Error("Overlays may not be stateful."); this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); this.state.modeGen++; regChange(this); }), removeOverlay: operation(null, function(spec) { 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.state.modeGen++; regChange(this); return; } } }), indentLine: operation(null, 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: operation(null, function(how) { var sel = this.doc.sel; if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how); var e = sel.to.line - (sel.to.ch ? 0 : 1); for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how); }), // 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) { var doc = this.doc; pos = clipPos(doc, pos); var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode; var line = getLine(doc, pos.line); var stream = new StringStream(line.text, this.options.tabSize); while (stream.pos < pos.ch && !stream.eol()) { stream.start = stream.pos; var style = mode.token(stream, state); } return {start: stream.start, end: stream.pos, string: stream.current(), className: style || null, // Deprecated, use 'type' instead type: style || null, state: state}; }, 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; if (ch == 0) return styles[2]; 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 return styles[mid * 2 + 2]; } }, 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) { if (!helpers.hasOwnProperty(type)) return; var help = helpers[type], mode = this.getModeAt(pos); return mode[type] && help[mode[type]] || mode.helperType && help[mode.helperType] || help[mode.name]; }, getStateAfter: function(line, precise) { var doc = this.doc; line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); return getStateBefore(this, line + 1, precise); }, cursorCoords: function(start, mode) { var pos, sel = this.doc.sel; if (start == null) pos = sel.head; else if (typeof start == "object") pos = clipPos(this.doc, start); else pos = start ? sel.from : sel.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) { var end = false, 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; } var lineObj = getLine(this.doc, line); return intoCoordSystem(this, getLine(this.doc, line), {top: 0, left: 0}, mode || "page").top + (end ? lineObj.height : 0); }, defaultTextHeight: function() { return textHeight(this.display); }, defaultCharWidth: function() { return charWidth(this.display); }, setGutterMarker: operation(null, function(line, gutterID, value) { return changeLine(this, line, function(line) { var markers = line.gutterMarkers || (line.gutterMarkers = {}); markers[gutterID] = value; if (!value && isEmpty(markers)) line.gutterMarkers = null; return true; }); }), clearGutter: operation(null, function(gutterID) { var cm = this, doc = cm.doc, i = doc.first; doc.iter(function(line) { if (line.gutterMarkers && line.gutterMarkers[gutterID]) { line.gutterMarkers[gutterID] = null; regChange(cm, i, i + 1); if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; } ++i; }); }), addLineClass: operation(null, function(handle, where, cls) { return changeLine(this, handle, function(line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; if (!line[prop]) line[prop] = cls; else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false; else line[prop] += " " + cls; return true; }); }), removeLineClass: operation(null, function(handle, where, cls) { return changeLine(this, handle, function(line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; var cur = line[prop]; if (!cur) return false; else if (cls == null) line[prop] = null; else { var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)")); 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: operation(null, function(handle, node, options) { return addLineWidget(this, handle, node, options); }), removeLineWidget: function(widget) { widget.clear(); }, lineInfo: function(line) { if (typeof line == "number") { if (!isLine(this.doc, line)) return null; var n = line; line = getLine(this.doc, line); if (!line) return null; } else { var 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}; }, getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};}, 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"; 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, top, left + node.offsetWidth, top + node.offsetHeight); }, triggerOnKeyDown: operation(null, onKeyDown), execCommand: function(cmd) {return commands[cmd](this);}, findPosH: function(from, amount, unit, visually) { var dir = 1; if (amount < 0) { dir = -1; amount = -amount; } for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { cur = findPosH(this.doc, cur, dir, unit, visually); if (cur.hitSide) break; } return cur; }, moveH: operation(null, function(dir, unit) { var sel = this.doc.sel, pos; if (sel.shift || sel.extend || posEq(sel.from, sel.to)) pos = findPosH(this.doc, sel.head, dir, unit, this.options.rtlMoveVisually); else pos = dir < 0 ? sel.from : sel.to; extendSelection(this.doc, pos, pos, dir); }), deleteH: operation(null, function(dir, unit) { var sel = this.doc.sel; if (!posEq(sel.from, sel.to)) replaceRange(this.doc, "", sel.from, sel.to, "+delete"); else replaceRange(this.doc, "", sel.from, findPosH(this.doc, sel.head, dir, unit, false), "+delete"); this.curOp.userSelChange = true; }), findPosV: function(from, amount, unit, goalColumn) { var dir = 1, x = goalColumn; if (amount < 0) { dir = -1; amount = -amount; } for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { var coords = cursorCoords(this, cur, "div"); if (x == null) x = coords.left; else coords.left = x; cur = findPosV(this, coords, dir, unit); if (cur.hitSide) break; } return cur; }, moveV: operation(null, function(dir, unit) { var sel = this.doc.sel; var pos = cursorCoords(this, sel.head, "div"); if (sel.goalColumn != null) pos.left = sel.goalColumn; var target = findPosV(this, pos, dir, unit); if (unit == "page") addToScrollPos(this, 0, charCoords(this, target, "div").top - pos.top); extendSelection(this.doc, target, target, dir); sel.goalColumn = pos.left; }), toggleOverwrite: function(value) { if (value != null && value == this.state.overwrite) return; if (this.state.overwrite = !this.state.overwrite) this.display.cursor.className += " CodeMirror-overwrite"; else this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", ""); }, hasFocus: function() { return this.state.focused; }, scrollTo: operation(null, function(x, y) { updateScrollPos(this, x, y); }), getScrollInfo: function() { var scroller = this.display.scroller, co = scrollerCutOff; return {left: scroller.scrollLeft, top: scroller.scrollTop, height: scroller.scrollHeight - co, width: scroller.scrollWidth - co, clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co}; }, scrollIntoView: operation(null, function(range, margin) { if (range == null) range = {from: this.doc.sel.head, to: null}; 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; if (!margin) margin = 0; var coords = range; if (range.from.line != null) { this.curOp.scrollToPos = {from: range.from, to: range.to, margin: margin}; coords = {from: cursorCoords(this, range.from), to: cursorCoords(this, range.to)}; } var sPos = calculateScrollPos(this, Math.min(coords.from.left, coords.to.left), Math.min(coords.from.top, coords.to.top) - margin, Math.max(coords.from.right, coords.to.right), Math.max(coords.from.bottom, coords.to.bottom) + margin); updateScrollPos(this, sPos.scrollLeft, sPos.scrollTop); }), setSize: operation(null, function(width, height) { function interpret(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) this.display.measureLineCache.length = this.display.measureLineCachePos = 0; this.curOp.forceUpdate = true; }), operation: function(f){return runInOp(this, f);}, refresh: operation(null, function() { var badHeight = this.display.cachedTextHeight == null; clearCaches(this); updateScrollPos(this, this.doc.scrollLeft, this.doc.scrollTop); regChange(this); if (badHeight) estimateLineHeights(this); }), swapDoc: operation(null, function(doc) { var old = this.doc; old.cm = null; attachDoc(this, doc); clearCaches(this); resetInput(this, true); updateScrollPos(this, doc.scrollLeft, doc.scrollTop); signalLater(this, "swapDoc", this, old); return old; }), getInputField: function(){return this.display.input;}, getWrapperElement: function(){return this.display.wrapper;}, getScrollerElement: function(){return this.display.scroller;}, getGutterElement: function(){return this.display.gutters;} }; eventMixin(CodeMirror); // OPTION DEFAULTS var optionHandlers = CodeMirror.optionHandlers = {}; // The default configuration options. var defaults = CodeMirror.defaults = {}; 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; } var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.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) { 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) { loadMode(cm); clearCaches(cm); regChange(cm); }, true); option("electricChars", true); option("rtlMoveVisually", !windows); option("theme", "default", function(cm) { themeChanged(cm); guttersChanged(cm); }, true); option("keyMap", "default", keyMapChanged); option("extraKeys", null); option("onKeyEvent", null); option("onDragEvent", 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, updateScrollbars, 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("readOnly", false, function(cm, val) { if (val == "nocursor") {onBlur(cm); cm.display.input.blur();} else if (!val) resetInput(cm, true); }); option("dragDrop", true); option("cursorBlinkRate", 530); option("cursorScrollMargin", 0); option("cursorHeight", 1); option("workTime", 100); option("workDelay", 100); option("flattenSpans", true); option("pollInterval", 100); option("undoDepth", 40, function(cm, val){cm.doc.history.undoDepth = val;}); option("historyEventDelay", 500); option("viewportMargin", 10, function(cm){cm.refresh();}, true); option("maxHighlightLength", 10000, function(cm){loadMode(cm); cm.refresh();}, true); option("crudeMeasuringFrom", 10000); option("moveInputWithCursor", true, function(cm, val) { if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0; }); option("tabindex", null, function(cm, val) { cm.display.input.tabIndex = val || ""; }); option("autofocus", null); // MODE DEFINITION AND QUERYING // Known modes, by name and by MIME var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; CodeMirror.defineMode = function(name, mode) { if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; if (arguments.length > 2) { mode.dependencies = []; for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]); } modes[name] = mode; }; CodeMirror.defineMIME = function(mime, spec) { mimeModes[mime] = spec; }; CodeMirror.resolveMode = function(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]; spec = createObj(found, spec); spec.name = found.name; } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { return CodeMirror.resolveMode("application/xml"); } if (typeof spec == "string") return {name: spec}; else return spec || {name: "null"}; }; CodeMirror.getMode = function(options, spec) { var spec = CodeMirror.resolveMode(spec); var mfactory = modes[spec.name]; if (!mfactory) return CodeMirror.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; return modeObj; }; CodeMirror.defineMode("null", function() { return {token: function(stream) {stream.skipToEnd();}}; }); CodeMirror.defineMIME("text/plain", "null"); var modeExtensions = CodeMirror.modeExtensions = {}; CodeMirror.extendMode = function(mode, properties) { var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); copyObj(properties, exts); }; // EXTENSIONS CodeMirror.defineExtension = function(name, func) { CodeMirror.prototype[name] = func; }; CodeMirror.defineDocExtension = function(name, func) { Doc.prototype[name] = func; }; CodeMirror.defineOption = option; var initHooks = []; CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; var helpers = CodeMirror.helpers = {}; CodeMirror.registerHelper = function(type, name, value) { if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {}; helpers[type][name] = value; }; // UTILITIES CodeMirror.isWordChar = isWordChar; // MODE STATE HANDLING // Utility functions for working with state. Exported because modes // sometimes need to do this. 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; } CodeMirror.copyState = copyState; function startState(mode, a1, a2) { return mode.startState ? mode.startState(a1, a2) : true; } CodeMirror.startState = startState; CodeMirror.innerMode = function(mode, state) { while (mode.innerMode) { var info = mode.innerMode(state); if (!info || info.mode == mode) break; state = info.state; mode = info.mode; } return info || {mode: mode, state: state}; }; // STANDARD COMMANDS var commands = CodeMirror.commands = { selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()));}, killLine: function(cm) { var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to); if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, Pos(from.line + 1, 0), "+delete"); else cm.replaceRange("", from, sel ? to : Pos(from.line), "+delete"); }, deleteLine: function(cm) { var l = cm.getCursor().line; cm.replaceRange("", Pos(l, 0), Pos(l), "+delete"); }, delLineLeft: function(cm) { var cur = cm.getCursor(); cm.replaceRange("", Pos(cur.line, 0), cur, "+delete"); }, undo: function(cm) {cm.undo();}, redo: function(cm) {cm.redo();}, goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, goLineStart: function(cm) { cm.extendSelection(lineStart(cm, cm.getCursor().line)); }, goLineStartSmart: function(cm) { var cur = cm.getCursor(), start = lineStart(cm, cur.line); var line = cm.getLineHandle(start.line); var order = getOrder(line); if (!order || order[0].level == 0) { var firstNonWS = Math.max(0, line.text.search(/\S/)); var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch; cm.extendSelection(Pos(start.line, inWS ? 0 : firstNonWS)); } else cm.extendSelection(start); }, goLineEnd: function(cm) { cm.extendSelection(lineEnd(cm, cm.getCursor().line)); }, goLineRight: function(cm) { var top = cm.charCoords(cm.getCursor(), "div").top + 5; cm.extendSelection(cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")); }, goLineLeft: function(cm) { var top = cm.charCoords(cm.getCursor(), "div").top + 5; cm.extendSelection(cm.coordsChar({left: 0, top: top}, "div")); }, goLineUp: function(cm) {cm.moveV(-1, "line");}, goLineDown: function(cm) {cm.moveV(1, "line");}, goPageUp: function(cm) {cm.moveV(-1, "page");}, goPageDown: function(cm) {cm.moveV(1, "page");}, goCharLeft: function(cm) {cm.moveH(-1, "char");}, goCharRight: function(cm) {cm.moveH(1, "char");}, goColumnLeft: function(cm) {cm.moveH(-1, "column");}, goColumnRight: function(cm) {cm.moveH(1, "column");}, goWordLeft: function(cm) {cm.moveH(-1, "word");}, goGroupRight: function(cm) {cm.moveH(1, "group");}, goGroupLeft: function(cm) {cm.moveH(-1, "group");}, goWordRight: function(cm) {cm.moveH(1, "word");}, delCharBefore: function(cm) {cm.deleteH(-1, "char");}, delCharAfter: function(cm) {cm.deleteH(1, "char");}, delWordBefore: function(cm) {cm.deleteH(-1, "word");}, delWordAfter: function(cm) {cm.deleteH(1, "word");}, delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, delGroupAfter: function(cm) {cm.deleteH(1, "group");}, indentAuto: function(cm) {cm.indentSelection("smart");}, indentMore: function(cm) {cm.indentSelection("add");}, indentLess: function(cm) {cm.indentSelection("subtract");}, insertTab: function(cm) {cm.replaceSelection("\t", "end", "+input");}, defaultTab: function(cm) { if (cm.somethingSelected()) cm.indentSelection("add"); else cm.replaceSelection("\t", "end", "+input"); }, transposeChars: function(cm) { var cur = cm.getCursor(), line = cm.getLine(cur.line); if (cur.ch > 0 && cur.ch < line.length - 1) cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1)); }, newlineAndIndent: function(cm) { operation(cm, function() { cm.replaceSelection("\n", "end", "+input"); cm.indentLine(cm.getCursor().line, null, true); })(); }, toggleOverwrite: function(cm) {cm.toggleOverwrite();} }; // STANDARD KEYMAPS var keyMap = CodeMirror.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" }; // Note that the save and find-related commands aren't defined by // default. 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", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd", "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", fallthrough: "basic" }; keyMap.macDefault = { "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "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": "delLineLeft", fallthrough: ["basic", "emacsy"] }; keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; 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" }; // KEYMAP DISPATCH function getKeyMap(val) { if (typeof val == "string") return keyMap[val]; else return val; } function lookupKey(name, maps, handle) { function lookup(map) { map = getKeyMap(map); var found = map[name]; if (found === false) return "stop"; if (found != null && handle(found)) return true; if (map.nofallthrough) return "stop"; var fallthrough = map.fallthrough; if (fallthrough == null) return false; if (Object.prototype.toString.call(fallthrough) != "[object Array]") return lookup(fallthrough); for (var i = 0, e = fallthrough.length; i < e; ++i) { var done = lookup(fallthrough[i]); if (done) return done; } return false; } for (var i = 0; i < maps.length; ++i) { var done = lookup(maps[i]); if (done) return done != "stop"; } } function isModifierKey(event) { var name = keyNames[event.keyCode]; return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; } function keyName(event, noShift) { if (opera && event.keyCode == 34 && event["char"]) return false; var name = keyNames[event.keyCode]; if (name == null || event.altGraphKey) return false; if (event.altKey) name = "Alt-" + name; if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name; if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name; if (!noShift && event.shiftKey) name = "Shift-" + name; return name; } CodeMirror.lookupKey = lookupKey; CodeMirror.isModifierKey = isModifierKey; CodeMirror.keyName = keyName; // FROMTEXTAREA CodeMirror.fromTextArea = function(textarea, options) { if (!options) 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 = document.body; // doc.activeElement occasionally throws on IE try { hasFocus = document.activeElement; } catch(e) {} options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body; } function save() {textarea.value = cm.getValue();} 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) {} } } textarea.style.display = "none"; var cm = CodeMirror(function(node) { textarea.parentNode.insertBefore(node, textarea.nextSibling); }, options); cm.save = save; cm.getTextArea = function() { return textarea; }; cm.toTextArea = function() { 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; } }; return cm; }; // STRING STREAM // Fed to the mode parsers, provides helper functions to make // parsers more succinct. // The character stream used by a mode's parser. function StringStream(string, tabSize) { this.pos = this.start = 0; this.string = string; this.tabSize = tabSize || 8; this.lastColumnPos = this.lastColumnValue = 0; } StringStream.prototype = { eol: function() {return this.pos >= this.string.length;}, sol: function() {return this.pos == 0;}, peek: function() {return this.string.charAt(this.pos) || undefined;}, next: function() { if (this.pos < this.string.length) return this.string.charAt(this.pos++); }, eat: function(match) { var ch = this.string.charAt(this.pos); if (typeof match == "string") var ok = ch == match; else var ok = ch && (match.test ? match.test(ch) : match(ch)); if (ok) {++this.pos; return ch;} }, eatWhile: function(match) { var start = this.pos; while (this.eat(match)){} return this.pos > start; }, eatSpace: function() { var start = this.pos; while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; return this.pos > start; }, skipToEnd: function() {this.pos = this.string.length;}, skipTo: function(ch) { var found = this.string.indexOf(ch, this.pos); if (found > -1) {this.pos = found; return true;} }, backUp: function(n) {this.pos -= n;}, 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; }, indentation: function() {return countColumn(this.string, null, this.tabSize);}, 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; } }, current: function(){return this.string.slice(this.start, this.pos);} }; CodeMirror.StringStream = StringStream; // TEXTMARKERS function TextMarker(doc, type) { this.lines = []; this.type = type; this.doc = doc; } CodeMirror.TextMarker = TextMarker; eventMixin(TextMarker); TextMarker.prototype.clear = function() { 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.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this); if (span.to != null) max = lineNo(line); line.markedSpans = removeMarkedSpan(line.markedSpans, span); if (span.from != null) min = lineNo(line); else if (this.collapsed && !lineIsHidden(this.doc, line) && cm) updateLineHeight(line, textHeight(cm.display)); } if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) { var visual = visualLine(cm.doc, this.lines[i]), len = lineLength(cm.doc, visual); if (len > cm.display.maxLineLength) { cm.display.maxLine = visual; cm.display.maxLineLength = len; cm.display.maxLineChanged = true; } } if (min != null && cm) 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); } if (withOp) endOperation(cm); }; TextMarker.prototype.find = function() { var from, to; for (var i = 0; i < this.lines.length; ++i) { var line = this.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this); if (span.from != null || span.to != null) { var found = lineNo(line); if (span.from != null) from = Pos(found, span.from); if (span.to != null) to = Pos(found, span.to); } } if (this.type == "bookmark") return from; return from && {from: from, to: to}; }; TextMarker.prototype.changed = function() { var pos = this.find(), cm = this.doc.cm; if (!pos || !cm) return; if (this.type != "bookmark") pos = pos.from; var line = getLine(this.doc, pos.line); clearCachedMeasurement(cm, line); if (pos.line >= cm.display.showingFrom && pos.line < cm.display.showingTo) { for (var node = cm.display.lineDiv.firstChild; node; node = node.nextSibling) if (node.lineObj == line) { if (node.offsetHeight != line.height) updateLineHeight(line, node.offsetHeight); break; } runInOp(cm, function() { cm.curOp.selectionChanged = cm.curOp.forceUpdate = cm.curOp.updateMaxLine = true; }); } }; 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); } }; function markText(doc, from, to, options, type) { if (options && options.shared) return markTextShared(doc, from, to, options, type); if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); var marker = new TextMarker(doc, type); if (type == "range" && !posLess(from, to)) return marker; if (options) copyObj(options, marker); if (marker.replacedWith) { marker.collapsed = true; marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget"); if (!options.handleMouseEvents) marker.replacedWith.ignoreEvents = true; } if (marker.collapsed) sawCollapsedSpans = true; if (marker.addToHistory) addToHistory(doc, {from: from, to: to, origin: "markText"}, {head: doc.sel.head, anchor: doc.sel.anchor}, NaN); var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd, cm = doc.cm, updateMaxLine; doc.iter(curLine, to.line + 1, function(line) { if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(doc, line) == cm.display.maxLine) updateMaxLine = true; var span = {from: null, to: null, marker: marker}; size += line.text.length; if (curLine == from.line) {span.from = from.ch; size -= from.ch;} if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;} if (marker.collapsed) { if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch); if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch); else updateLineHeight(line, 0); } addMarkedSpan(line, span); ++curLine; }); 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() { marker.clear(); }); if (marker.readOnly) { sawReadOnlySpans = true; if (doc.history.done.length || doc.history.undone.length) doc.clearHistory(); } if (marker.collapsed) { if (collapsedAtStart != collapsedAtEnd) throw new Error("Inserting collapsed marker overlapping an existing one"); marker.size = size; marker.atomic = true; } if (cm) { if (updateMaxLine) cm.curOp.updateMaxLine = true; if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.collapsed) regChange(cm, from.line, to.line + 1); if (marker.atomic) reCheckSelection(cm); } return marker; } // SHARED TEXTMARKERS function SharedTextMarker(markers, primary) { this.markers = markers; this.primary = primary; for (var i = 0, me = this; i < markers.length; ++i) { markers[i].parent = this; on(markers[i], "clear", function(){me.clear();}); } } CodeMirror.SharedTextMarker = SharedTextMarker; eventMixin(SharedTextMarker); SharedTextMarker.prototype.clear = function() { if (this.explicitlyCleared) return; this.explicitlyCleared = true; for (var i = 0; i < this.markers.length; ++i) this.markers[i].clear(); signalLater(this, "clear"); }; SharedTextMarker.prototype.find = function() { return this.primary.find(); }; 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.replacedWith; linkedDocs(doc, function(doc) { if (widget) options.replacedWith = 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); } // TEXTMARKER SPANS function getMarkedSpanFor(spans, marker) { if (spans) for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if (span.marker == marker) return span; } } function removeMarkedSpan(spans, span) { for (var r, i = 0; i < spans.length; ++i) if (spans[i] != span) (r || (r = [])).push(spans[i]); return r; } function addMarkedSpan(line, span) { line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; span.marker.attachLine(line); } function markedSpansBefore(old, startCh, isInsert) { if (old) for (var i = 0, nw; 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 || marker.type == "bookmark" && span.from == startCh && (!isInsert || !span.marker.insertLeft)) { var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); (nw || (nw = [])).push({from: span.from, to: endsAfter ? null : span.to, marker: marker}); } } return nw; } function markedSpansAfter(old, endCh, isInsert) { if (old) for (var i = 0, nw; 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 || marker.type == "bookmark" && span.from == endCh && (!isInsert || span.marker.insertLeft)) { var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh, to: span.to == null ? null : span.to - endCh, marker: marker}); } } return nw; } function stretchSpansOverChange(doc, change) { 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 = posEq(change.from, change.to); // 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 = 0; i < last.length; ++i) { var span = last[i]; if (span.to != null) span.to += offset; if (span.from == null) { var found = getMarkedSpanFor(first, span.marker); if (!found) { span.from = offset; if (sameLine) (first || (first = [])).push(span); } } else { span.from += offset; if (sameLine) (first || (first = [])).push(span); } } } if (sameLine && first) { // Make sure we didn't create any zero-length spans for (var i = 0; i < first.length; ++i) if (first[i].from != null && first[i].from == first[i].to && first[i].marker.type != "bookmark") first.splice(i--, 1); if (!first.length) first = null; } 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 = 0; i < first.length; ++i) if (first[i].to == null) (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker}); for (var i = 0; i < gap; ++i) newMarkers.push(gapMarkers); newMarkers.push(last); } return newMarkers; } 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; } 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(); for (var j = 0; j < parts.length; ++j) { var p = parts[j]; if (posLess(p.to, m.from) || posLess(m.to, p.from)) continue; var newParts = [j, 1]; if (posLess(p.from, m.from) || !mk.inclusiveLeft && posEq(p.from, m.from)) newParts.push({from: p.from, to: m.from}); if (posLess(m.to, p.to) || !mk.inclusiveRight && posEq(p.to, m.to)) newParts.push({from: m.to, to: p.to}); parts.splice.apply(parts, newParts); j += newParts.length - 1; } } return parts; } function collapsedSpanAt(line, ch) { var sps = sawCollapsedSpans && line.markedSpans, found; if (sps) for (var sp, i = 0; i < sps.length; ++i) { sp = sps[i]; if (!sp.marker.collapsed) continue; if ((sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || found.width < sp.marker.width)) found = sp.marker; } return found; } function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); } function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); } function visualLine(doc, line) { var merged; while (merged = collapsedSpanAtStart(line)) line = getLine(doc, merged.find().from.line); return line; } function lineIsHidden(doc, line) { var sps = sawCollapsedSpans && line.markedSpans; if (sps) for (var sp, i = 0; i < sps.length; ++i) { sp = sps[i]; if (!sp.marker.collapsed) continue; if (sp.from == null) return true; if (sp.marker.replacedWith) 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().to, endLine = getLine(doc, end.line); return lineIsHiddenInner(doc, endLine, getMarkedSpanFor(endLine.markedSpans, span.marker)); } if (span.marker.inclusiveRight && span.to == line.text.length) return true; for (var sp, i = 0; i < line.markedSpans.length; ++i) { sp = line.markedSpans[i]; if (sp.marker.collapsed && !sp.marker.replacedWith && sp.from == span.to && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc, line, sp)) return true; } } 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; } // LINE WIDGETS var LineWidget = CodeMirror.LineWidget = function(cm, node, options) { if (options) for (var opt in options) if (options.hasOwnProperty(opt)) this[opt] = options[opt]; this.cm = cm; this.node = node; }; eventMixin(LineWidget); function widgetOperation(f) { return function() { var withOp = !this.cm.curOp; if (withOp) startOperation(this.cm); try {var result = f.apply(this, arguments);} finally {if (withOp) endOperation(this.cm);} return result; }; } LineWidget.prototype.clear = widgetOperation(function() { var ws = this.line.widgets, no = lineNo(this.line); if (no == null || !ws) return; for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); if (!ws.length) this.line.widgets = null; var aboveVisible = heightAtLine(this.cm, this.line) < this.cm.doc.scrollTop; updateLineHeight(this.line, Math.max(0, this.line.height - widgetHeight(this))); if (aboveVisible) addToScrollPos(this.cm, 0, -this.height); regChange(this.cm, no, no + 1); }); LineWidget.prototype.changed = widgetOperation(function() { var oldH = this.height; this.height = null; var diff = widgetHeight(this) - oldH; if (!diff) return; updateLineHeight(this.line, this.line.height + diff); var no = lineNo(this.line); regChange(this.cm, no, no + 1); }); function widgetHeight(widget) { if (widget.height != null) return widget.height; if (!widget.node.parentNode || widget.node.parentNode.nodeType != 1) removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative")); return widget.height = widget.node.offsetHeight; } function addLineWidget(cm, handle, node, options) { var widget = new LineWidget(cm, node, options); if (widget.noHScroll) cm.display.alignWidgets = true; changeLine(cm, handle, 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 (!lineIsHidden(cm.doc, line) || widget.showIfHidden) { var aboveVisible = heightAtLine(cm, line) < cm.doc.scrollTop; updateLineHeight(line, line.height + widgetHeight(widget)); if (aboveVisible) addToScrollPos(cm, 0, widget.height); } return true; }); return widget; } // LINE DATA STRUCTURE // Line objects. These hold state related to a line, including // highlighting info (the styles array). var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { this.text = text; attachMarkedSpans(this, markedSpans); this.height = estimateHeight ? estimateHeight(this) : 1; }; eventMixin(Line); 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); } function cleanUpLine(line) { line.parent = null; detachMarkedSpans(line); } // Run the given mode's parser over a line, update the styles // array, which contains alternating fragments of text and CSS // classes. function runMode(cm, text, mode, state, f) { var flattenSpans = mode.flattenSpans; if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; var curStart = 0, curStyle = null; var stream = new StringStream(text, cm.options.tabSize), style; if (text == "" && mode.blankLine) mode.blankLine(state); while (!stream.eol()) { if (stream.pos > cm.options.maxHighlightLength) { flattenSpans = false; stream.pos = text.length; style = null; } else { style = mode.token(stream, state); } if (!flattenSpans || curStyle != style) { if (curStart < stream.start) f(stream.start, curStyle); curStart = stream.start; curStyle = style; } stream.start = stream.pos; } while (curStart < stream.pos) { // Webkit seems to refuse to render text nodes longer than 57444 characters var pos = Math.min(stream.pos, curStart + 50000); f(pos, curStyle); curStart = pos; } } function highlightLine(cm, line, state) { // 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]; // Compute the base array of styles runMode(cm, line.text, cm.doc.mode, state, function(end, style) {st.push(end, style);}); // Run overlays, adjust style array. for (var o = 0; o < cm.state.overlays.length; ++o) { var overlay = cm.state.overlays[o], i = 1, at = 0; runMode(cm, line.text, overlay.mode, true, 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, style); i = start + 2; } else { for (; start < i; start += 2) { var cur = st[start+1]; st[start+1] = cur ? cur + " " + style : style; } } }); } return st; } function getLineStyles(cm, line) { if (!line.styles || line.styles[0] != cm.state.modeGen) line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line))); return line.styles; } // Lightweight form of highlight -- proceed over this line and // update state, but don't save a style array. function processLine(cm, line, state) { var mode = cm.doc.mode; var stream = new StringStream(line.text, cm.options.tabSize); if (line.text == "" && mode.blankLine) mode.blankLine(state); while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) { mode.token(stream, state); stream.start = stream.pos; } } var styleToClassCache = {}; function interpretTokenStyle(style, builder) { if (!style) return null; for (;;) { var lineClass = style.match(/(?:^|\s)line-(background-)?(\S+)/); if (!lineClass) break; style = style.slice(0, lineClass.index) + style.slice(lineClass.index + lineClass[0].length); var prop = lineClass[1] ? "bgClass" : "textClass"; if (builder[prop] == null) builder[prop] = lineClass[2]; else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(builder[prop])) builder[prop] += " " + lineClass[2]; } return styleToClassCache[style] || (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-")); } function buildLineContent(cm, realLine, measure, copyWidgets) { var merged, line = realLine, empty = true; while (merged = collapsedSpanAtStart(line)) line = getLine(cm.doc, merged.find().from.line); var builder = {pre: elt("pre"), col: 0, pos: 0, measure: null, measuredSomething: false, cm: cm, copyWidgets: copyWidgets}; do { if (line.text) empty = false; builder.measure = line == realLine && measure; builder.pos = 0; builder.addToken = builder.measure ? buildTokenMeasure : buildToken; if ((ie || webkit) && cm.getOption("lineWrapping")) builder.addToken = buildTokenSplitSpaces(builder.addToken); var next = insertLineContent(line, builder, getLineStyles(cm, line)); if (measure && line == realLine && !builder.measuredSomething) { measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure)); builder.measuredSomething = true; } if (next) line = getLine(cm.doc, next.to.line); } while (next); if (measure && !builder.measuredSomething && !measure[0]) measure[0] = builder.pre.appendChild(empty ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure)); if (!builder.pre.firstChild && !lineIsHidden(cm.doc, realLine)) builder.pre.appendChild(document.createTextNode("\u00a0")); var order; // Work around problem with the reported dimensions of single-char // direction spans on IE (issue #1129). See also the comment in // cursorCoords. if (measure && ie && (order = getOrder(line))) { var l = order.length - 1; if (order[l].from == order[l].to) --l; var last = order[l], prev = order[l - 1]; if (last.from + 1 == last.to && prev && last.level < prev.level) { var span = measure[builder.pos - 1]; if (span) span.parentNode.insertBefore(span.measureRight = zeroWidthElement(cm.display.measure), span.nextSibling); } } var textClass = builder.textClass ? builder.textClass + " " + (realLine.textClass || "") : realLine.textClass; if (textClass) builder.pre.className = textClass; signal(cm, "renderLine", cm, realLine, builder.pre); return builder; } var tokenSpecialChars = /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\uFEFF]/g; function buildToken(builder, text, style, startStyle, endStyle, title) { if (!text) return; if (!tokenSpecialChars.test(text)) { builder.col += text.length; var content = document.createTextNode(text); } else { var content = document.createDocumentFragment(), pos = 0; while (true) { tokenSpecialChars.lastIndex = pos; var m = tokenSpecialChars.exec(text); var skipped = m ? m.index - pos : text.length - pos; if (skipped) { content.appendChild(document.createTextNode(text.slice(pos, pos + skipped))); builder.col += skipped; } if (!m) break; pos += skipped + 1; if (m[0] == "\t") { var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); builder.col += tabWidth; } else { var token = elt("span", "\u2022", "cm-invalidchar"); token.title = "\\u" + m[0].charCodeAt(0).toString(16); content.appendChild(token); builder.col += 1; } } } if (style || startStyle || endStyle || builder.measure) { var fullStyle = style || ""; if (startStyle) fullStyle += startStyle; if (endStyle) fullStyle += endStyle; var token = elt("span", [content], fullStyle); if (title) token.title = title; return builder.pre.appendChild(token); } builder.pre.appendChild(content); } function buildTokenMeasure(builder, text, style, startStyle, endStyle) { var wrapping = builder.cm.options.lineWrapping; for (var i = 0; i < text.length; ++i) { var ch = text.charAt(i), start = i == 0; if (ch >= "\ud800" && ch < "\udbff" && i < text.length - 1) { ch = text.slice(i, i + 2); ++i; } else if (i && wrapping && spanAffectsWrapping(text, i)) { builder.pre.appendChild(elt("wbr")); } var old = builder.measure[builder.pos]; var span = builder.measure[builder.pos] = buildToken(builder, ch, style, start && startStyle, i == text.length - 1 && endStyle); if (old) span.leftSide = old.leftSide || old; // In IE single-space nodes wrap differently than spaces // embedded in larger text nodes, except when set to // white-space: normal (issue #1268). if (ie && wrapping && ch == " " && i && !/\s/.test(text.charAt(i - 1)) && i < text.length - 1 && !/\s/.test(text.charAt(i + 1))) span.style.whiteSpace = "normal"; builder.pos += ch.length; } if (text.length) builder.measuredSomething = true; } function buildTokenSplitSpaces(inner) { function split(old) { var out = " "; for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; out += " "; return out; } return function(builder, text, style, startStyle, endStyle, title) { return inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle, title); }; } function buildCollapsedSpan(builder, size, marker, ignoreWidget) { var widget = !ignoreWidget && marker.replacedWith; if (widget) { if (builder.copyWidgets) widget = widget.cloneNode(true); builder.pre.appendChild(widget); if (builder.measure) { if (size) { builder.measure[builder.pos] = widget; } else { var elt = zeroWidthElement(builder.cm.display.measure); if (marker.type == "bookmark" && !marker.insertLeft) builder.measure[builder.pos] = builder.pre.appendChild(elt); else if (builder.measure[builder.pos]) return; else builder.measure[builder.pos] = builder.pre.insertBefore(elt, widget); } builder.measuredSomething = true; } } builder.pos += size; } // 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; i < styles.length; i+=2) builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder)); return; } var len = allText.length, pos = 0, i = 1, text = "", style; var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; for (;;) { if (nextChange == pos) { // Update current marker set spanStyle = spanEndStyle = spanStartStyle = title = ""; collapsed = null; nextChange = Infinity; var foundBookmarks = []; for (var j = 0; j < spans.length; ++j) { var sp = spans[j], m = sp.marker; if (sp.from <= pos && (sp.to == null || sp.to > pos)) { if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; } if (m.className) spanStyle += " " + m.className; if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; if (m.title && !title) title = m.title; if (m.collapsed && (!collapsed || collapsed.marker.size < m.size)) collapsed = sp; } else if (sp.from > pos && nextChange > sp.from) { nextChange = sp.from; } if (m.type == "bookmark" && sp.from == pos && m.replacedWith) foundBookmarks.push(m); } if (collapsed && (collapsed.from || 0) == pos) { buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos, collapsed.marker, collapsed.from == null); if (collapsed.to == null) return collapsed.marker.find(); } if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j) buildCollapsedSpan(builder, 0, foundBookmarks[j]); } 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); } 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); } } } // DOCUMENT DATA STRUCTURE function updateDoc(doc, change, markedSpans, selAfter, estimateHeight) { function spansFor(n) {return markedSpans ? markedSpans[n] : null;} function update(line, text, spans) { updateLine(line, text, spans, estimateHeight); signalLater(line, "change", line, change); } 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; // First adjust the line structure if (from.ch == 0 && to.ch == 0 && lastText == "") { // This is a whole-line replace. Treated specially to make // sure line objects move the way they are supposed to. for (var i = 0, e = text.length - 1, added = []; i < e; ++i) added.push(new Line(text[i], spansFor(i), estimateHeight)); 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 { for (var added = [], i = 1, e = text.length - 1; i < e; ++i) added.push(new Line(text[i], spansFor(i), estimateHeight)); added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); doc.insert(from.line + 1, added); } } else if (text.length == 1) { update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); doc.remove(from.line + 1, nlines); } else { update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); for (var i = 1, e = text.length - 1, added = []; i < e; ++i) added.push(new Line(text[i], spansFor(i), estimateHeight)); if (nlines > 1) doc.remove(from.line + 1, nlines - 1); doc.insert(from.line + 1, added); } signalLater(doc, "change", doc, change); setSelection(doc, selAfter.anchor, selAfter.head, null, true); } function LeafChunk(lines) { this.lines = lines; this.parent = null; for (var i = 0, e = lines.length, height = 0; i < e; ++i) { lines[i].parent = this; height += lines[i].height; } this.height = height; } LeafChunk.prototype = { chunkSize: function() { return this.lines.length; }, removeInner: function(at, n) { for (var i = at, e = at + n; i < e; ++i) { var line = this.lines[i]; this.height -= line.height; cleanUpLine(line); signalLater(line, "delete"); } this.lines.splice(at, n); }, collapse: function(lines) { lines.splice.apply(lines, [lines.length, 0].concat(this.lines)); }, insertInner: function(at, lines, height) { this.height += height; this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this; }, iterN: function(at, n, op) { for (var e = at + n; at < e; ++at) if (op(this.lines[at])) return true; } }; function BranchChunk(children) { this.children = children; var size = 0, height = 0; for (var i = 0, e = children.length; i < e; ++i) { var ch = children[i]; size += ch.chunkSize(); height += ch.height; ch.parent = this; } this.size = size; this.height = height; this.parent = null; } BranchChunk.prototype = { chunkSize: function() { return this.size; }, removeInner: function(at, n) { this.size -= n; for (var i = 0; i < this.children.length; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at < sz) { var rm = Math.min(n, sz - at), oldHeight = child.height; child.removeInner(at, rm); this.height -= oldHeight - child.height; if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } if ((n -= rm) == 0) break; at = 0; } else at -= sz; } if (this.size - n < 25) { var lines = []; this.collapse(lines); this.children = [new LeafChunk(lines)]; this.children[0].parent = this; } }, collapse: function(lines) { for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines); }, insertInner: function(at, lines, height) { this.size += lines.length; this.height += height; for (var i = 0, e = this.children.length; i < e; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at <= sz) { child.insertInner(at, lines, height); if (child.lines && child.lines.length > 50) { while (child.lines.length > 50) { var spilled = child.lines.splice(child.lines.length - 25, 25); var newleaf = new LeafChunk(spilled); child.height -= newleaf.height; this.children.splice(i + 1, 0, newleaf); newleaf.parent = this; } this.maybeSpill(); } break; } at -= sz; } }, maybeSpill: function() { if (this.children.length <= 10) return; var me = this; do { var spilled = me.children.splice(me.children.length - 5, 5); var sibling = new BranchChunk(spilled); if (!me.parent) { // Become the parent node var copy = new BranchChunk(me.children); copy.parent = me; me.children = [copy, sibling]; me = copy; } else { me.size -= sibling.size; me.height -= sibling.height; var myIndex = indexOf(me.parent.children, me); me.parent.children.splice(myIndex + 1, 0, sibling); } sibling.parent = me.parent; } while (me.children.length > 10); me.parent.maybeSpill(); }, iterN: function(at, n, op) { for (var i = 0, e = this.children.length; i < e; ++i) { var child = this.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; } } }; var nextDocId = 0; var Doc = CodeMirror.Doc = function(text, mode, firstLine) { if (!(this instanceof Doc)) return new Doc(text, mode, firstLine); 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.history = makeHistory(); this.cleanGeneration = 1; this.frontier = firstLine; var start = Pos(firstLine, 0); this.sel = {from: start, to: start, head: start, anchor: start, shift: false, extend: false, goalColumn: null}; this.id = ++nextDocId; this.modeOption = mode; if (typeof text == "string") text = splitLines(text); updateDoc(this, {from: start, to: start, text: text}, null, {head: start, anchor: start}); }; Doc.prototype = createObj(BranchChunk.prototype, { constructor: Doc, 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); }, insert: function(at, lines) { var height = 0; for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height; this.insertInner(at - this.first, lines, height); }, remove: function(at, n) { this.removeInner(at - this.first, n); }, getValue: function(lineSep) { var lines = getLines(this, this.first, this.first + this.size); if (lineSep === false) return lines; return lines.join(lineSep || "\n"); }, setValue: 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: splitLines(code), origin: "setValue"}, {head: top, anchor: top}, true); }, 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 || "\n"); }, getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, setLine: function(line, text) { if (isLine(this, line)) replaceRange(this, text, Pos(line, 0), clipPos(this, Pos(line))); }, removeLine: function(line) { if (line) replaceRange(this, "", clipPos(this, Pos(line - 1)), clipPos(this, Pos(line))); else replaceRange(this, "", Pos(0, 0), clipPos(this, Pos(1, 0))); }, 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(this, 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 sel = this.sel, pos; if (start == null || start == "head") pos = sel.head; else if (start == "anchor") pos = sel.anchor; else if (start == "end" || start === false) pos = sel.to; else pos = sel.from; return copyPos(pos); }, somethingSelected: function() {return !posEq(this.sel.head, this.sel.anchor);}, setCursor: docOperation(function(line, ch, extend) { var pos = clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line); if (extend) extendSelection(this, pos); else setSelection(this, pos, pos); }), setSelection: docOperation(function(anchor, head, bias) { setSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), bias); }), extendSelection: docOperation(function(from, to, bias) { extendSelection(this, clipPos(this, from), to && clipPos(this, to), bias); }), getSelection: function(lineSep) {return this.getRange(this.sel.from, this.sel.to, lineSep);}, replaceSelection: function(code, collapse, origin) { makeChange(this, {from: this.sel.from, to: this.sel.to, text: splitLines(code), origin: origin}, collapse || "around"); }, undo: docOperation(function() {makeChangeFromHistory(this, "undo");}), redo: docOperation(function() {makeChangeFromHistory(this, "redo");}), setExtending: function(val) {this.sel.extend = val;}, historySize: function() { var hist = this.history; return {undo: hist.done.length, redo: hist.undone.length}; }, clearHistory: function() {this.history = makeHistory(this.history.maxGeneration);}, markClean: function() { this.cleanGeneration = this.changeGeneration(); }, changeGeneration: function() { this.history.lastOp = 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 = makeHistory(this.history.maxGeneration); hist.done = histData.done.slice(0); hist.undone = histData.undone.slice(0); }, markText: function(from, to, options) { return markText(this, clipPos(this, from), clipPos(this, to), options, "range"); }, setBookmark: function(pos, options) { var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), insertLeft: options && options.insertLeft}; 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; }, 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; this.iter(function(line) { var sz = line.text.length + 1; 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; this.iter(this.first, coords.line, function (line) { index += line.text.length + 1; }); return index; }, copy: function(copyHistory) { var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first); doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; doc.sel = {from: this.sel.from, to: this.sel.to, head: this.sel.head, anchor: this.sel.anchor, shift: this.sel.shift, extend: false, goalColumn: this.sel.goalColumn}; 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); 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}]; return copy; }, unlinkDoc: function(other) { if (other instanceof CodeMirror) other = other.doc; if (this.linked) for (var i = 0; i < this.linked.length; ++i) { var link = this.linked[i]; if (link.doc != other) continue; this.linked.splice(i, 1); other.unlinkDoc(this); break; } // If the histories were shared, split them again if (other.history == this.history) { var splitIds = [other.id]; linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); other.history = makeHistory(); 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;} }); Doc.prototype.eachLine = Doc.prototype.iter; // The Doc methods that should be available on CodeMirror instances var dontDelegate = "iter insert remove copy getEditor".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); 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); } 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); if (!cm.options.lineWrapping) computeMaxLength(cm); cm.options.mode = doc.modeOption; regChange(cm); } // LINE UTILITIES function getLine(chunk, n) { n -= chunk.first; 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]; } 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; } function getLines(doc, from, to) { var out = []; doc.iter(from, to, function(line) { out.push(line.text); }); return out; } function updateLineHeight(line, height) { var diff = height - line.height; for (var n = line; n; n = n.parent) n.height += diff; } 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; } function lineAtHeight(chunk, h) { var n = chunk.first; outer: do { for (var i = 0, e = chunk.children.length; i < e; ++i) { var child = chunk.children[i], ch = child.height; if (h < ch) { chunk = child; continue outer; } h -= ch; n += child.chunkSize(); } return n; } while (!chunk.lines); for (var i = 0, e = chunk.lines.length; i < e; ++i) { var line = chunk.lines[i], lh = line.height; if (h < lh) break; h -= lh; } return n + i; } function heightAtLine(cm, lineObj) { lineObj = visualLine(cm.doc, 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 = 0; i < p.children.length; ++i) { var cur = p.children[i]; if (cur == chunk) break; else h += cur.height; } } return h; } function getOrder(line) { var order = line.order; if (order == null) order = line.order = bidiOrdering(line.text); return order; } // HISTORY function makeHistory(startGen) { return { // Arrays of history events. Doing something adds an event to // done and clears undo. Undoing moves events from done to // undone, redoing moves them in the other direction. done: [], undone: [], undoDepth: Infinity, // Used to track when changes can be merged into a single undo // event lastTime: 0, lastOp: null, lastOrigin: null, // Used by the isClean() method generation: startGen || 1, maxGeneration: startGen || 1 }; } 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; }); } function historyChangeFromChange(doc, change) { var from = { line: change.from.line, ch: change.from.ch }; var histChange = {from: 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) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); return histChange; } function addToHistory(doc, change, selAfter, opId) { var hist = doc.history; hist.undone.length = 0; var time = +new Date, cur = lst(hist.done); if (cur && (hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && ((change.origin.charAt(0) == "+" && doc.cm && hist.lastTime > time - doc.cm.options.historyEventDelay) || change.origin.charAt(0) == "*"))) { // Merge this change into the last event var last = lst(cur.changes); if (posEq(change.from, change.to) && posEq(change.from, last.to)) { // 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)); } cur.anchorAfter = selAfter.anchor; cur.headAfter = selAfter.head; } else { // Can not be merged, start a new event. cur = {changes: [historyChangeFromChange(doc, change)], generation: hist.generation, anchorBefore: doc.sel.anchor, headBefore: doc.sel.head, anchorAfter: selAfter.anchor, headAfter: selAfter.head}; hist.done.push(cur); hist.generation = ++hist.maxGeneration; while (hist.done.length > hist.undoDepth) hist.done.shift(); } hist.lastTime = time; hist.lastOp = opId; hist.lastOrigin = change.origin; } function removeClearedSpans(spans) { if (!spans) return null; for (var i = 0, out; 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; } function getOldSpans(doc, change) { var found = change["spans_" + doc.id]; if (!found) return null; for (var i = 0, nw = []; i < change.text.length; ++i) nw.push(removeClearedSpans(found[i])); return nw; } // 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) { for (var i = 0, copy = []; i < events.length; ++i) { var event = events[i], changes = event.changes, newChanges = []; copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefore: event.headBefore, anchorAfter: event.anchorAfter, headAfter: event.headAfter}); for (var j = 0; j < changes.length; ++j) { var change = changes[j], m; newChanges.push({from: change.from, to: change.to, text: change.text}); if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { if (indexOf(newGroup, Number(m[1])) > -1) { lst(newChanges)[prop] = change[prop]; delete change[prop]; } } } } return copy; } // Rebasing/resetting history to deal with externally-sourced changes function rebaseHistSel(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; for (var j = 0; j < sub.changes.length; ++j) { var cur = sub.changes[j]; if (!sub.copied) { cur.from = copyPos(cur.from); cur.to = copyPos(cur.to); } if (to < cur.from.line) { cur.from.line += diff; cur.to.line += diff; } else if (from <= cur.to.line) { ok = false; break; } } if (!sub.copied) { sub.anchorBefore = copyPos(sub.anchorBefore); sub.headBefore = copyPos(sub.headBefore); sub.anchorAfter = copyPos(sub.anchorAfter); sub.readAfter = copyPos(sub.headAfter); sub.copied = true; } if (!ok) { array.splice(0, i + 1); i = 0; } else { rebaseHistSel(sub.anchorBefore); rebaseHistSel(sub.headBefore); rebaseHistSel(sub.anchorAfter); rebaseHistSel(sub.headAfter); } } } 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); } // EVENT OPERATORS function stopMethod() {e_stop(this);} // Ensure an event has a stop method. function addStop(event) { if (!event.stop) event.stop = stopMethod; return event; } 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);} CodeMirror.e_stop = e_stop; CodeMirror.e_preventDefault = e_preventDefault; CodeMirror.e_stopPropagation = e_stopPropagation; 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; } // EVENT HANDLING function on(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 = {}); var arr = map[type] || (map[type] = []); arr.push(f); } } function off(emitter, type, f) { if (emitter.removeEventListener) emitter.removeEventListener(type, f, false); else if (emitter.detachEvent) emitter.detachEvent("on" + type, f); else { var arr = emitter._handlers && emitter._handlers[type]; if (!arr) return; for (var i = 0; i < arr.length; ++i) if (arr[i] == f) { arr.splice(i, 1); break; } } } function signal(emitter, type /*, values...*/) { var arr = emitter._handlers && emitter._handlers[type]; if (!arr) return; var args = Array.prototype.slice.call(arguments, 2); for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); } var delayedCallbacks, delayedCallbackDepth = 0; function signalLater(emitter, type /*, values...*/) { var arr = emitter._handlers && emitter._handlers[type]; if (!arr) return; var args = Array.prototype.slice.call(arguments, 2); if (!delayedCallbacks) { ++delayedCallbackDepth; delayedCallbacks = []; setTimeout(fireDelayed, 0); } function bnd(f) {return function(){f.apply(null, args);};}; for (var i = 0; i < arr.length; ++i) delayedCallbacks.push(bnd(arr[i])); } function signalDOMEvent(cm, e, override) { signal(cm, override || e.type, cm, e); return e_defaultPrevented(e) || e.codemirrorIgnore; } function fireDelayed() { --delayedCallbackDepth; var delayed = delayedCallbacks; delayedCallbacks = null; for (var i = 0; i < delayed.length; ++i) delayed[i](); } function hasHandler(emitter, type) { var arr = emitter._handlers && emitter._handlers[type]; return arr && arr.length > 0; } CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal; function eventMixin(ctor) { ctor.prototype.on = function(type, f) {on(this, type, f);}; ctor.prototype.off = function(type, f) {off(this, type, f);}; } // MISC UTILITIES // Number of pixels added to scroller and sizer to hide scrollbar var scrollerCutOff = 30; // Returned or thrown by various protocols to signal 'I'm not // handling this'. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; function Delayed() {this.id = null;} Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}}; // 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; i < end; ++i) { if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); else ++n; } return n; } CodeMirror.countColumn = countColumn; 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 selectInput(node) { if (ios) { // Mobile Safari apparently has a bug where select() is broken. node.selectionStart = 0; node.selectionEnd = node.value.length; } else { // Suppress mysterious IE10 errors try { node.select(); } catch(_e) {} } } function indexOf(collection, elt) { if (collection.indexOf) return collection.indexOf(elt); for (var i = 0, e = collection.length; i < e; ++i) if (collection[i] == elt) return i; return -1; } function createObj(base, props) { function Obj() {} Obj.prototype = base; var inst = new Obj(); if (props) copyObj(props, inst); return inst; } function copyObj(obj, target) { if (!target) target = {}; for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop]; return target; } function emptyArray(size) { for (var a = [], i = 0; i < size; ++i) a.push(undefined); return a; } function bind(f) { var args = Array.prototype.slice.call(arguments, 1); return function(){return f.apply(null, args);}; } var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; function isWordChar(ch) { return /\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); } function isEmpty(obj) { for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; return true; } var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F\udc00-\udfff]/; // DOM UTILITIES 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") setTextContent(e, content); else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); return e; } 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 setTextContent(e, str) { if (ie_lt9) { e.innerHTML = ""; e.appendChild(document.createTextNode(str)); } else e.textContent = str; } function getRect(node) { return node.getBoundingClientRect(); } CodeMirror.replaceGetRect = function(f) { getRect = f; }; // FEATURE DETECTION // 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_lt9) return false; var div = elt('div'); return "draggable" in div || "dragDrop" in div; }(); // For a reason I have yet to figure out, some browsers disallow // word wrapping between certain characters *only* if a new inline // element is started between them. This makes it hard to reliably // measure the position of things, since that requires inserting an // extra span. This terribly fragile set of tests matches the // character combinations that suffer from this phenomenon on the // various browsers. function spanAffectsWrapping() { return false; } if (gecko) // Only for "$'" spanAffectsWrapping = function(str, i) { return str.charCodeAt(i - 1) == 36 && str.charCodeAt(i) == 39; }; else if (safari && !/Version\/([6-9]|\d\d)\b/.test(navigator.userAgent)) spanAffectsWrapping = function(str, i) { return /\-[^ \-?]|\?[^ !\'\"\),.\-\/:;\?\]\}]/.test(str.slice(i - 1, i + 1)); }; else if (webkit && /Chrome\/(?:29|[3-9]\d|\d\d\d)\./.test(navigator.userAgent)) spanAffectsWrapping = function(str, i) { var code = str.charCodeAt(i - 1); return code >= 8208 && code <= 8212; }; else if (webkit) spanAffectsWrapping = function(str, i) { if (i > 1 && str.charCodeAt(i - 1) == 45) { if (/\w/.test(str.charAt(i - 2)) && /[^\-?\.]/.test(str.charAt(i))) return true; if (i > 2 && /[\d\.,]/.test(str.charAt(i - 2)) && /[\d\.,]/.test(str.charAt(i))) return false; } return /[~!#%&*)=+}\]\\|\"\.>,:;][({[<]|-[^\-?\.\u2010-\u201f\u2026]|\?[\w~`@#$%\^&*(_=+{[|><]|…[\w~`@#$%\^&*(_=+{[><]/.test(str.slice(i - 1, i + 1)); }; var knownScrollbarWidth; function scrollbarWidth(measure) { if (knownScrollbarWidth != null) return knownScrollbarWidth; var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll"); removeChildrenAndAdd(measure, test); if (test.offsetWidth) knownScrollbarWidth = test.offsetHeight - test.clientHeight; return knownScrollbarWidth || 0; } 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_lt8; } if (zwspSupported) return elt("span", "\u200b"); else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); } // See if "".split is the broken IE version, if so, provide an // alternative way to split lines. var splitLines = "\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/);}; CodeMirror.splitLines = splitLines; var hasSelection = window.getSelection ? function(te) { try { return te.selectionStart != te.selectionEnd; } catch(e) { return false; } } : function(te) { try {var 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'; })(); // KEY NAMING var keyNames = {3: "Enter", 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: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home", 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"}; CodeMirror.keyNames = keyNames; (function() { // Number keys for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i); // Alphabetic keys for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); // Function keys for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; })(); // BIDI HELPERS function iterateBidiSections(order, from, to, f) { if (!order) return f(from, to, "ltr"); 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"); found = true; } } if (!found) f(from, to, "ltr"); } function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } function bidiRight(part) { return part.level % 2 ? part.from : part.to; } function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } function lineRight(line) { var order = getOrder(line); if (!order) return line.text.length; return bidiRight(lst(order)); } function lineStart(cm, lineN) { var line = getLine(cm.doc, lineN); var visual = visualLine(cm.doc, line); if (visual != line) lineN = lineNo(visual); var order = getOrder(visual); var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); return Pos(lineN, ch); } function lineEnd(cm, lineN) { var merged, line; while (merged = collapsedSpanAtEnd(line = getLine(cm.doc, lineN))) lineN = merged.find().to.line; var order = getOrder(line); var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); return Pos(lineN, ch); } function compareBidiLevel(order, a, b) { var linedir = order[0].level; if (a == linedir) return true; if (b == linedir) return false; return a < b; } var bidiOther; function getBidiPartAt(order, pos) { for (var i = 0, found; i < order.length; ++i) { var cur = order[i]; if (cur.from < pos && cur.to > pos) { bidiOther = null; return i; } if (cur.from == pos || cur.to == pos) { if (found == null) { found = i; } else if (compareBidiLevel(order, cur.level, order[found].level)) { bidiOther = found; return i; } else { bidiOther = i; return found; } } } bidiOther = null; return found; } function moveInLine(line, pos, dir, byUnit) { if (!byUnit) return pos + dir; do pos += dir; while (pos > 0 && isExtendingChar.test(line.text.charAt(pos))); return pos; } // This is somewhat involved. It is needed in order to move // 'visually' through bi-directional text -- i.e., pressing left // should make the cursor go left, even when in RTL text. The // tricky part is the 'jumps', where RTL and LTR text touch each // other. This often requires the cursor offset to move more than // one unit, in order to visually move one unit. function moveVisually(line, start, dir, byUnit) { var bidi = getOrder(line); if (!bidi) return moveLogically(line, start, dir, byUnit); var pos = getBidiPartAt(bidi, start), part = bidi[pos]; var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); for (;;) { if (target > part.from && target < part.to) return target; if (target == part.from || target == part.to) { if (getBidiPartAt(bidi, target) == pos) return target; part = bidi[pos += dir]; return (dir > 0) == part.level % 2 ? part.to : part.from; } else { part = bidi[pos += dir]; if (!part) return null; if ((dir > 0) == part.level % 2) target = moveInLine(line, part.to, -1, byUnit); else target = moveInLine(line, part.from, 1, byUnit); } } } function moveLogically(line, start, dir, byUnit) { var target = start + dir; if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir; return target < 0 || target > line.text.length ? null : target; } // 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%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL"; // Character types for codepoints 0x600 to 0x6ff var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr"; function charType(code) { if (code <= 0xff) return lowTypes.charAt(code); else if (0x590 <= code && code <= 0x5f4) return "R"; else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600); else if (0x700 <= code && code <= 0x8ac) return "r"; else return "L"; } var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; // Browsers seem to always treat the boundaries of block elements as being L. var outerType = "L"; return function(str) { if (!bidiRE.test(str)) return false; var len = str.length, types = []; for (var i = 0, type; i < len; ++i) types.push(type = 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 = 0, prev = outerType; i < len; ++i) { var type = types[i]; if (type == "m") types[i] = prev; else prev = type; } // W2. Search backwards from each instance of a European number // until the first strong type (R, L, AL, or sor) is found. If an // AL is found, change the type of the European number to Arabic // number. // W3. Change all ALs to R. for (var i = 0, cur = outerType; i < len; ++i) { var type = types[i]; if (type == "1" && cur == "r") types[i] = "n"; else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } } // W4. A single European separator between two European numbers // changes to a European number. A single common separator between // two numbers of the same type changes to that type. for (var i = 1, prev = types[0]; i < len - 1; ++i) { var type = types[i]; if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; else if (type == "," && prev == types[i+1] && (prev == "1" || prev == "n")) types[i] = prev; prev = type; } // W5. A sequence of European terminators adjacent to European // numbers changes to all European numbers. // W6. Otherwise, separators and terminators change to Other // Neutral. for (var i = 0; i < len; ++i) { var type = types[i]; if (type == ",") types[i] = "N"; else if (type == "%") { for (var end = i + 1; end < len && types[end] == "%"; ++end) {} var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N"; for (var j = i; j < end; ++j) types[j] = replace; i = end - 1; } } // W7. Search backwards from each instance of a European number // until the first strong type (R, L, or sor) is found. If an L is // found, then change the type of the European number to L. for (var i = 0, cur = outerType; i < len; ++i) { var type = types[i]; if (cur == "L" && type == "1") types[i] = "L"; else if (isStrong.test(type)) cur = type; } // N1. A sequence of neutrals takes the direction of the // surrounding strong text if the text on both sides has the same // direction. European and Arabic numbers act as if they were R in // terms of their influence on neutrals. Start-of-level-run (sor) // and end-of-level-run (eor) are used at level run boundaries. // N2. Any remaining neutrals take the embedding direction. for (var i = 0; i < len; ++i) { if (isNeutral.test(types[i])) { for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} var before = (i ? types[i-1] : outerType) == "L"; var after = (end < len - 1 ? types[end] : outerType) == "L"; var replace = before || after ? "L" : "R"; for (var j = i; j < end; ++j) types[j] = replace; i = end - 1; } } // Here we depart from the documented algorithm, in order to avoid // building up an actual levels array. Since there are only three // levels (0, 1, 2) in an implementation that doesn't take // explicit embedding into account, we can build up the order on // the fly, without following the level-based algorithm. var order = [], m; for (var i = 0; i < len;) { if (countsAsLeft.test(types[i])) { var start = i; for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} order.push({from: start, to: i, level: 0}); } else { var pos = i, at = order.length; for (++i; i < len && types[i] != "L"; ++i) {} for (var j = pos; j < i;) { if (countsAsNum.test(types[j])) { if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1}); var nstart = j; for (++j; j < i && countsAsNum.test(types[j]); ++j) {} order.splice(at, 0, {from: nstart, to: j, level: 2}); pos = j; } else ++j; } if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1}); } } if (order[0].level == 1 && (m = str.match(/^\s+/))) { order[0].from = m[0].length; order.unshift({from: 0, to: m[0].length, level: 0}); } if (lst(order).level == 1 && (m = str.match(/\s+$/))) { lst(order).to -= m[0].length; order.push({from: len - m[0].length, to: len, level: 0}); } if (order[0].level != lst(order).level) order.push({from: len, to: len, level: order[0].level}); return order; }; })(); // THE END CodeMirror.version = "3.19.0"; return CodeMirror; })(); ================================================ FILE: public/packages/codemirror-3.19/mode/apl/apl.js ================================================ 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/apl/index.html ================================================ CodeMirror: APL mode

            APL mode

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

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

            MIME types defined: text/apl (APL code)

            ================================================ FILE: public/packages/codemirror-3.19/mode/asterisk/asterisk.js ================================================ /* * ===================================================================================== * * 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/asterisk/index.html ================================================ CodeMirror: Asterisk dialplan mode

            Asterisk dialplan mode

            MIME types defined: text/x-asterisk.

            ================================================ FILE: public/packages/codemirror-3.19/mode/clike/clike.js ================================================ 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 (ctx.align && (!dontAlignCalls || ctx.type != ")")) return ctx.column + (closing ? 0 : 1); else if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit; else return ctx.indented + (closing ? 0 : indentUnit); }, electricChars: "{}", blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: "//", fold: "brace" }; }); (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"; } } }); mimes(["x-shader/x-vertex", "x-shader/x-fragment"], { name: "clike", keywords: words("float int bool void " + "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " + "mat2 mat3 mat4 " + "sampler1D sampler2D sampler3D samplerCube " + "sampler1DShadow sampler2DShadow" + "const attribute uniform varying " + "break continue discard return " + "for while do if else struct " + "in out inout"), blockKeywords: words("for while do if else struct"), builtin: words("radians degrees sin cos tan asin acos atan " + "pow exp log exp2 sqrt inversesqrt " + "abs sign floor ceil fract mod min max clamp mix step smootstep " + "length distance dot cross normalize ftransform faceforward " + "reflect refract matrixCompMult " + "lessThan lessThanEqual greaterThan greaterThanEqual " + "equal notEqual any all not " + "texture1D texture1DProj texture1DLod texture1DProjLod " + "texture2D texture2DProj texture2DLod texture2DProjLod " + "texture3D texture3DProj texture3DLod texture3DProjLod " + "textureCube textureCubeLod " + "shadow1D shadow2D shadow1DProj shadow2DProj " + "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " + "dFdx dFdy fwidth " + "noise1 noise2 noise3 noise4"), atoms: words("true false " + "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " + "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " + "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " + "gl_FogCoord " + "gl_Position gl_PointSize gl_ClipVertex " + "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " + "gl_TexCoord gl_FogFragCoord " + "gl_FragCoord gl_FrontFacing " + "gl_FragColor gl_FragData gl_FragDepth " + "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " + "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " + "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " + "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " + "gl_ProjectionMatrixInverseTranspose " + "gl_ModelViewProjectionMatrixInverseTranspose " + "gl_TextureMatrixInverseTranspose " + "gl_NormalScale gl_DepthRange gl_ClipPlane " + "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " + "gl_FrontLightModelProduct gl_BackLightModelProduct " + "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " + "gl_FogParameters " + "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " + "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " + "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " + "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " + "gl_MaxDrawBuffers"), hooks: {"#": cppHook} }); }()); ================================================ FILE: public/packages/codemirror-3.19/mode/clike/index.html ================================================ CodeMirror: C-like mode

            C-like mode

            C++ example

            Java example

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/clike/scala.html ================================================ CodeMirror: Scala mode

            Scala mode

            ================================================ FILE: public/packages/codemirror-3.19/mode/clojure/clojure.js ================================================ /** * 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", CHARACTER = "string-2", 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* *compiler-options* *data-readers* *e *err* *file* *flush-on-newline* *fn-loader* *in* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *unchecked-math* *use-context-classloader* *verbose-defrecords* *warn-on-reflection* + +' - -' -> ->> ->ArrayChunk ->Vec ->VecNode ->VecSeq -cache-protocol-fn -reset-methods .. / < <= = == > >= EMPTY-NODE accessor aclone add-classpath add-watch agent agent-error agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and 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 biginteger binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* bound? 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 dec' decimal? declare default-data-readers definline definterface defmacro defmethod defmulti defn defn- defonce defprotocol defrecord defstruct deftype delay delay? deliver denominator deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq error-handler error-mode eval even? every-pred every? ex-data ex-info extend extend-protocol extend-type extenders extends? false? ffirst file-seq filter filterv find find-keyword find-ns find-protocol-impl find-protocol-method find-var first flatten float float-array float? floats flush fn fn? fnext fnil for force format frequencies future future-call future-cancel future-cancelled? future-done? future? gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator group-by hash hash-combine hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc inc' init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt keep keep-indexed key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array make-hierarchy map map-indexed map? mapcat mapv max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod munge name namespace namespace-munge neg? newline next nfirst nil? nnext not not-any? not-empty not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap nth nthnext nthrest num number? numerator object-array odd? or parents partial partition partition-all partition-by pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-dup print-method print-simple print-str printf println println-str prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot rand rand-int rand-nth range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string realized? reduce reduce-kv reductions ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure reify release-pending-sends rem remove remove-all-methods remove-method remove-ns remove-watch repeat repeatedly replace replicate require reset! reset-meta! resolve rest restart-agent resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? seque sequence sequential? set set-error-handler! set-error-mode! set-validator! set? short short-array shorts shuffle shutdown-agents slurp some some-fn sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-symbol? spit split-at split-with str string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync take take-last take-nth take-while test the-ns thread-bound? time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-add-int unchecked-byte unchecked-char unchecked-dec unchecked-dec-int unchecked-divide-int unchecked-double unchecked-float unchecked-inc unchecked-inc-int unchecked-int unchecked-long unchecked-multiply unchecked-multiply-int unchecked-negate unchecked-negate-int unchecked-remainder-int unchecked-short unchecked-subtract unchecked-subtract-int underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector-of 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 with-redefs with-redefs-fn xml-seq zero? zipmap *default-data-reader-fn* as-> cond-> cond->> reduced reduced? send-via set-agent-send-executor! set-agent-send-off-executor! some-> some->>"); 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\(\[\;\)\]]/, symbol: /[\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; } // Eat character that starts after backslash \ function eatCharacter(stream) { var first = stream.next(); // Read special literals: backspace, newline, space, return. // Just read all lowercase letters. if (first.match(/[a-z]/) && stream.match(/[a-z]+/, true)) { return; } // Read unicode character: \u1000 \uA0a1 if (first === "u") { stream.match(/[0-9a-z]{4}/i, true); } } 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 == "\\") { eatCharacter(stream); returnType = CHARACTER; } 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.symbol); return ATOM; } else { stream.eatWhile(tests.symbol); 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; }, lineComment: ";;" }; }); CodeMirror.defineMIME("text/x-clojure", "clojure"); ================================================ FILE: public/packages/codemirror-3.19/mode/clojure/index.html ================================================ CodeMirror: Clojure mode

            Clojure mode

            MIME types defined: text/x-clojure.

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

            COBOL mode

            Select Theme Select Font Size

            ================================================ FILE: public/packages/codemirror-3.19/mode/coffeescript/coffeescript.js ================================================ /** * 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 operators = /^(?:->|=>|\+[+=]?|-[\-=]?|\*[\*=]?|\/[\/=]?|[=!]=|<[><]?=?|>>?=?|%=?|&=?|\|=?|\^=?|\~|!|\?)/; var delimiters = /^(?:[()\[\]{},:`=;]|\.\.?\.?)/; var identifiers = /^[_A-Za-z$][_A-Za-z$0-9]*/; var properties = /^(@|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 = /^('{3}|\"{3}|['\"])/; var regexPrefixes = /^(\/{3}|\/)/; var commonConstants = ["Infinity", "NaN", "undefined", "null", "true", "false", "on", "off", "yes", "no"]; var constants = wordRegexp(commonConstants); // Tokenizers function tokenBase(stream, state) { // Handle scope changes if (stream.sol()) { if (state.scope.align === null) state.scope.align = false; var scopeOffset = state.scope.offset; if (stream.eatSpace()) { var lineOffset = stream.indentation(); if (lineOffset > scopeOffset && state.scope.type == "coffee") { return "indent"; } else if (lineOffset < scopeOffset) { return "dedent"; } return null; } else { if (scopeOffset > 0) { dedent(stream, state); } } } if (stream.eatSpace()) { return null; } var ch = stream.peek(); // Handle docco title comment (single line) if (stream.match("####")) { stream.skipToEnd(); return "comment"; } // Handle multi line comments if (stream.match("###")) { state.tokenize = longComment; return state.tokenize(stream, state); } // Single line comment if (ch === "#") { stream.skipToEnd(); return "comment"; } // Handle number literals if (stream.match(/^-?[0-9\.]/, false)) { var floatLiteral = false; // Floats if (stream.match(/^-?\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; } if (stream.match(/^-?\d+\.\d*/)) { floatLiteral = true; } if (stream.match(/^-?\.\d+/)) { floatLiteral = true; } if (floatLiteral) { // prevent from getting extra . on 1.. if (stream.peek() == "."){ stream.backUp(1); } return "number"; } // Integers var intLiteral = false; // Hex if (stream.match(/^-?0x[0-9a-f]+/i)) { intLiteral = true; } // Decimal if (stream.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)) { intLiteral = true; } // Zero by itself with no other piece of number. if (stream.match(/^-?0(?![\dx])/i)) { intLiteral = true; } if (intLiteral) { return "number"; } } // Handle strings if (stream.match(stringPrefixes)) { state.tokenize = tokenFactory(stream.current(), "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(operators) || stream.match(wordOperators)) { return "operator"; } if (stream.match(delimiters)) { 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 offset = 0, align = false, alignOffset = null; for (var scope = state.scope; scope; scope = scope.prev) { if (scope.type === "coffee") { offset = scope.offset + conf.indentUnit; break; } } if (type !== "coffee") { align = null; alignOffset = stream.column() + stream.current().length; } state.scope = { offset: offset, type: type, prev: state.scope, align: align, alignOffset: alignOffset }; } function dedent(stream, state) { if (!state.scope.prev) return; if (state.scope.type === "coffee") { var _indent = stream.indentation(); var matched = false; for (var scope = state.scope; scope; scope = scope.prev) { if (_indent === scope.offset) { matched = true; break; } } if (!matched) { return true; } while (state.scope.prev && state.scope.offset !== _indent) { state.scope = state.scope.prev; } return false; } else { state.scope = state.scope.prev; return false; } } function tokenLexer(stream, state) { var style = state.tokenize(stream, state); var current = stream.current(); // Handle "." connected identifiers if (current === ".") { style = state.tokenize(stream, state); current = stream.current(); if (/^\.[\w$]+$/.test(current)) { return "variable"; } else { return ERRORCLASS; } } // Handle scope changes. if (current === "return") { state.dedent += 1; } if (((current === "->" || current === "=>") && !state.lambda && state.scope.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.scope.type == "coffee") { if (state.scope.prev) state.scope = state.scope.prev; state.dedent -= 1; } return style; } var external = { startState: function(basecolumn) { return { tokenize: tokenBase, scope: {offset:basecolumn || 0, type:"coffee", prev: null, align: false}, lastToken: null, lambda: false, dedent: 0 }; }, token: function(stream, state) { var fillAlign = state.scope.align === null && state.scope; if (fillAlign && stream.sol()) fillAlign.align = false; var style = tokenLexer(stream, state); if (fillAlign && style && style != "comment") fillAlign.align = true; state.lastToken = {style:style, content: stream.current()}; if (stream.eol() && stream.lambda) { state.lambda = false; } return style; }, indent: function(state, text) { if (state.tokenize != tokenBase) return 0; var closes = state.scope.type === (text && text.charAt(0)); if (state.scope.align) return state.scope.alignOffset - (closes ? 1 : 0); else return (closes ? state.scope.prev : state.scope).offset; }, lineComment: "#", fold: "indent" }; return external; }); CodeMirror.defineMIME("text/x-coffeescript", "coffeescript"); ================================================ FILE: public/packages/codemirror-3.19/mode/coffeescript/index.html ================================================ CodeMirror: CoffeeScript mode

            CoffeeScript mode

            MIME types defined: text/x-coffeescript.

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/commonlisp/commonlisp.js ================================================ 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; }, lineComment: ";;", blockCommentStart: "#|", blockCommentEnd: "|#" }; }); CodeMirror.defineMIME("text/x-common-lisp", "commonlisp"); ================================================ FILE: public/packages/codemirror-3.19/mode/commonlisp/index.html ================================================ CodeMirror: Common Lisp mode

            Common Lisp mode

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/css/css.js ================================================ CodeMirror.defineMode("css", function(config, parserConfig) { "use strict"; if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css"); var indentUnit = config.indentUnit || config.tabSize || 2, hooks = parserConfig.hooks || {}, atMediaTypes = parserConfig.atMediaTypes || {}, atMediaFeatures = parserConfig.atMediaFeatures || {}, propertyKeywords = parserConfig.propertyKeywords || {}, colorKeywords = parserConfig.colorKeywords || {}, valueKeywords = parserConfig.valueKeywords || {}, allowNested = !!parserConfig.allowNested, type = null; function ret(style, tp) { type = tp; return style; } function tokenBase(stream, state) { var ch = stream.next(); if (hooks[ch]) { // result[0] is style and result[1] is type var result = hooks[ch](stream, state); if (result !== false) return result; } if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("def", stream.current());} 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) || ch == "." && stream.eat(/\d/)) { stream.eatWhile(/[\w.%]/); return ret("number", "unit"); } else if (ch === "-") { if (/\d/.test(stream.peek())) { stream.eatWhile(/[\w.%]/); return ret("number", "unit"); } else if (stream.match(/^[^-]+-/)) { 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 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: [], lastToken: null}; }, 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. state.tokenize = state.tokenize || tokenBase; if (state.tokenize == tokenBase && stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (style && typeof style != "string") style = ret(style[0], style[1]); // Changing style returned based on context var context = state.stack[state.stack.length-1]; if (style == "variable") { if (type == "variable-definition") state.stack.push("propertyValue"); return state.lastToken = "variable-2"; } else if (style == "property") { var word = stream.current().toLowerCase(); if (context == "propertyValue") { if (valueKeywords.hasOwnProperty(word)) { style = "string-2"; } else if (colorKeywords.hasOwnProperty(word)) { style = "keyword"; } else { style = "variable-2"; } } else if (context == "rule") { if (!propertyKeywords.hasOwnProperty(word)) { style += " error"; } } else if (context == "block") { // if a value is present in both property, value, or color, the order // of preference is property -> color -> value if (propertyKeywords.hasOwnProperty(word)) { style = "property"; } else if (colorKeywords.hasOwnProperty(word)) { style = "keyword"; } else if (valueKeywords.hasOwnProperty(word)) { style = "string-2"; } else { style = "tag"; } } else if (!context || context == "@media{") { style = "tag"; } else if (context == "@media") { if (atMediaTypes[stream.current()]) { style = "attribute"; // Known attribute } else if (/^(only|not)$/.test(word)) { style = "keyword"; } else if (word == "and") { style = "error"; // "and" is only allowed in @mediaType } else if (atMediaFeatures.hasOwnProperty(word)) { 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.hasOwnProperty(word)) { style = "attribute"; } else if (word == "and") { style = "operator"; } else if (/^(only|not)$/.test(word)) { style = "error"; // Only allowed in @media } else { // Unknown attribute or property, but expecting property (preceded // by "and"). Should be in parentheses style = "error"; } } else if (context == "@mediaType(") { if (propertyKeywords.hasOwnProperty(word)) { // do nothing, remains "property" } else if (atMediaTypes.hasOwnProperty(word)) { style = "error"; // Known property, should be in parentheses } else if (word == "and") { style = "operator"; } else if (/^(only|not)$/.test(word)) { style = "error"; // Only allowed in @media } else { style += " error"; } } else if (context == "@import") { style = "tag"; } else { style = "error"; } } else if (style == "atom") { if(!context || context == "@media{" || context == "block") { 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[state.stack.length-1] = "@media{"; } else { var newContext = allowNested ? "block" : "rule"; state.stack.push(newContext); } } else if (type == "}") { if (context == "interpolation") style = "operator"; // Pop off end of array until { is reached while(state.stack.length){ var removed = state.stack.pop(); if(removed.indexOf("{") > -1){ break; } } } else if (type == "interpolation") state.stack.push("interpolation"); else if (type == "@media") state.stack.push("@media"); else if (type == "@import") state.stack.push("@import"); else if (context == "@media" && /\b(keyword|attribute)\b/.test(style)) state.stack[state.stack.length-1] = "@mediaType"; else if (context == "@mediaType" && stream.current() == ",") state.stack[state.stack.length-1] = "@media"; else if (type == "(") { if (context == "@media" || context == "@mediaType") { // Make sure @mediaType is used to avoid error on { state.stack[state.stack.length-1] = "@mediaType"; state.stack.push("@mediaType("); } else state.stack.push("("); } else if (type == ")") { // Pop off end of array until ( is reached while(state.stack.length){ var removed = state.stack.pop(); if(removed.indexOf("(") > -1){ break; } } } else if (type == ":" && state.lastToken == "property") state.stack.push("propertyValue"); else if (context == "propertyValue" && type == ";") state.stack.pop(); else if (context == "@import" && type == ";") state.stack.pop(); return state.lastToken = style; }, indent: function(state, textAfter) { var n = state.stack.length; if (/^\}/.test(textAfter)) n -= state.stack[n-1] == "propertyValue" ? 2 : 1; return state.baseIndent + n * indentUnit; }, electricChars: "}", blockCommentStart: "/*", blockCommentEnd: "*/", fold: "brace" }; }); (function() { function keySet(array) { var keys = {}; for (var i = 0; i < array.length; ++i) { keys[array[i]] = true; } return keys; } 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", "flow-from", "flow-into", "font", "font-feature-settings", "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-synthesis", "font-variant", "font-variant-alternates", "font-variant-caps", "font-variant-east-asian", "font-variant-ligatures", "font-variant-numeric", "font-variant-position", "font-weight", "grid-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", "region-break-after", "region-break-before", "region-break-inside", "region-fragment", "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness", "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang", "ruby-position", "ruby-span", "shape-inside", "shape-outside", "size", "speak", "speak-as", "speak-header", "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set", "tab-size", "table-layout", "target", "target-name", "target-new", "target-position", "text-align", "text-align-last", "text-decoration", "text-decoration-color", "text-decoration-line", "text-decoration-skip", "text-decoration-style", "text-emphasis", "text-emphasis-color", "text-emphasis-position", "text-emphasis-style", "text-height", "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow", "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position", "text-wrap", "top", "transform", "transform-origin", "transform-style", "transition", "transition-delay", "transition-duration", "transition-property", "transition-timing-function", "unicode-bidi", "vertical-align", "visibility", "voice-balance", "voice-duration", "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress", "voice-volume", "volume", "white-space", "widows", "width", "word-break", "word-spacing", "word-wrap", "z-index", "zoom", // SVG-specific "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color", "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering", "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering", "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal", "glyph-orientation-vertical", "kerning", "text-anchor", "writing-mode" ]); var colorKeywords = keySet([ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen" ]); var valueKeywords = 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", "avoid-column", "avoid-page", "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary", "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box", "both", "bottom", "break", "break-all", "break-word", "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", "column", "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", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", "ethiopic-halehame-gez", "ethiopic-halehame-om-et", "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig", "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", "keep-all", "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", "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", "outside-shape", "overlay", "overline", "padding", "padding-box", "painted", "page", "paused", "persian", "plus-darker", "plus-lighter", "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button", "radio", "read-only", "read-write", "read-write-plaintext-only", "rectangle", "region", "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", "wider", "window", "windowframe", "windowtext", "x-large", "x-small", "xor", "xx-large", "xx-small" ]); function tokenCComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (maybeEnd && ch == "/") { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return ["comment", "comment"]; } CodeMirror.defineMIME("text/css", { atMediaTypes: atMediaTypes, atMediaFeatures: atMediaFeatures, propertyKeywords: propertyKeywords, colorKeywords: colorKeywords, valueKeywords: valueKeywords, hooks: { "<": function(stream, state) { function tokenSGMLComment(stream, state) { var dashes = 0, ch; while ((ch = stream.next()) != null) { if (dashes >= 2 && ch == ">") { state.tokenize = null; break; } dashes = (ch == "-") ? dashes + 1 : 0; } return ["comment", "comment"]; } if (stream.eat("!")) { state.tokenize = tokenSGMLComment; return tokenSGMLComment(stream, state); } }, "/": function(stream, state) { if (stream.eat("*")) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } return false; } }, name: "css" }); CodeMirror.defineMIME("text/x-scss", { atMediaTypes: atMediaTypes, atMediaFeatures: atMediaFeatures, propertyKeywords: propertyKeywords, colorKeywords: colorKeywords, valueKeywords: valueKeywords, allowNested: true, hooks: { ":": function(stream) { if (stream.match(/\s*{/)) { return [null, "{"]; } return false; }, "$": function(stream) { stream.match(/^[\w-]+/); if (stream.peek() == ":") { return ["variable", "variable-definition"]; } return ["variable", "variable"]; }, ",": function(_stream, state) { if (state.stack[state.stack.length - 1] == "propertyValue") { return ["operator", ";"]; } }, "/": function(stream, state) { if (stream.eat("/")) { stream.skipToEnd(); return ["comment", "comment"]; } else if (stream.eat("*")) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } else { return ["operator", "operator"]; } }, "#": function(stream) { if (stream.eat("{")) { return ["operator", "interpolation"]; } else { stream.eatWhile(/[\w\\\-]/); return ["atom", "hash"]; } } }, name: "css" }); })(); ================================================ FILE: public/packages/codemirror-3.19/mode/css/index.html ================================================ CodeMirror: CSS mode

            CSS mode

            MIME types defined: text/css.

            Parsing/Highlighting Tests: normal, verbose.

            ================================================ FILE: public/packages/codemirror-3.19/mode/css/scss.html ================================================ CodeMirror: SCSS mode

            SCSS mode

            MIME types defined: text/scss.

            Parsing/Highlighting Tests: normal, verbose.

            ================================================ FILE: public/packages/codemirror-3.19/mode/css/scss_test.js ================================================ (function() { var mode = CodeMirror.getMode({tabSize: 1}, "text/x-scss"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "scss"); } function IT(name) { test.indentation(name, mode, Array.prototype.slice.call(arguments, 1), "scss"); } MT('url_with_quotation', "[tag foo] { [property background][operator :][string-2 url]([string test.jpg]) }"); MT('url_with_double_quotes', "[tag foo] { [property background][operator :][string-2 url]([string \"test.jpg\"]) }"); MT('url_with_single_quotes', "[tag foo] { [property background][operator :][string-2 url]([string \'test.jpg\']) }"); MT('string', "[def @import] [string \"compass/css3\"]"); MT('important_keyword', "[tag foo] { [property background][operator :][string-2 url]([string \'test.jpg\']) [keyword !important] }"); MT('variable', "[variable-2 $blue][operator :][atom #333]"); MT('variable_as_attribute', "[tag foo] { [property color][operator :][variable-2 $blue] }"); MT('numbers', "[tag foo] { [property padding][operator :][number 10px] [number 10] [number 10em] [number 8in] }"); MT('number_percentage', "[tag foo] { [property width][operator :][number 80%] }"); MT('selector', "[builtin #hello][qualifier .world]{}"); MT('singleline_comment', "[comment // this is a comment]"); MT('multiline_comment', "[comment /*foobar*/]"); MT('attribute_with_hyphen', "[tag foo] { [property font-size][operator :][number 10px] }"); MT('string_after_attribute', "[tag foo] { [property content][operator :][string \"::\"] }"); MT('directives', "[def @include] [qualifier .mixin]"); MT('basic_structure', "[tag p] { [property background][operator :][keyword red]; }"); MT('nested_structure', "[tag p] { [tag a] { [property color][operator :][keyword red]; } }"); MT('mixin', "[def @mixin] [tag table-base] {}"); MT('number_without_semicolon', "[tag p] {[property width][operator :][number 12]}", "[tag a] {[property color][operator :][keyword red];}"); MT('atom_in_nested_block', "[tag p] { [tag a] { [property color][operator :][atom #000]; } }"); MT('interpolation_in_property', "[tag foo] { [operator #{][variable-2 $hello][operator }:][number 2]; }"); MT('interpolation_in_selector', "[tag foo][operator #{][variable-2 $hello][operator }] { [property color][operator :][atom #000]; }"); MT('interpolation_error', "[tag foo][operator #{][error foo][operator }] { [property color][operator :][atom #000]; }"); MT("divide_operator", "[tag foo] { [property width][operator :][number 4] [operator /] [number 2] }"); MT('nested_structure_with_id_selector', "[tag p] { [builtin #hello] { [property color][operator :][keyword red]; } }"); IT('mixin', "@mixin container[1 (][2 $a: 10][1 , ][2 $b: 10][1 , ][2 $c: 10]) [1 {]}"); })(); ================================================ FILE: public/packages/codemirror-3.19/mode/css/test.js ================================================ (function() { var mode = CodeMirror.getMode({tabSize: 1}, "css"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } function IT(name) { test.indentation(name, mode, Array.prototype.slice.call(arguments, 1)); } // 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("atMediaPropertyOnly", "[def @media] ([property color]) { } [tag foo] { }"); MT("atMediaCheckStackInvalidAttribute", "[def @media] [attribute&error foobarhello] { [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]) { }"); // Make sure nesting works with media queries MT("atMediaMaxWidthNested", "[def @media] [attribute screen] [operator and] ([property max-width][operator :] [number 25px]) { [tag foo] { } }"); 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];" + "[property color][operator :] [keyword navy];" + "[property color][operator :] [keyword yellow];" + "}"); 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]; }"); MT("tagTwoPropertiesURL", "[tag foo] { [property background][operator :] [string-2 url]([string //example.com/foo.png]); [property padding][operator :] [number 0]; }"); MT("commentSGML", "[comment ]"); IT("tagSelector", "strong, em [1 { background][2 : rgba][3 (255, 255, 0, .2][2 )][1 ;]}"); })(); ================================================ FILE: public/packages/codemirror-3.19/mode/d/d.js ================================================ 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"; } } }); }()); ================================================ FILE: public/packages/codemirror-3.19/mode/d/index.html ================================================ CodeMirror: D mode

            D mode

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

            MIME types defined: text/x-d .

            ================================================ FILE: public/packages/codemirror-3.19/mode/diff/diff.js ================================================ CodeMirror.defineMode("diff", function() { var TOKEN_NAMES = { '+': 'positive', '-': 'negative', '@': 'meta' }; return { token: function(stream) { var tw_pos = stream.string.search(/[\t ]+?$/); if (!stream.sol() || tw_pos === 0) { stream.skipToEnd(); return ("error " + ( TOKEN_NAMES[stream.string.charAt(0)] || '')).replace(/ $/, ''); } var token_name = TOKEN_NAMES[stream.peek()] || stream.skipToEnd(); if (tw_pos === -1) { stream.skipToEnd(); } else { stream.pos = tw_pos; } return token_name; } }; }); CodeMirror.defineMIME("text/x-diff", "diff"); ================================================ FILE: public/packages/codemirror-3.19/mode/diff/index.html ================================================ CodeMirror: Diff mode

            Diff mode

            MIME types defined: text/x-diff.

            ================================================ FILE: public/packages/codemirror-3.19/mode/dtd/dtd.js ================================================ /* DTD mode Ported to CodeMirror by Peter Kroon Report bugs/issues here: https://github.com/marijnh/CodeMirror/issues GitHub: @peterkroon */ CodeMirror.defineMode("dtd", function(config) { var indentUnit = config.indentUnit, type; function ret(style, tp) {type = tp; return style;} function tokenBase(stream, state) { var ch = stream.next(); if (ch == "<" && stream.eat("!") ) { if (stream.eatWhile(/[\-]/)) { state.tokenize = tokenSGMLComment; return tokenSGMLComment(stream, state); } else if (stream.eatWhile(/[\w]/)) return ret("keyword", "doindent"); } else if (ch == "<" && stream.eat("?")) { //xml declaration state.tokenize = inBlock("meta", "?>"); return ret("meta", ch); } else if (ch == "#" && stream.eatWhile(/[\w]/)) return ret("atom", "tag"); else if (ch == "|") return ret("keyword", "seperator"); else if (ch.match(/[\(\)\[\]\-\.,\+\?>]/)) return ret(null, ch);//if(ch === ">") return ret(null, "endtag"); else else if (ch.match(/[\[\]]/)) return ret("rule", ch); else if (ch == "\"" || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (stream.eatWhile(/[a-zA-Z\?\+\d]/)) { var sc = stream.current(); if( sc.substr(sc.length-1,sc.length).match(/\?|\+/) !== null )stream.backUp(1); return ret("tag", "tag"); } else if (ch == "%" || ch == "*" ) return ret("number", "number"); else { stream.eatWhile(/[\w\\\-_%.{,]/); return ret(null, null); } } function tokenSGMLComment(stream, state) { var dashes = 0, ch; while ((ch = stream.next()) != null) { if (dashes >= 2 && ch == ">") { state.tokenize = tokenBase; break; } dashes = (ch == "-") ? dashes + 1 : 0; } return ret("comment", "comment"); } function tokenString(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) { state.tokenize = tokenBase; break; } escaped = !escaped && ch == "\\"; } return ret("string", "tag"); }; } function inBlock(style, terminator) { return function(stream, state) { while (!stream.eol()) { if (stream.match(terminator)) { state.tokenize = tokenBase; break; } stream.next(); } return style; }; } return { startState: function(base) { return {tokenize: tokenBase, baseIndent: base || 0, stack: []}; }, token: function(stream, state) { if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); var context = state.stack[state.stack.length-1]; if (stream.current() == "[" || type === "doindent" || type == "[") state.stack.push("rule"); else if (type === "endtag") state.stack[state.stack.length-1] = "endtag"; else if (stream.current() == "]" || type == "]" || (type == ">" && context == "rule")) state.stack.pop(); else if (type == "[") state.stack.push("["); return style; }, indent: function(state, textAfter) { var n = state.stack.length; if( textAfter.match(/\]\s+|\]/) )n=n-1; else if(textAfter.substr(textAfter.length-1, textAfter.length) === ">"){ if(textAfter.substr(0,1) === "<")n; else if( type == "doindent" && textAfter.length > 1 )n; else if( type == "doindent")n--; else if( type == ">" && textAfter.length > 1)n; else if( type == "tag" && textAfter !== ">")n; else if( type == "tag" && state.stack[state.stack.length-1] == "rule")n--; else if( type == "tag")n++; else if( textAfter === ">" && state.stack[state.stack.length-1] == "rule" && type === ">")n--; else if( textAfter === ">" && state.stack[state.stack.length-1] == "rule")n; else if( textAfter.substr(0,1) !== "<" && textAfter.substr(0,1) === ">" )n=n-1; else if( textAfter === ">")n; else n=n-1; //over rule them all if(type == null || type == "]")n--; } return state.baseIndent + n * indentUnit; }, electricChars: "]>" }; }); CodeMirror.defineMIME("application/xml-dtd", "dtd"); ================================================ FILE: public/packages/codemirror-3.19/mode/dtd/index.html ================================================ CodeMirror: DTD mode

            DTD mode

            MIME types defined: application/xml-dtd.

            ================================================ FILE: public/packages/codemirror-3.19/mode/ecl/ecl.js ================================================ 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/ecl/index.html ================================================ CodeMirror: ECL mode

            ECL mode

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

            MIME types defined: text/x-ecl.

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

            Eiffel mode

            MIME types defined: text/x-eiffel.

            Created by YNH.

            ================================================ FILE: public/packages/codemirror-3.19/mode/erlang/erlang.js ================================================ // 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 state.in_record = (type == "record"); // erlang -> CodeMirror tag switch (type) { case "atom": return "atom"; case "attribute": return "attribute"; case "boolean": return "special"; 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 separatorRE = /[\->\.,:;]/; var separatorWords = [ "->",";",":",".",","]; var operatorWords = [ "and","andalso","band","bnot","bor","bsl","bsr","bxor", "div","not","or","orelse","rem","xor"]; var symbolRE = /[\+\-\*\/<>=\|:!]/; var symbolWords = [ "+","-","*","/",">",">=","<","=<","=:=","==","=/=","/=","||","<-","!"]; var openParenRE = /[<\(\[\{]/; var openParenWords = [ "<<","(","[","{"]; var closeParenRE = /[>\)\]\}]/; var closeParenWords = [ "}","]",")",">>"]; var guardWords = [ "is_atom","is_binary","is_bitstring","is_boolean","is_float", "is_function","is_integer","is_list","is_number","is_pid", "is_port","is_record","is_reference","is_tuple", "atom","binary","bitstring","boolean","function","integer","list", "number","pid","port","record","reference","tuple"]; var bifWords = [ "abs","adler32","adler32_combine","alive","apply","atom_to_binary", "atom_to_list","binary_to_atom","binary_to_existing_atom", "binary_to_list","binary_to_term","bit_size","bitstring_to_list", "byte_size","check_process_code","contact_binary","crc32", "crc32_combine","date","decode_packet","delete_module", "disconnect_node","element","erase","exit","float","float_to_list", "garbage_collect","get","get_keys","group_leader","halt","hd", "integer_to_list","internal_bif","iolist_size","iolist_to_binary", "is_alive","is_atom","is_binary","is_bitstring","is_boolean", "is_float","is_function","is_integer","is_list","is_number","is_pid", "is_port","is_process_alive","is_record","is_reference","is_tuple", "length","link","list_to_atom","list_to_binary","list_to_bitstring", "list_to_existing_atom","list_to_float","list_to_integer", "list_to_pid","list_to_tuple","load_module","make_ref","module_loaded", "monitor_node","node","node_link","node_unlink","nodes","notalive", "now","open_port","pid_to_list","port_close","port_command", "port_connect","port_control","pre_loaded","process_flag", "process_info","processes","purge_module","put","register", "registered","round","self","setelement","size","spawn","spawn_link", "spawn_monitor","spawn_opt","split_binary","statistics", "term_to_binary","time","throw","tl","trunc","tuple_size", "tuple_to_list","unlink","unregister","whereis"]; // [Ø-Þ] [À-Ö] // [ß-ö] [ø-ÿ] var anumRE = /[\w@Ø-ÞÀ-Öß-öø-ÿ]/; var escapesRE = /[0-7]{1,3}|[bdefnrstv\\"']|\^[a-zA-Z]|x[0-9a-zA-Z]{2}|x{[0-9a-zA-Z]+}/; function tokenize(stream, state) { // in multi-line string if (state.in_string) { state.in_string = (!doubleQuote(stream)); return rval(state,stream,"string"); } // in multi-line atom if (state.in_atom) { state.in_atom = (!singleQuote(stream)); return rval(state,stream,"atom"); } // whitespace if (stream.eatSpace()) { return rval(state,stream,"whitespace"); } // attributes and type specs if ((peekToken(state).token == "") && stream.match(/-\s*[a-zß-öø-ÿ][\wØ-ÞÀ-Öß-öø-ÿ]*/)) { if (isMember(stream.current(),typeWords)) { return rval(state,stream,"type"); }else{ return rval(state,stream,"attribute"); } } var ch = stream.next(); // comment if (ch == '%') { stream.skipToEnd(); return rval(state,stream,"comment"); } // macro if (ch == '?') { stream.eatWhile(anumRE); return rval(state,stream,"macro"); } // record if (ch == "#") { stream.eatWhile(anumRE); return rval(state,stream,"record"); } // dollar escape if ( ch == "$" ) { if (stream.next() == "\\" && !stream.match(escapesRE)) { return rval(state,stream,"error"); } return rval(state,stream,"number"); } // quoted atom if (ch == '\'') { if (!(state.in_atom = (!singleQuote(stream)))) { if (stream.match(/\s*\/\s*[0-9]/,false)) { stream.match(/\s*\/\s*[0-9]/,true); popToken(state); return rval(state,stream,"fun"); // 'f'/0 style fun } if (stream.match(/\s*\(/,false) || stream.match(/\s*:/,false)) { return rval(state,stream,"function"); } } return rval(state,stream,"atom"); } // string if (ch == '"') { state.in_string = (!doubleQuote(stream)); return rval(state,stream,"string"); } // variable if (/[A-Z_Ø-ÞÀ-Ö]/.test(ch)) { stream.eatWhile(anumRE); return rval(state,stream,"variable"); } // atom/keyword/BIF/function if (/[a-z_ß-öø-ÿ]/.test(ch)) { stream.eatWhile(anumRE); if (stream.match(/\s*\/\s*[0-9]/,false)) { stream.match(/\s*\/\s*[0-9]/,true); popToken(state); return rval(state,stream,"fun"); // f/0 style fun } var w = stream.current(); if (isMember(w,keywordWords)) { pushToken(state,stream); return rval(state,stream,"keyword"); }else if (stream.match(/\s*\(/,false)) { // '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 if (isMember(w,guardWords)) { return rval(state,stream,"guard"); }else{ return rval(state,stream,"function"); } }else if (isMember(w,operatorWords)) { return rval(state,stream,"operator"); }else if (stream.match(/\s*:/,false)) { if (w == "erlang") { return rval(state,stream,"builtin"); } else { return rval(state,stream,"function"); } }else if (isMember(w,["true","false"])) { return rval(state,stream,"boolean"); }else{ return rval(state,stream,"atom"); } } // number var digitRE = /[0-9]/; var radixRE = /[0-9a-zA-Z]/; // 36#zZ style int if (digitRE.test(ch)) { stream.eatWhile(digitRE); if (stream.eat('#')) { stream.eatWhile(radixRE); // 36#aZ 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,separatorRE,separatorWords)) { // distinguish between "." as terminator and record field operator if (!state.in_record) { 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 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 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 isMember(element,list) { return (-1 < list.indexOf(element)); } ///////////////////////////////////////////////////////////////////////////// function myIndent(state,textAfter) { var indent = cmCfg.indentUnit; var token = (peekToken(state)).token; var wordAfter = takewhile(textAfter,/[^a-z]/); if (state.in_string || state.in_atom) { return CodeMirror.Pass; }else if (token == "") { return 0; }else if (isMember(token,openParenWords)) { return (peekToken(state)).column+token.length; }else if (token == "when") { return (peekToken(state)).column+token.length+1; }else if (token == "fun" && wordAfter == "") { return (peekToken(state)).column+token.length; }else if (token == "->") { if (isMember(wordAfter,["end","after","catch"])) { return peekToken(state,2).column; }else if (peekToken(state,2).token == "fun") { return peekToken(state,2).column+indent; }else if (peekToken(state,2).token == "") { return indent; }else{ return (peekToken(state)).indent+indent; } }else if (isMember(wordAfter,["after","catch","of"])) { 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 Token(stream) { this.token = stream ? stream.current() : ""; this.column = stream ? stream.column() : 0; this.indent = stream ? stream.indentation() : 0; } 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 (token == ".") { state.tokenStack = []; return false; }else if(isMember(token,[",", ":", "of", "cond", "let", "query"])) { return false; }else if (drop_last(prev_token,token)) { 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 if (isMember(token,["after","catch"])) { return false; }else{ state.tokenStack.push(new Token(stream)); return true; } } function drop_last(open, close) { switch(open+" "+close) { case "when ;": return true; default: return false; } } function drop_first(open, close) { switch (open+" "+close) { case "when ->": return true; case "-> end": 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 "-> catch": return true; case "-> after": return true; case "-> ;": return true; default: return false; } } return { startState: function() { return {tokenStack: [], in_record: false, in_string: false, in_atom: false}; }, token: function(stream, state) { return tokenize(stream, state); }, indent: function(state, textAfter) { return myIndent(state,textAfter); }, lineComment: "%" }; }); ================================================ FILE: public/packages/codemirror-3.19/mode/erlang/index.html ================================================ CodeMirror: Erlang mode

            Erlang mode

            MIME types defined: text/x-erlang.

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

            Fortran mode

            MIME types defined: text/x-Fortran.

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

            Gas mode

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

            MIME types defined: text/x-gas

            ================================================ FILE: public/packages/codemirror-3.19/mode/gfm/gfm.js ================================================ 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) && stream.string.slice(stream.start - 2, stream.start) != "](") { // 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, taskLists: true, fencedCodeBlocks: true }); return CodeMirror.overlayMode(CodeMirror.getMode(config, "gfmBase"), gfmOverlay); }, "markdown"); ================================================ FILE: public/packages/codemirror-3.19/mode/gfm/index.html ================================================ CodeMirror: GFM mode

            GFM mode

            Optionally depends on other modes for properly highlighted code blocks.

            Parsing/Highlighting Tests: normal, verbose.

            ================================================ FILE: public/packages/codemirror-3.19/mode/gfm/test.js ================================================ (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 __][em&strong _foo__][em _] bar"); MT("fencedCodeBlocks", "[comment ```]", "[comment foo]", "", "[comment ```]", "bar"); MT("fencedCodeBlockModeSwitching", "[comment ```javascript]", "[variable foo]", "", "[comment ```]", "bar"); MT("taskListAsterisk", "[variable-2 * []] foo]", // Invalid; must have space or x between [] "[variable-2 * [ ]]bar]", // Invalid; must have space after ] "[variable-2 * [x]]hello]", // Invalid; must have space after ] "[variable-2 * ][meta [ ]]][variable-2 [world]]]", // Valid; tests reference style links " [variable-3 * ][property [x]]][variable-3 foo]"); // Valid; can be nested MT("taskListPlus", "[variable-2 + []] foo]", // Invalid; must have space or x between [] "[variable-2 + [ ]]bar]", // Invalid; must have space after ] "[variable-2 + [x]]hello]", // Invalid; must have space after ] "[variable-2 + ][meta [ ]]][variable-2 [world]]]", // Valid; tests reference style links " [variable-3 + ][property [x]]][variable-3 foo]"); // Valid; can be nested MT("taskListDash", "[variable-2 - []] foo]", // Invalid; must have space or x between [] "[variable-2 - [ ]]bar]", // Invalid; must have space after ] "[variable-2 - [x]]hello]", // Invalid; must have space after ] "[variable-2 - ][meta [ ]]][variable-2 [world]]]", // Valid; tests reference style links " [variable-3 - ][property [x]]][variable-3 foo]"); // Valid; can be nested MT("taskListNumber", "[variable-2 1. []] foo]", // Invalid; must have space or x between [] "[variable-2 2. [ ]]bar]", // Invalid; must have space after ] "[variable-2 3. [x]]hello]", // Invalid; must have space after ] "[variable-2 4. ][meta [ ]]][variable-2 [world]]]", // Valid; tests reference style links " [variable-3 1. ][property [x]]][variable-3 foo]"); // Valid; can be nested MT("SHA", "foo [link be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] bar"); MT("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/]"); })(); ================================================ FILE: public/packages/codemirror-3.19/mode/gherkin/gherkin.js ================================================ /* Gherkin mode - http://www.cukes.info/ Report bugs/issues here: https://github.com/marijnh/CodeMirror/issues */ // Following Objs from Brackets implementation: https://github.com/tregusti/brackets-gherkin/blob/master/main.js //var Quotes = { // SINGLE: 1, // DOUBLE: 2 //}; //var regex = { // keywords: /(Feature| {2}(Scenario|In order to|As|I)| {4}(Given|When|Then|And))/ //}; CodeMirror.defineMode("gherkin", function () { return { startState: function () { return { lineNumber: 0, tableHeaderLine: null, allowFeature: true, allowBackground: false, allowScenario: false, allowSteps: false, allowPlaceholders: false, inMultilineArgument: false, inMultilineString: false, inMultilineTable: false }; }, token: function (stream, state) { if (stream.sol()) { state.lineNumber++; } stream.eatSpace(); // INSIDE OF MULTILINE ARGUMENTS if (state.inMultilineArgument) { // STRING if (state.inMultilineString) { if (stream.match('"""')) { state.inMultilineString = false; state.inMultilineArgument = false; } else { stream.match(/.*/); } return "string"; } // TABLE if (state.inMultilineTable) { // New table, assume first row is headers if (state.tableHeaderLine === null) { state.tableHeaderLine = state.lineNumber; } if (stream.match(/\|\s*/)) { if (stream.eol()) { state.inMultilineTable = false; } return "bracket"; } else { stream.match(/[^\|]*/); return state.tableHeaderLine === state.lineNumber ? "property" : "string"; } } // DETECT START if (stream.match('"""')) { // String state.inMultilineString = true; return "string"; } else if (stream.match("|")) { // Table state.inMultilineTable = true; return "bracket"; } else { // Or abort state.inMultilineArgument = false; state.tableHeaderLine = null; } return null; } // LINE COMMENT if (stream.match(/#.*/)) { return "comment"; // TAG } else if (stream.match(/@\S+/)) { return "def"; // FEATURE } else if (state.allowFeature && stream.match(/Feature:/)) { state.allowScenario = true; state.allowBackground = true; state.allowPlaceholders = false; state.allowSteps = false; return "keyword"; // BACKGROUND } else if (state.allowBackground && stream.match("Background:")) { state.allowPlaceholders = false; state.allowSteps = true; state.allowBackground = false; return "keyword"; // SCENARIO OUTLINE } else if (state.allowScenario && stream.match("Scenario Outline:")) { state.allowPlaceholders = true; state.allowSteps = true; return "keyword"; // EXAMPLES } else if (state.allowScenario && stream.match("Examples:")) { state.allowPlaceholders = false; state.allowSteps = true; state.allowBackground = false; state.inMultilineArgument = true; return "keyword"; // SCENARIO } else if (state.allowScenario && stream.match(/Scenario:/)) { state.allowPlaceholders = false; state.allowSteps = true; state.allowBackground = false; return "keyword"; // STEPS } else if (state.allowSteps && stream.match(/(Given|When|Then|And|But)/)) { return "keyword"; // INLINE STRING } else if (!state.inMultilineArgument && stream.match(/"/)) { stream.match(/.*?"/); return "string"; // MULTILINE ARGUMENTS } else if (state.allowSteps && stream.eat(":")) { if (stream.match(/\s*$/)) { state.inMultilineArgument = true; return "keyword"; } else { return null; } } else if (state.allowSteps && stream.match("<")) { if (stream.match(/.*?>/)) { return "property"; } else { return null; } // Fall through } else { stream.eatWhile(/[^":<]/); } return null; } }; }); CodeMirror.defineMIME("text/x-feature", "gherkin"); ================================================ FILE: public/packages/codemirror-3.19/mode/gherkin/index.html ================================================ CodeMirror: Gherkin mode

            Gherkin mode

            MIME types defined: text/x-feature.

            ================================================ FILE: public/packages/codemirror-3.19/mode/go/go.js ================================================ 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: "{}:", blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: "//" }; }); CodeMirror.defineMIME("text/x-go", "go"); ================================================ FILE: public/packages/codemirror-3.19/mode/go/index.html ================================================ CodeMirror: Go mode

            Go mode

            MIME type: text/x-go

            ================================================ FILE: public/packages/codemirror-3.19/mode/groovy/groovy.js ================================================ 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: "{}", fold: "brace" }; }); CodeMirror.defineMIME("text/x-groovy", "groovy"); ================================================ FILE: public/packages/codemirror-3.19/mode/groovy/index.html ================================================ CodeMirror: Groovy mode

            Groovy mode

            MIME types defined: text/x-groovy

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

            HAML mode

            MIME types defined: text/x-haml.

            Parsing/Highlighting Tests: normal, verbose.

            ================================================ FILE: public/packages/codemirror-3.19/mode/haml/test.js ================================================ (function() { var mode = CodeMirror.getMode({tabSize: 4}, "haml"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } // Requires at least one media query MT("elementName", "[tag %h1] Hey There"); MT("oneElementPerLine", "[tag %h1] Hey There %h2"); MT("idSelector", "[tag %h1][attribute #test] Hey There"); MT("classSelector", "[tag %h1][attribute .hello] Hey There"); MT("docType", "[tag !!! XML]"); MT("comment", "[comment / Hello WORLD]"); MT("notComment", "[tag %h1] This is not a / comment "); MT("attributes", "[tag %a]([variable title][operator =][string \"test\"]){[atom :title] [operator =>] [string \"test\"]}"); MT("htmlCode", "[tag

            ]Title[tag

            ]"); MT("rubyBlock", "[operator =][variable-2 @item]"); MT("selectorRubyBlock", "[tag %a.selector=] [variable-2 @item]"); MT("nestedRubyBlock", "[tag %a]", " [operator =][variable puts] [string \"test\"]"); MT("multilinePlaintext", "[tag %p]", " Hello,", " World"); MT("multilineRuby", "[tag %p]", " [comment -# this is a comment]", " [comment and this is a comment too]", " Date/Time", " [operator -] [variable now] [operator =] [tag DateTime][operator .][variable now]", " [tag %strong=] [variable now]", " [operator -] [keyword if] [variable now] [operator >] [tag DateTime][operator .][variable parse]([string \"December 31, 2006\"])", " [operator =][string \"Happy\"]", " [operator =][string \"Belated\"]", " [operator =][string \"Birthday\"]"); MT("multilineComment", "[comment /]", " [comment Multiline]", " [comment Comment]"); MT("hamlComment", "[comment -# this is a comment]"); MT("multilineHamlComment", "[comment -# this is a comment]", " [comment and this is a comment too]"); MT("multilineHTMLComment", "[comment ]"); MT("hamlAfterRubyTag", "[attribute .block]", " [tag %strong=] [variable now]", " [attribute .test]", " [operator =][variable now]", " [attribute .right]"); MT("stretchedRuby", "[operator =] [variable puts] [string \"Hello\"],", " [string \"World\"]"); MT("interpolationInHashAttribute", //"[tag %div]{[atom :id] [operator =>] [string \"#{][variable test][string }_#{][variable ting][string }\"]} test"); "[tag %div]{[atom :id] [operator =>] [string \"#{][variable test][string }_#{][variable ting][string }\"]} test"); MT("interpolationInHTMLAttribute", "[tag %div]([variable title][operator =][string \"#{][variable test][string }_#{][variable ting]()[string }\"]) Test"); })(); ================================================ FILE: public/packages/codemirror-3.19/mode/haskell/haskell.js ================================================ CodeMirror.defineMode("haskell", function(_config, modeConfig) { function switchState(source, setState, f) { setState(f); return f(source, setState); } // These should all be Unicode extended, as per the Haskell 2010 report var smallRE = /[a-z_]/; var largeRE = /[A-Z]/; var digitRE = /[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"); var override = modeConfig.overrideKeywords; if (override) for (var word in override) if (override.hasOwnProperty(word)) wkw[word] = override[word]; return wkw; })(); return { startState: function () { return { f: normal }; }, copyState: function (s) { return { f: s.f }; }, token: function(stream, state) { var t = state.f(stream, function(s) { state.f = s; }); var w = stream.current(); return (w in wellKnownWords) ? wellKnownWords[w] : t; }, blockCommentStart: "{-", blockCommentEnd: "-}", lineComment: "--" }; }); CodeMirror.defineMIME("text/x-haskell", "haskell"); ================================================ FILE: public/packages/codemirror-3.19/mode/haskell/index.html ================================================ CodeMirror: Haskell mode

            Haskell mode

            MIME types defined: text/x-haskell.

            ================================================ FILE: public/packages/codemirror-3.19/mode/haxe/haxe.js ================================================ 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(")"), commasep(metaargs, ")"), poplex, statement); } function metaargs(type) { if(type == "variable") return cont(); } function importdef (type, value) { if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); } else if(type == "variable" || type == "property" || type == ".") 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/haxe/index.html ================================================ CodeMirror: Haxe mode

            Haxe mode

            MIME types defined: text/x-haxe.

            ================================================ FILE: public/packages/codemirror-3.19/mode/htmlembedded/htmlembedded.js ================================================ 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"}); ================================================ FILE: public/packages/codemirror-3.19/mode/htmlembedded/index.html ================================================ CodeMirror: Html Embedded Scripts mode

            Html Embedded Scripts mode

            Mode for html embedded scripts like JSP and ASP.NET. Depends on 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)

            ================================================ FILE: public/packages/codemirror-3.19/mode/htmlmixed/htmlmixed.js ================================================ 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/htmlmixed/index.html ================================================ CodeMirror: HTML mixed mode

            HTML mixed mode

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

            It takes an optional mode configuration option, 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).

            ================================================ FILE: public/packages/codemirror-3.19/mode/http/http.js ================================================ CodeMirror.defineMode("http", function() { function failFirstLine(stream, state) { stream.skipToEnd(); state.cur = header; return "error"; } function start(stream, state) { if (stream.match(/^HTTP\/\d\.\d/)) { state.cur = responseStatusCode; return "keyword"; } else if (stream.match(/^[A-Z]+/) && /[ \t]/.test(stream.peek())) { state.cur = requestPath; return "keyword"; } else { return failFirstLine(stream, state); } } function responseStatusCode(stream, state) { var code = stream.match(/^\d+/); if (!code) return failFirstLine(stream, state); state.cur = responseStatusText; var status = Number(code[0]); if (status >= 100 && status < 200) { return "positive informational"; } else if (status >= 200 && status < 300) { return "positive success"; } else if (status >= 300 && status < 400) { return "positive redirect"; } else if (status >= 400 && status < 500) { return "negative client-error"; } else if (status >= 500 && status < 600) { return "negative server-error"; } else { return "error"; } } function responseStatusText(stream, state) { stream.skipToEnd(); state.cur = header; return null; } function requestPath(stream, state) { stream.eatWhile(/\S/); state.cur = requestProtocol; return "string-2"; } function requestProtocol(stream, state) { if (stream.match(/^HTTP\/\d\.\d$/)) { state.cur = header; return "keyword"; } else { return failFirstLine(stream, state); } } function header(stream) { if (stream.sol() && !stream.eat(/[ \t]/)) { if (stream.match(/^.*?:/)) { return "atom"; } else { stream.skipToEnd(); return "error"; } } else { stream.skipToEnd(); return "string"; } } function body(stream) { stream.skipToEnd(); return null; } return { token: function(stream, state) { var cur = state.cur; if (cur != header && cur != body && stream.eatSpace()) return null; return cur(stream, state); }, blankLine: function(state) { state.cur = body; }, startState: function() { return {cur: start}; } }; }); CodeMirror.defineMIME("message/http", "http"); ================================================ FILE: public/packages/codemirror-3.19/mode/http/index.html ================================================ CodeMirror: HTTP mode

            HTTP mode

            MIME types defined: message/http.

            ================================================ FILE: public/packages/codemirror-3.19/mode/index.html ================================================ CodeMirror: Language Modes

            Language modes

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/jade/index.html ================================================ CodeMirror: Jade Templating Mode

            Jade Templating Mode

            The Jade Templating Mode

            Created by Drew Bratcher. Managed as part of an Adobe Brackets extension at https://github.com/dbratcher/brackets-jade.

            MIME type defined: text/x-jade.

            ================================================ FILE: public/packages/codemirror-3.19/mode/jade/jade.js ================================================ CodeMirror.defineMode("jade", function () { var symbol_regex1 = /^(?:~|!|%|\^|\*|\+|=|\\|:|;|,|\/|\?|&|<|>|\|)/; var open_paren_regex = /^(\(|\[)/; var close_paren_regex = /^(\)|\])/; var keyword_regex1 = /^(if|else|return|var|function|include|doctype|each)/; var keyword_regex2 = /^(#|{|}|\.)/; var keyword_regex3 = /^(in)/; var html_regex1 = /^(html|head|title|meta|link|script|body|br|div|input|span|a|img)/; var html_regex2 = /^(h1|h2|h3|h4|h5|p|strong|em)/; return { startState: function () { return { inString: false, stringType: "", beforeTag: true, justMatchedKeyword: false, afterParen: false }; }, token: function (stream, state) { //check for state changes if (!state.inString && ((stream.peek() == '"') || (stream.peek() == "'"))) { state.stringType = stream.peek(); stream.next(); // Skip quote state.inString = true; // Update state } //return state if (state.inString) { if (stream.skipTo(state.stringType)) { // Quote found on this line stream.next(); // Skip quote state.inString = false; // Clear flag } else { stream.skipToEnd(); // Rest of line is string } state.justMatchedKeyword = false; return "string"; // Token style } else if (stream.sol() && stream.eatSpace()) { if (stream.match(keyword_regex1)) { state.justMatchedKeyword = true; stream.eatSpace(); return "keyword"; } if (stream.match(html_regex1) || stream.match(html_regex2)) { state.justMatchedKeyword = true; return "variable"; } } else if (stream.sol() && stream.match(keyword_regex1)) { state.justMatchedKeyword = true; stream.eatSpace(); return "keyword"; } else if (stream.sol() && (stream.match(html_regex1) || stream.match(html_regex2))) { state.justMatchedKeyword = true; return "variable"; } else if (stream.eatSpace()) { state.justMatchedKeyword = false; if (stream.match(keyword_regex3) && stream.eatSpace()) { state.justMatchedKeyword = true; return "keyword"; } } else if (stream.match(symbol_regex1)) { state.justMatchedKeyword = false; return "atom"; } else if (stream.match(open_paren_regex)) { state.afterParen = true; state.justMatchedKeyword = true; return "def"; } else if (stream.match(close_paren_regex)) { state.afterParen = false; state.justMatchedKeyword = true; return "def"; } else if (stream.match(keyword_regex2)) { state.justMatchedKeyword = true; return "keyword"; } else if (stream.eatSpace()) { state.justMatchedKeyword = false; } else { stream.next(); if (state.justMatchedKeyword) { return "property"; } else if (state.afterParen) { return "property"; } } return null; } }; }); CodeMirror.defineMIME('text/x-jade', 'jade'); ================================================ FILE: public/packages/codemirror-3.19/mode/javascript/index.html ================================================ CodeMirror: JavaScript mode

            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).
            • statementIndent which (given a number) will determine the amount of indentation to use for statements continued on a new line.

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/javascript/javascript.js ================================================ // TODO actually recognize syntax of TypeScript constructs CodeMirror.defineMode("javascript", function(config, parserConfig) { var indentUnit = config.indentUnit; var statementIndent = parserConfig.statementIndent; 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": kw("if"), "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, "this": kw("this") }; // 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 (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) return ret("number", "number"); 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)) { 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, "this": 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, indent = state.indented; if (state.lexical.type == "stat") indent = state.lexical.indented; state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); }; result.lex = true; return result; } function poplex() { var state = cx.state; if (state.lexical.prev) { if (state.lexical.type == ")") state.indented = state.lexical.indented; state.lexical = state.lexical.prev; } } poplex.lex = true; function expect(wanted) { 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 == "if") return cont(pushlex("form"), expression, statement, poplex, maybeelse); 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) { return expressionInner(type, false); } function expressionNoComma(type) { return expressionInner(type, true); } function expressionInner(type, noComma) { var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); if (type == "function") return cont(functiondef); if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression); if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); if (type == "operator") return cont(noComma ? expressionNoComma : expression); if (type == "[") return cont(pushlex("]"), commasep(expressionNoComma, "]"), poplex, maybeop); if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeop); return cont(); } function maybeexpression(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expression); } function maybeexpressionNoComma(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expressionNoComma); } function maybeoperatorComma(type, value) { if (type == ",") return cont(expression); return maybeoperatorNoComma(type, value, false); } function maybeoperatorNoComma(type, value, noComma) { var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; var expr = noComma == false ? expression : expressionNoComma; if (type == "operator") { if (/\+\+|--/.test(value)) return cont(me); if (value == "?") return cont(expression, expect(":"), expr); return cont(expr); } if (type == ";") return; if (type == "(") return cont(pushlex(")", "call"), commasep(expressionNoComma, ")"), poplex, me); if (type == ".") return cont(property, me); if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); } function maybelabel(type) { if (type == ":") return cont(poplex, statement); return pass(maybeoperatorComma, expect(";"), poplex); } function property(type) { if (type == "variable") {cx.marked = "property"; return cont();} } function objprop(type, value) { if (type == "variable") { cx.marked = "property"; if (value == "get" || value == "set") return cont(getterSetter); } else if (type == "number" || type == "string") { cx.marked = type + " property"; } if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expressionNoComma); } function getterSetter(type) { if (type == ":") return cont(expression); if (type != "variable") return cont(expect(":"), expression); cx.marked = "property"; return cont(functiondef); } function commasep(what, end) { function proceed(type) { if (type == ",") { var lex = cx.state.lexical; if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; 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(expressionNoComma, vardef2); if (type == ",") return cont(vardef1); } function maybeelse(type, value) { if (type == "keyword b" && value == "else") return cont(pushlex("form"), statement, poplex); } function forspec1(type) { if (type == "var") return cont(vardef1, expect(";"), forspec2); if (type == ";") return cont(forspec2); if (type == "variable") return cont(formaybein); return pass(expression, expect(";"), forspec2); } function formaybein(_type, value) { if (value == "in") return cont(expression); return cont(maybeoperatorComma, forspec2); } function forspec2(type, value) { if (type == ";") return cont(forspec3); if (value == "in") return cont(expression); return pass(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 (state.tokenize != jsTokenComment && stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (type == "comment") return style; state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; return parseJS(state, style, type, content, stream); }, indent: function(state, textAfter) { if (state.tokenize == jsTokenComment) return CodeMirror.Pass; if (state.tokenize != jsTokenBase) return 0; var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; // Kludge to prevent 'maybelse' from blocking lexical scope pops for (var i = state.cc.length - 1; i >= 0; --i) { var c = state.cc[i]; if (c == poplex) lexical = lexical.prev; else if (c != maybeelse || /^else\b/.test(textAfter)) break; } if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev; var type = lexical.type, closing = firstChar == type; if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? 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 == "," ? statementIndent || indentUnit : 0); else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column + (closing ? 0 : 1); else return lexical.indented + (closing ? 0 : indentUnit); }, electricChars: ":{}", blockCommentStart: jsonMode ? null : "/*", blockCommentEnd: jsonMode ? null : "*/", lineComment: jsonMode ? null : "//", fold: "brace", helperType: jsonMode ? "json" : "javascript", 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("application/x-json", {name: "javascript", json: true}); CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); ================================================ FILE: public/packages/codemirror-3.19/mode/javascript/test.js ================================================ (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "javascript"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("locals", "[keyword function] [variable foo]([def a], [def b]) { [keyword var] [def c] = [number 10]; [keyword return] [variable-2 a] + [variable-2 c] + [variable d]; }"); MT("comma-and-binop", "[keyword function](){ [keyword var] [def x] = [number 1] + [number 2], [def y]; }"); })(); ================================================ FILE: public/packages/codemirror-3.19/mode/javascript/typescript.html ================================================ CodeMirror: TypeScript mode

            TypeScript mode

            This is a specialization of the JavaScript mode.

            ================================================ FILE: public/packages/codemirror-3.19/mode/jinja2/index.html ================================================ CodeMirror: Jinja2 mode

            Jinja2 mode

            ================================================ FILE: public/packages/codemirror-3.19/mode/jinja2/jinja2.js ================================================ 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); } }; }); ================================================ FILE: public/packages/codemirror-3.19/mode/less/index.html ================================================ CodeMirror: LESS mode

            LESS mode

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/less/less.js ================================================ /* 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;} var selectors = /(^\:root$|^\:nth\-child$|^\:nth\-last\-child$|^\:nth\-of\-type$|^\:nth\-last\-of\-type$|^\:first\-child$|^\:last\-child$|^\:first\-of\-type$|^\:last\-of\-type$|^\:only\-child$|^\:only\-of\-type$|^\:empty$|^\:link|^\:visited$|^\:active$|^\:hover$|^\:focus$|^\:target$|^\:lang$|^\:enabled^\:disabled$|^\:checked$|^\:first\-line$|^\:first\-letter$|^\:before$|^\:after$|^\:not$|^\:required$|^\:invalid$)/; function tokenBase(stream, state) { var ch = stream.next(); if (ch == "@") {stream.eatWhile(/[\w\-]/); return ret("meta", stream.current());} else if (ch == "/" && stream.eat("*")) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } else if (ch == "<" && stream.eat("!")) { state.tokenize = tokenSGMLComment; return tokenSGMLComment(stream, state); } else if (ch == "=") ret(null, "compare"); else if (ch == "|" && stream.eat("=")) return ret(null, "compare"); else if (ch == "\"" || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (ch == "/") { // e.g.: .png will not be parsed as a class if(stream.eat("/")){ state.tokenize = tokenSComment; return tokenSComment(stream, state); } else { if(type == "string" || type == "(") return ret("string", "string"); if(state.stack[state.stack.length-1] !== undefined) return ret(null, ch); stream.eatWhile(/[\a-zA-Z0-9\-_.\s]/); if( /\/|\)|#/.test(stream.peek() || (stream.eatSpace() && stream.peek() === ")")) || stream.eol() )return ret("string", "string"); // let url(/images/logo.png) without quotes return as string } } else if (ch == "!") { stream.match(/^\s*\w*/); return ret("keyword", "important"); } else if (/\d/.test(ch)) { stream.eatWhile(/[\w.%]/); return ret("number", "unit"); } else if (/[,+<>*\/]/.test(ch)) { if(stream.peek() == "=" || type == "a")return ret("string", "string"); if(ch === ",")return ret(null, ch); 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 == "(")return ret("string", "string"); // allow url(../image.png) stream.eatWhile(/[\a-zA-Z0-9\-_]/); if(stream.peek() === " ")stream.eatSpace(); if(stream.peek() === ")" || type === ":")return ret("number", "unit");//rgba(0,0,0,.25); else if(state.stack[state.stack.length-1] === "rule" && stream.peek().match(/{|,|\+|\(/) === null)return ret("number", "unit"); 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()) ){ if(type === "select-op")return ret("number", "unit"); else 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", stream.current()); } } else {//when not a valid hexvalue length stream.eatWhile(/[\w\\\-]/); if(state.stack[state.stack.length-1] === "rule")return ret("atom", stream.current());return ret("atom", stream.current()); return ret("atom", "tag"); } } else if (ch == "&") { stream.eatWhile(/[\w\-]/); return ret(null, ch); } else { stream.eatWhile(/[\w\\\-_%.{]/); if(stream.current().match(/\\/) !== null){ if(stream.current().charAt(stream.current().length-1) === "\\"){ stream.eat(/\'|\"|\)|\(/); while(stream.eatWhile(/[\w\\\-_%.{]/)){ stream.eat(/\'|\"|\)|\(/); } return ret("string", stream.current()); } } //else if(type === "tag")return ret("tag", "tag"); else if(type == "string"){ if(state.stack[state.stack.length-1] === "{" && stream.peek() === ":")return ret("variable", "variable"); if(stream.peek() === "/")stream.eatWhile(/[\w\\\-_%.{:\/]/); return ret(type, stream.current()); } else if(stream.current().match(/(^http$|^https$)/) != null){ stream.eatWhile(/[\w\\\-_%.{:\/]/); if(stream.peek() === "/")stream.eatWhile(/[\w\\\-_%.{:\/]/); return ret("string", "string"); } else if(stream.peek() == "<" || stream.peek() == ">" || stream.peek() == "+"){ if(type === "(" && (stream.current() === "n" || stream.current() === "-n"))return ret("string", stream.current()); return ret("tag", "tag"); } else if( /\(/.test(stream.peek()) ){ if(stream.current() === "when")return ret("variable","variable"); else if(state.stack[state.stack.length-1] === "@media" && stream.current() === "and")return ret("variable",stream.current()); return ret(null, ch); } else if (stream.peek() == "/" && state.stack[state.stack.length-1] !== undefined){ // url(dir/center/image.png) if(stream.peek() === "/")stream.eatWhile(/[\w\\\-_%.{:\/]/); return ret("string", stream.current()); } 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); return ret("number", "unit"); } 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); else if(state.stack[state.stack.length-1] === "border-color" || state.stack[state.stack.length-1] === "background-position" || state.stack[state.stack.length-1] === "font-family")return ret(null, stream.current()); else if(type === "tag")return ret("tag", "tag"); else if((type === ":" || type === "unit") && state.stack[state.stack.length-1] === "rule")return ret(null, stream.current()); else if(state.stack[state.stack.length-1] === "rule" && type === "tag")return ret("string", stream.current()); else if(state.stack[state.stack.length-1] === ";" && type === ":")return ret(null, stream.current()); //else if(state.stack[state.stack.length-1] === ";" || type === "")return ret("variable", stream.current()); else if(stream.peek() === "#" && type !== undefined && type.match(/\+|,|tag|select\-op|}|{|;/g) === null)return ret("string", stream.current()); else if(type === "variable")return ret(null, stream.current()); else if(state.stack[state.stack.length-1] === "{" && type === "comment")return ret("variable", stream.current()); else if(state.stack.length === 0 && (type === ";" || type === "comment"))return ret("tag", stream.current()); else if((state.stack[state.stack.length-1] === "{" || type === ";") && state.stack[state.stack.length-1] !== "@media{")return ret("variable", stream.current()); else if(state.stack[state.stack.length-2] === "{" && state.stack[state.stack.length-1] === ";")return ret("variable", stream.current()); return ret("tag", "tag"); } else if(type == "compare" || type == "a" || type == "("){ return ret("string", "string"); } else if(type == "|" || stream.current() == "-" || type == "["){ if(type == "|" && stream.peek().match(/\]|=|\~/) !== null)return ret("number", stream.current()); else if(type == "|" )return ret("tag", "tag"); else if(type == "["){ stream.eatWhile(/\w\-/); return ret("number", stream.current()); } return ret(null, ch); } else if((stream.peek() == ":") || ( stream.eatSpace() && 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 if(state.stack[state.stack.length-1] === "font-family" || state.stack[state.stack.length-1] === "background-position" || state.stack[state.stack.length-1] === "border-color"){ return ret(null, null); } else { if(state.stack[state.stack.length-1] === null && type === ":")return ret(null, stream.current()); //else if((type === ")" && state.stack[state.stack.length-1] === "rule") || (state.stack[state.stack.length-2] === "{" && state.stack[state.stack.length-1] === "rule" && type === "variable"))return ret(null, stream.current()); else if(/\^|\$/.test(stream.current()) && stream.peek().match(/\~|=/) !== null)return ret("string", "string");//att^=val else if(type === "unit" && state.stack[state.stack.length-1] === "rule")return ret(null, "unit"); else if(type === "unit" && state.stack[state.stack.length-1] === ";")return ret(null, "unit"); else if(type === ")" && state.stack[state.stack.length-1] === "rule")return ret(null, "unit"); else if(type.match("@") !== null && state.stack[state.stack.length-1] === "rule")return ret(null, "unit"); //else if(type === "unit" && state.stack[state.stack.length-1] === "rule")return ret(null, stream.current()); else if((type === ";" || type === "}" || type === ",") && state.stack[state.stack.length-1] === ";")return ret("tag", stream.current()); else if((type === ";" && stream.peek() !== undefined && stream.peek().match(/{|./) === null) || (type === ";" && stream.eatSpace() && stream.peek().match(/{|./) === null))return ret("variable", stream.current()); else if((type === "@media" && state.stack[state.stack.length-1] === "@media") || type === "@namespace")return ret("tag", stream.current()); else if(type === "{" && state.stack[state.stack.length-1] === ";" && stream.peek() === "{")return ret("tag", "tag"); else if((type === "{" || type === ":") && state.stack[state.stack.length-1] === ";")return ret(null, stream.current()); else if((state.stack[state.stack.length-1] === "{" && stream.eatSpace() && stream.peek().match(/.|#/) === null) || type === "select-op" || (state.stack[state.stack.length-1] === "rule" && type === ",") )return ret("tag", "tag"); else if(type === "variable" && state.stack[state.stack.length-1] === "rule")return ret("tag", "tag"); else if((stream.eatSpace() && stream.peek() === "{") || stream.eol() || stream.peek() === "{")return ret("tag", "tag"); //this one messes up indentation //else if((type === "}" && stream.peek() !== ":") || (type === "}" && stream.eatSpace() && stream.peek() !== ":"))return(type, "tag"); else if(type === ")" && (stream.current() == "and" || stream.current() == "and "))return ret("variable", "variable"); else if(type === ")" && (stream.current() == "when" || stream.current() == "when "))return ret("variable", "variable"); else if(type === ")" || type === "comment" || type === "{")return ret("tag", "tag"); else if(stream.sol())return ret("tag", "tag"); else if((stream.eatSpace() && stream.peek() === "#") || stream.peek() === "#")return ret("tag", "tag"); else if(state.stack.length === 0)return ret("tag", "tag"); else if(type === ";" && stream.peek() !== undefined && stream.peek().match(/^[.|\#]/g) !== null)return ret("tag", "tag"); else if(type === ":"){stream.eatSpace();return ret(null, stream.current());} else if(stream.current() === "and " || stream.current() === "and")return ret("variable", stream.current()); else if(type === ";" && state.stack[state.stack.length-1] === "{")return ret("variable", stream.current()); else if(state.stack[state.stack.length-1] === "rule")return ret(null, stream.current()); return ret("tag", stream.current()); } } } 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 (stream.current() === "font-family") state.stack[state.stack.length-1] = "font-family"; else if (stream.current() === "background-position") state.stack[state.stack.length-1] = "background-position"; else if (stream.current() === "border-color") state.stack[state.stack.length-1] = "border-color"; else if (context == "{" && type != "comment" && type !== "tag") state.stack.push("rule"); else if (stream.peek() === ":" && stream.current().match(/@|#/) === null) style = type; if(type === ";" && (state.stack[state.stack.length-1] == "font-family" || state.stack[state.stack.length-1] == "background-position" || state.stack[state.stack.length-1] == "border-color"))state.stack[state.stack.length-1] = stream.current(); else if(type === "tag" && stream.peek() === ")" && stream.current().match(/\:/) === null){type = null; style = null;} // ???? else if((type === "variable" && stream.peek() === ")") || (type === "variable" && stream.eatSpace() && stream.peek() === ")"))return ret(null,stream.current()); return style; }, indent: function(state, textAfter) { var n = state.stack.length; if (/^\}/.test(textAfter)) n -= state.stack[state.stack.length-1] === "rule" ? 2 : 1; else if (state.stack[state.stack.length-2] === "{") n -= state.stack[state.stack.length-1] === "rule" ? 1 : 0; return state.baseIndent + n * indentUnit; }, electricChars: "}", blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: "//" }; }); CodeMirror.defineMIME("text/x-less", "less"); if (!CodeMirror.mimeModes.hasOwnProperty("text/css")) CodeMirror.defineMIME("text/css", "less"); ================================================ FILE: public/packages/codemirror-3.19/mode/livescript/index.html ================================================ CodeMirror: LiveScript mode

            LiveScript mode

            MIME types defined: text/x-livescript.

            The LiveScript mode was written by Kenneth Bentley (license).

            ================================================ FILE: public/packages/codemirror-3.19/mode/livescript/livescript.js ================================================ /** * Link to the project's GitHub page: * https://github.com/duralog/CodeMirror */ (function() { CodeMirror.defineMode('livescript', function(){ var tokenBase, external; tokenBase = function(stream, state){ var next_rule, nr, i$, len$, r, m; if (next_rule = state.next || 'start') { state.next = state.next; if (Array.isArray(nr = Rules[next_rule])) { for (i$ = 0, len$ = nr.length; i$ < len$; ++i$) { r = nr[i$]; if (r.regex && (m = stream.match(r.regex))) { state.next = r.next; return r.token; } } stream.next(); return 'error'; } if (stream.match(r = Rules[next_rule])) { if (r.regex && stream.match(r.regex)) { state.next = r.next; return r.token; } else { stream.next(); return 'error'; } } } stream.next(); return 'error'; }; external = { startState: function(){ return { next: 'start', lastToken: null }; }, token: function(stream, state){ var style; style = tokenBase(stream, state); state.lastToken = { style: style, indent: stream.indentation(), content: stream.current() }; return style.replace(/\./g, ' '); }, indent: function(state){ var indentation; indentation = state.lastToken.indent; if (state.lastToken.content.match(indenter)) { indentation += 2; } return indentation; } }; return external; }); var identifier = '(?![\\d\\s])[$\\w\\xAA-\\uFFDC](?:(?!\\s)[$\\w\\xAA-\\uFFDC]|-[A-Za-z])*'; var indenter = RegExp('(?:[({[=:]|[-~]>|\\b(?:e(?:lse|xport)|d(?:o|efault)|t(?:ry|hen)|finally|import(?:\\s*all)?|const|var|let|new|catch(?:\\s*' + identifier + ')?))\\s*$'); var keywordend = '(?![$\\w]|-[A-Za-z]|\\s*:(?![:=]))'; var stringfill = { token: 'string', regex: '.+' }; var Rules = { start: [ { token: 'comment.doc', regex: '/\\*', next: 'comment' }, { token: 'comment', regex: '#.*' }, { token: 'keyword', regex: '(?:t(?:h(?:is|row|en)|ry|ypeof!?)|c(?:on(?:tinue|st)|a(?:se|tch)|lass)|i(?:n(?:stanceof)?|mp(?:ort(?:\\s+all)?|lements)|[fs])|d(?:e(?:fault|lete|bugger)|o)|f(?:or(?:\\s+own)?|inally|unction)|s(?:uper|witch)|e(?:lse|x(?:tends|port)|val)|a(?:nd|rguments)|n(?:ew|ot)|un(?:less|til)|w(?:hile|ith)|o[fr]|return|break|let|var|loop)' + keywordend }, { token: 'constant.language', regex: '(?:true|false|yes|no|on|off|null|void|undefined)' + keywordend }, { token: 'invalid.illegal', regex: '(?:p(?:ackage|r(?:ivate|otected)|ublic)|i(?:mplements|nterface)|enum|static|yield)' + keywordend }, { token: 'language.support.class', regex: '(?:R(?:e(?:gExp|ferenceError)|angeError)|S(?:tring|yntaxError)|E(?:rror|valError)|Array|Boolean|Date|Function|Number|Object|TypeError|URIError)' + keywordend }, { token: 'language.support.function', regex: '(?:is(?:NaN|Finite)|parse(?:Int|Float)|Math|JSON|(?:en|de)codeURI(?:Component)?)' + keywordend }, { token: 'variable.language', regex: '(?:t(?:hat|il|o)|f(?:rom|allthrough)|it|by|e)' + keywordend }, { token: 'identifier', regex: identifier + '\\s*:(?![:=])' }, { token: 'variable', regex: identifier }, { token: 'keyword.operator', regex: '(?:\\.{3}|\\s+\\?)' }, { token: 'keyword.variable', regex: '(?:@+|::|\\.\\.)', next: 'key' }, { token: 'keyword.operator', regex: '\\.\\s*', next: 'key' }, { token: 'string', regex: '\\\\\\S[^\\s,;)}\\]]*' }, { token: 'string.doc', regex: '\'\'\'', next: 'qdoc' }, { token: 'string.doc', regex: '"""', next: 'qqdoc' }, { token: 'string', regex: '\'', next: 'qstring' }, { token: 'string', regex: '"', next: 'qqstring' }, { token: 'string', regex: '`', next: 'js' }, { token: 'string', regex: '<\\[', next: 'words' }, { token: 'string.regex', regex: '//', next: 'heregex' }, { token: 'string.regex', regex: '\\/(?:[^[\\/\\n\\\\]*(?:(?:\\\\.|\\[[^\\]\\n\\\\]*(?:\\\\.[^\\]\\n\\\\]*)*\\])[^[\\/\\n\\\\]*)*)\\/[gimy$]{0,4}', next: 'key' }, { token: 'constant.numeric', regex: '(?:0x[\\da-fA-F][\\da-fA-F_]*|(?:[2-9]|[12]\\d|3[0-6])r[\\da-zA-Z][\\da-zA-Z_]*|(?:\\d[\\d_]*(?:\\.\\d[\\d_]*)?|\\.\\d[\\d_]*)(?:e[+-]?\\d[\\d_]*)?[\\w$]*)' }, { token: 'lparen', regex: '[({[]' }, { token: 'rparen', regex: '[)}\\]]', next: 'key' }, { token: 'keyword.operator', regex: '\\S+' }, { token: 'text', regex: '\\s+' } ], heregex: [ { token: 'string.regex', regex: '.*?//[gimy$?]{0,4}', next: 'start' }, { token: 'string.regex', regex: '\\s*#{' }, { token: 'comment.regex', regex: '\\s+(?:#.*)?' }, { token: 'string.regex', regex: '\\S+' } ], key: [ { token: 'keyword.operator', regex: '[.?@!]+' }, { token: 'identifier', regex: identifier, next: 'start' }, { token: 'text', regex: '.', next: 'start' } ], comment: [ { token: 'comment.doc', regex: '.*?\\*/', next: 'start' }, { token: 'comment.doc', regex: '.+' } ], qdoc: [ { token: 'string', regex: ".*?'''", next: 'key' }, stringfill ], qqdoc: [ { token: 'string', regex: '.*?"""', next: 'key' }, stringfill ], qstring: [ { token: 'string', regex: '[^\\\\\']*(?:\\\\.[^\\\\\']*)*\'', next: 'key' }, stringfill ], qqstring: [ { token: 'string', regex: '[^\\\\"]*(?:\\\\.[^\\\\"]*)*"', next: 'key' }, stringfill ], js: [ { token: 'string', regex: '[^\\\\`]*(?:\\\\.[^\\\\`]*)*`', next: 'key' }, stringfill ], words: [ { token: 'string', regex: '.*?\\]>', next: 'key' }, stringfill ] }; for (var idx in Rules) { var r = Rules[idx]; if (Array.isArray(r)) { for (var i = 0, len = r.length; i < len; ++i) { var rr = r[i]; if (rr.regex) { Rules[idx][i].regex = new RegExp('^' + rr.regex); } } } else if (r.regex) { Rules[idx].regex = new RegExp('^' + r.regex); } } })(); CodeMirror.defineMIME('text/x-livescript', 'livescript'); ================================================ FILE: public/packages/codemirror-3.19/mode/livescript/livescript.ls ================================================ /** * Link to the project's GitHub page: * https://github.com/duralog/CodeMirror */ CodeMirror.defineMode 'livescript', (conf) -> tokenBase = (stream, state) -> #indent = if next_rule = state.next or \start state.next = state.next if Array.isArray nr = Rules[next_rule] for r in nr if r.regex and m = stream.match r.regex state.next = r.next return r.token stream.next! return \error if stream.match r = Rules[next_rule] if r.regex and stream.match r.regex state.next = r.next return r.token else stream.next! return \error stream.next! return 'error' external = { startState: (basecolumn) -> { next: \start lastToken: null } token: (stream, state) -> style = tokenBase stream, state #tokenLexer stream, state state.lastToken = { style: style indent: stream.indentation! content: stream.current! } style.replace /\./g, ' ' indent: (state, textAfter) -> # XXX this won't work with backcalls indentation = state.lastToken.indent if state.lastToken.content.match indenter then indentation += 2 return indentation } external ### Highlight Rules # taken from mode-ls.ls indenter = // (? : [({[=:] | [-~]> | \b (?: e(?:lse|xport) | d(?:o|efault) | t(?:ry|hen) | finally | import (?:\s* all)? | const | var | let | new | catch (?:\s* #identifier)? ) ) \s* $ // identifier = /(?![\d\s])[$\w\xAA-\uFFDC](?:(?!\s)[$\w\xAA-\uFFDC]|-[A-Za-z])*/$ keywordend = /(?![$\w]|-[A-Za-z]|\s*:(?![:=]))/$ stringfill = token: \string, regex: '.+' Rules = start: * token: \comment.doc regex: '/\\*' next : \comment * token: \comment regex: '#.*' * token: \keyword regex: //(? :t(?:h(?:is|row|en)|ry|ypeof!?) |c(?:on(?:tinue|st)|a(?:se|tch)|lass) |i(?:n(?:stanceof)?|mp(?:ort(?:\s+all)?|lements)|[fs]) |d(?:e(?:fault|lete|bugger)|o) |f(?:or(?:\s+own)?|inally|unction) |s(?:uper|witch) |e(?:lse|x(?:tends|port)|val) |a(?:nd|rguments) |n(?:ew|ot) |un(?:less|til) |w(?:hile|ith) |o[fr]|return|break|let|var|loop )//$ + keywordend * token: \constant.language regex: '(?:true|false|yes|no|on|off|null|void|undefined)' + keywordend * token: \invalid.illegal regex: '(? :p(?:ackage|r(?:ivate|otected)|ublic) |i(?:mplements|nterface) |enum|static|yield )' + keywordend * token: \language.support.class regex: '(? :R(?:e(?:gExp|ferenceError)|angeError) |S(?:tring|yntaxError) |E(?:rror|valError) |Array|Boolean|Date|Function|Number|Object|TypeError|URIError )' + keywordend * token: \language.support.function regex: '(? :is(?:NaN|Finite) |parse(?:Int|Float) |Math|JSON |(?:en|de)codeURI(?:Component)? )' + keywordend * token: \variable.language regex: '(?:t(?:hat|il|o)|f(?:rom|allthrough)|it|by|e)' + keywordend * token: \identifier regex: identifier + /\s*:(?![:=])/$ * token: \variable regex: identifier * token: \keyword.operator regex: /(?:\.{3}|\s+\?)/$ * token: \keyword.variable regex: /(?:@+|::|\.\.)/$ next : \key * token: \keyword.operator regex: /\.\s*/$ next : \key * token: \string regex: /\\\S[^\s,;)}\]]*/$ * token: \string.doc regex: \''' next : \qdoc * token: \string.doc regex: \""" next : \qqdoc * token: \string regex: \' next : \qstring * token: \string regex: \" next : \qqstring * token: \string regex: \` next : \js * token: \string regex: '<\\[' next : \words * token: \string.regex regex: \// next : \heregex * token: \string.regex regex: // /(?: [^ [ / \n \\ ]* (?: (?: \\. | \[ [^\]\n\\]* (?:\\.[^\]\n\\]*)* \] ) [^ [ / \n \\ ]* )* )/ [gimy$]{0,4} //$ next : \key * token: \constant.numeric regex: '(?:0x[\\da-fA-F][\\da-fA-F_]* |(?:[2-9]|[12]\\d|3[0-6])r[\\da-zA-Z][\\da-zA-Z_]* |(?:\\d[\\d_]*(?:\\.\\d[\\d_]*)?|\\.\\d[\\d_]*) (?:e[+-]?\\d[\\d_]*)?[\\w$]*)' * token: \lparen regex: '[({[]' * token: \rparen regex: '[)}\\]]' next : \key * token: \keyword.operator regex: \\\S+ * token: \text regex: \\\s+ heregex: * token: \string.regex regex: '.*?//[gimy$?]{0,4}' next : \start * token: \string.regex regex: '\\s*#{' * token: \comment.regex regex: '\\s+(?:#.*)?' * token: \string.regex regex: '\\S+' key: * token: \keyword.operator regex: '[.?@!]+' * token: \identifier regex: identifier next : \start * token: \text regex: '.' next : \start comment: * token: \comment.doc regex: '.*?\\*/' next : \start * token: \comment.doc regex: '.+' qdoc: token: \string regex: ".*?'''" next : \key stringfill qqdoc: token: \string regex: '.*?"""' next : \key stringfill qstring: token: \string regex: /[^\\']*(?:\\.[^\\']*)*'/$ next : \key stringfill qqstring: token: \string regex: /[^\\"]*(?:\\.[^\\"]*)*"/$ next : \key stringfill js: token: \string regex: /[^\\`]*(?:\\.[^\\`]*)*`/$ next : \key stringfill words: token: \string regex: '.*?\\]>' next : \key stringfill # for optimization, precompile the regexps for idx, r of Rules if Array.isArray r for rr, i in r if rr.regex then Rules[idx][i].regex = new RegExp '^'+rr.regex else if r.regex then Rules[idx].regex = new RegExp '^'+r.regex CodeMirror.defineMIME 'text/x-livescript', 'livescript' ================================================ FILE: public/packages/codemirror-3.19/mode/lua/index.html ================================================ CodeMirror: Lua mode

            Lua mode

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

            MIME types defined: text/x-lua.

            ================================================ FILE: public/packages/codemirror-3.19/mode/lua/lua.js ================================================ // 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)); }, lineComment: "--", blockCommentStart: "--[[", blockCommentEnd: "]]" }; }); CodeMirror.defineMIME("text/x-lua", "lua"); ================================================ FILE: public/packages/codemirror-3.19/mode/markdown/index.html ================================================ CodeMirror: Markdown mode

            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.

            ================================================ FILE: public/packages/codemirror-3.19/mode/markdown/markdown.js ================================================ CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) { var htmlFound = CodeMirror.modes.hasOwnProperty("xml"); var htmlMode = CodeMirror.getMode(cmCfg, htmlFound ? {name: "xml", htmlMode: true} : "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; // Turn on task lists? ("- [ ] " and "- [x] ") if (modeCfg.taskLists === undefined) modeCfg.taskLists = false; var codeDepth = 0; var header = 'header' , code = 'comment' , quote1 = 'atom' , quote2 = 'number' , list1 = 'variable-2' , list2 = 'variable-3' , list3 = 'keyword' , hr = 'hr' , image = 'tag' , linkinline = 'link' , linkemail = 'link' , linktext = 'link' , linkhref = 'string' , em = 'em' , strong = 'strong'; var hrRE = /^([*\-=_])(?:\s*\1){2,}\s*$/ , ulRE = /^[*\-+]\s+/ , olRE = /^[0-9]+\.\s+/ , taskListRE = /^\[(x| )\](?=\s)/ // Must follow ulRE or olRE , 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 = 0; if (!htmlFound && state.f == htmlBlock) { state.f = inlineNormal; state.block = blockNormal; } // Reset state.trailingSpace state.trailingSpace = 0; state.trailingSpaceNewLine = false; // Mark this line as blank state.thisLineHasContent = false; return null; } function blockNormal(stream, state) { var prevLineIsList = (state.list !== false); 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 if (state.list !== false && state.indentation > 0) { state.list = null; state.listDepth = Math.floor(state.indentation / 4); } else if (state.list !== false) { // No longer a list state.list = false; state.listDepth = 0; } if (state.indentationDiff >= 4) { state.indentation -= 4; stream.skipToEnd(); return code; } else if (stream.eatSpace()) { return null; } else if (stream.peek() === '#' || (state.prevLineHasContent && stream.match(headerRE)) ) { state.header = true; } else if (stream.eat('>')) { state.indentation++; state.quote = 1; stream.eatSpace(); while (stream.eat('>')) { stream.eatSpace(); state.quote++; } } else if (stream.peek() === '[') { return switchInline(stream, state, footnoteLink); } else if (stream.match(hrRE, true)) { return hr; } else if ((!state.prevLineHasContent || prevLineIsList) && (stream.match(ulRE, true) || stream.match(olRE, true))) { state.indentation += 4; state.list = true; state.listDepth++; if (modeCfg.taskLists && stream.match(taskListRE, false)) { state.taskList = 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.taskOpen) { return "meta"; } if (state.taskClosed) { return "property"; } if (state.strong) { styles.push(strong); } 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(state.quote % 2 ? quote1 : quote2); } if (state.list !== false) { var listMod = (state.listDepth - 1) % 3; if (!listMod) { styles.push(list1); } else if (listMod === 1) { styles.push(list2); } else { styles.push(list3); } } if (state.trailingSpaceNewLine) { styles.push("trailing-space-new-line"); } else if (state.trailingSpace) { styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b")); } return styles.length ? styles.join(' ') : null; } function handleText(stream, state) { if (stream.match(textRE, true)) { return getType(state); } return undefined; } function inlineNormal(stream, state) { var style = state.text(stream, state); if (typeof style !== 'undefined') return style; if (state.list) { // List marker (*, +, -, 1., etc) state.list = null; return getType(state); } if (state.taskList) { var taskOpen = stream.match(taskListRE, true)[1] !== "x"; if (taskOpen) state.taskOpen = true; else state.taskClosed = true; state.taskList = false; return getType(state); } state.taskOpen = false; state.taskClosed = false; 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?):\/\/(?:[^\\>]|\\.)+>/, false)) { return switchInline(stream, state, inlineElement(linkinline, '>')); } if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) { 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); } } } if (ch === ' ') { if (stream.match(/ +$/, false)) { state.trailingSpace++; } else if (state.trailingSpace) { state.trailingSpaceNewLine = true; } } 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() { return { f: blockNormal, prevLineHasContent: false, thisLineHasContent: false, block: blockNormal, htmlState: CodeMirror.startState(htmlMode), indentation: 0, inline: inlineNormal, text: handleText, linkText: false, linkTitle: false, em: false, strong: false, header: false, taskList: false, list: false, listDepth: 0, quote: 0, trailingSpace: 0, trailingSpaceNewLine: false }; }, copyState: function(s) { return { f: s.f, prevLineHasContent: s.prevLineHasContent, thisLineHasContent: s.thisLineHasContent, 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, taskList: s.taskList, list: s.list, listDepth: s.listDepth, quote: s.quote, trailingSpace: s.trailingSpace, trailingSpaceNewLine: s.trailingSpaceNewLine, md_inside: s.md_inside }; }, token: function(stream, state) { if (stream.sol()) { if (stream.match(/^\s*$/, true)) { state.prevLineHasContent = false; return blankLine(state); } else { state.prevLineHasContent = state.thisLineHasContent; state.thisLineHasContent = true; } // Reset state.header state.header = false; // Reset state.taskList state.taskList = false; // Reset state.code state.code = false; // Reset state.trailingSpace state.trailingSpace = 0; state.trailingSpaceNewLine = 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/markdown/test.js ================================================ (function() { var mode = CodeMirror.getMode({tabSize: 4}, "markdown"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("plainText", "foo"); // Don't style single trailing space MT("trailingSpace1", "foo "); // Two or more trailing spaces should be styled with line break character MT("trailingSpace2", "foo[trailing-space-a ][trailing-space-new-line ]"); MT("trailingSpace3", "foo[trailing-space-a ][trailing-space-b ][trailing-space-new-line ]"); MT("trailingSpace4", "foo[trailing-space-a ][trailing-space-b ][trailing-space-a ][trailing-space-new-line ]"); // Code blocks using 4 spaces (regardless of CodeMirror.tabSize value) MT("codeBlocksUsing4Spaces", " [comment foo]"); // Code blocks using 4 spaces with internal indentation MT("codeBlocksUsing4SpacesIndentation", " [comment bar]", " [comment hello]", " [comment world]", " [comment foo]", "bar"); // Code blocks 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", "[atom > foo]"); // Single-line blockquote MT("blockquoteNoSpace", "[atom >foo]"); // No blank line before blockquote MT("blockquoteNoBlankLine", "foo", "[atom > bar]"); // Nested blockquote MT("blockquoteSpace", "[atom > foo]", "[number > > foo]", "[atom > > > foo]"); // Single-line blockquote followed by normal paragraph MT("blockquoteThenParagraph", "[atom >foo]", "", "bar"); // Multi-line blockquote (lazy mode) MT("multiBlockquoteLazy", "[atom >foo]", "[atom bar]"); // Multi-line blockquote followed by normal paragraph (lazy mode) MT("multiBlockquoteLazyThenParagraph", "[atom >foo]", "[atom bar]", "", "hello"); // Multi-line blockquote (non-lazy mode) MT("multiBlockquote", "[atom >foo]", "[atom >bar]"); // Multi-line blockquote followed by normal paragraph (non-lazy mode) MT("multiBlockquoteThenParagraph", "[atom >foo]", "[atom >bar]", "", "hello"); // Check list types MT("listAsterisk", "foo", "bar", "", "[variable-2 * foo]", "[variable-2 * bar]"); MT("listPlus", "foo", "bar", "", "[variable-2 + foo]", "[variable-2 + bar]"); MT("listDash", "foo", "bar", "", "[variable-2 - foo]", "[variable-2 - bar]"); MT("listNumber", "foo", "bar", "", "[variable-2 1. foo]", "[variable-2 2. bar]"); // Lists require a preceding blank line (per Dingus) MT("listBogus", "foo", "1. bar", "2. hello"); // Formatting in lists (*) MT("listAsteriskFormatting", "[variable-2 * ][variable-2&em *foo*][variable-2 bar]", "[variable-2 * ][variable-2&strong **foo**][variable-2 bar]", "[variable-2 * ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2 bar]", "[variable-2 * ][variable-2&comment `foo`][variable-2 bar]"); // Formatting in lists (+) MT("listPlusFormatting", "[variable-2 + ][variable-2&em *foo*][variable-2 bar]", "[variable-2 + ][variable-2&strong **foo**][variable-2 bar]", "[variable-2 + ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2 bar]", "[variable-2 + ][variable-2&comment `foo`][variable-2 bar]"); // Formatting in lists (-) MT("listDashFormatting", "[variable-2 - ][variable-2&em *foo*][variable-2 bar]", "[variable-2 - ][variable-2&strong **foo**][variable-2 bar]", "[variable-2 - ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2 bar]", "[variable-2 - ][variable-2&comment `foo`][variable-2 bar]"); // Formatting in lists (1.) MT("listNumberFormatting", "[variable-2 1. ][variable-2&em *foo*][variable-2 bar]", "[variable-2 2. ][variable-2&strong **foo**][variable-2 bar]", "[variable-2 3. ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2 bar]", "[variable-2 4. ][variable-2&comment `foo`][variable-2 bar]"); // Paragraph lists MT("listParagraph", "[variable-2 * foo]", "", "[variable-2 * bar]"); // Multi-paragraph lists // // 4 spaces MT("listMultiParagraph", "[variable-2 * foo]", "", "[variable-2 * bar]", "", " [variable-2 hello]"); // 4 spaces, extra blank lines (should still be list, per Dingus) MT("listMultiParagraphExtra", "[variable-2 * foo]", "", "[variable-2 * bar]", "", "", " [variable-2 hello]"); // 4 spaces, plus 1 space (should still be list, per Dingus) MT("listMultiParagraphExtraSpace", "[variable-2 * foo]", "", "[variable-2 * bar]", "", " [variable-2 hello]", "", " [variable-2 world]"); // 1 tab MT("listTab", "[variable-2 * foo]", "", "[variable-2 * bar]", "", "\t[variable-2 hello]"); // No indent MT("listNoIndent", "[variable-2 * foo]", "", "[variable-2 * bar]", "", "hello"); // Blockquote MT("blockquote", "[variable-2 * foo]", "", "[variable-2 * bar]", "", " [variable-2&atom > hello]"); // Code block MT("blockquoteCode", "[variable-2 * foo]", "", "[variable-2 * bar]", "", " [comment > hello]", "", " [variable-2 world]"); // Code block followed by text MT("blockquoteCodeText", "[variable-2 * foo]", "", " [variable-2 bar]", "", " [comment hello]", "", " [variable-2 world]"); // Nested list MT("listAsteriskNested", "[variable-2 * foo]", "", " [variable-3 * bar]"); MT("listPlusNested", "[variable-2 + foo]", "", " [variable-3 + bar]"); MT("listDashNested", "[variable-2 - foo]", "", " [variable-3 - bar]"); MT("listNumberNested", "[variable-2 1. foo]", "", " [variable-3 2. bar]"); MT("listMixed", "[variable-2 * foo]", "", " [variable-3 + bar]", "", " [keyword - hello]", "", " [variable-2 1. world]"); MT("listBlockquote", "[variable-2 * foo]", "", " [variable-3 + bar]", "", " [atom&variable-3 > hello]"); MT("listCode", "[variable-2 * foo]", "", " [variable-3 + bar]", "", " [comment hello]"); // Code with internal indentation MT("listCodeIndentation", "[variable-2 * foo]", "", " [comment bar]", " [comment hello]", " [comment world]", " [comment foo]", " [variable-2 bar]"); // List nesting edge cases MT("listNested", "[variable-2 * foo]", "", " [variable-3 * bar]", "", " [variable-2 hello]" ); MT("listNested", "[variable-2 * foo]", "", " [variable-3 * bar]", "", " [variable-3 * foo]" ); // Code followed by text MT("listCodeText", "[variable-2 * foo]", "", " [comment bar]", "", "hello"); // Following tests directly from official Markdown documentation // http://daringfireball.net/projects/markdown/syntax#hr MT("hrSpace", "[hr * * *]"); MT("hr", "[hr ***]"); MT("hrLong", "[hr *****]"); MT("hrSpaceDash", "[hr - - -]"); MT("hrDashLong", "[hr ---------------------------------------]"); // 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&em&strong *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&em&strong *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("linkWebDouble", "[link ] foo [link ]"); MT("linkEmail", "[link ] foo"); MT("linkEmailDouble", "[link ] foo [link ]"); MT("emAsterisk", "[em *foo*] bar"); MT("emUnderscore", "[em _foo_] bar"); MT("emInWordAsterisk", "foo[em *bar*]hello"); MT("emInWordUnderscore", "foo[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][em&strong **bar*][strong hello**] world"); MT("emStrongUnderscore", "[em _foo][em&strong __bar_][strong hello__] world"); // "...same character must be used to open and close an emphasis span."" MT("emStrongMixed", "[em _foo][em&strong **bar*hello__ world]"); MT("emStrongMixed", "[em *foo][em&strong __bar_hello** world]"); // 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"); // Tests to make sure GFM-specific things aren't getting through MT("taskList", "[variable-2 * [ ]] bar]"); MT("fencedCodeBlocks", "[comment ```]", "foo", "[comment ```]"); })(); ================================================ FILE: public/packages/codemirror-3.19/mode/meta.js ================================================ 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: 'Cobol', mime: 'text/x-cobol', mode: 'cobol'}, {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: 'DTD', mime: 'application/xml-dtd', mode: 'dtd'}, {name: 'ECL', mime: 'text/x-ecl', mode: 'ecl'}, {name: 'Eiffel', mime: 'text/x-eiffel', mode: 'eiffel'}, {name: 'Erlang', mime: 'text/x-erlang', mode: 'erlang'}, {name: 'Fortran', mime: 'text/x-fortran', mode: 'fortran'}, {name: 'Gas', mime: 'text/x-gas', mode: 'gas'}, {name: 'Gherkin', mime: 'text/x-feature', mode: 'gherkin'}, {name: 'GitHub Flavored Markdown', mime: 'text/x-gfm', mode: 'gfm'}, {name: 'Go', mime: 'text/x-go', mode: 'go'}, {name: 'Groovy', mime: 'text/x-groovy', mode: 'groovy'}, {name: 'HAML', mime: 'text/x-haml', mode: 'haml'}, {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: 'Jade', mime: 'text/x-jade', mode: 'jade'}, {name: 'JavaScript', mime: 'text/javascript', mode: 'javascript'}, {name: 'JSON', mime: 'application/x-json', 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: 'LiveScript', mime: 'text/x-livescript', mode: 'livescript'}, {name: 'Lua', mime: 'text/x-lua', mode: 'lua'}, {name: 'Markdown (GitHub-flavour)', mime: 'text/x-markdown', mode: 'markdown'}, {name: 'mIRC', mime: 'text/mirc', mode: 'mirc'}, {name: 'Nginx', mime: 'text/x-nginx-conf', mode: 'nginx'}, {name: 'NTriples', mime: 'text/n-triples', mode: 'ntriples'}, {name: 'OCaml', mime: 'text/x-ocaml', mode: 'ocaml'}, {name: 'Octave', mime: 'text/x-octave', mode: 'octave'}, {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: 'properties'}, {name: 'Python', mime: 'text/x-python', mode: 'python'}, {name: 'Cython', mime: 'text/x-cython', 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: 'SCSS', mime: 'text/x-scss', mode: 'css'}, {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: 'SmartyMixed', mime: 'text/x-smarty', mode: 'smartymixed'}, {name: 'SPARQL', mime: 'application/x-sparql-query', mode: 'sparql'}, {name: 'SQL', mime: 'text/x-sql', mode: 'sql'}, {name: 'MariaDB', mime: 'text/x-mariadb', mode: 'sql'}, {name: 'sTeX', mime: 'text/x-stex', mode: 'stex'}, {name: 'LaTeX', mime: 'text/x-latex', mode: 'stex'}, {name: 'Tcl', mime: 'text/x-tcl', mode: 'tcl'}, {name: 'TiddlyWiki ', mime: 'text/x-tiddlywiki', mode: 'tiddlywiki'}, {name: 'Tiki wiki', mime: 'text/tiki', mode: 'tiki'}, {name: 'TOML', mime: 'text/x-toml', mode: 'toml'}, {name: 'Turtle', mime: 'text/turtle', mode: 'turtle'}, {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'} ]; ================================================ FILE: public/packages/codemirror-3.19/mode/mirc/index.html ================================================ CodeMirror: mIRC mode

            mIRC mode

            MIME types defined: text/mirc.

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

            NGINX mode

            MIME types defined: text/nginx.

            ================================================ FILE: public/packages/codemirror-3.19/mode/nginx/nginx.js ================================================ CodeMirror.defineMode("nginx", function(config) { function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var keywords = words( /* ngxDirectiveControl */ "break return rewrite set" + /* ngxDirective */ " accept_mutex accept_mutex_delay access_log add_after_body add_before_body add_header addition_types aio alias allow ancient_browser ancient_browser_value auth_basic auth_basic_user_file auth_http auth_http_header auth_http_timeout autoindex autoindex_exact_size autoindex_localtime charset charset_types client_body_buffer_size client_body_in_file_only client_body_in_single_buffer client_body_temp_path client_body_timeout client_header_buffer_size client_header_timeout client_max_body_size connection_pool_size create_full_put_path daemon dav_access dav_methods debug_connection debug_points default_type degradation degrade deny devpoll_changes devpoll_events directio directio_alignment empty_gif env epoll_events error_log eventport_events expires fastcgi_bind fastcgi_buffer_size fastcgi_buffers fastcgi_busy_buffers_size fastcgi_cache fastcgi_cache_key fastcgi_cache_methods fastcgi_cache_min_uses fastcgi_cache_path fastcgi_cache_use_stale fastcgi_cache_valid fastcgi_catch_stderr fastcgi_connect_timeout fastcgi_hide_header fastcgi_ignore_client_abort fastcgi_ignore_headers fastcgi_index fastcgi_intercept_errors fastcgi_max_temp_file_size fastcgi_next_upstream fastcgi_param fastcgi_pass_header fastcgi_pass_request_body fastcgi_pass_request_headers fastcgi_read_timeout fastcgi_send_lowat fastcgi_send_timeout fastcgi_split_path_info fastcgi_store fastcgi_store_access fastcgi_temp_file_write_size fastcgi_temp_path fastcgi_upstream_fail_timeout fastcgi_upstream_max_fails flv geoip_city geoip_country google_perftools_profiles gzip gzip_buffers gzip_comp_level gzip_disable gzip_hash gzip_http_version gzip_min_length gzip_no_buffer gzip_proxied gzip_static gzip_types gzip_vary gzip_window if_modified_since ignore_invalid_headers image_filter image_filter_buffer image_filter_jpeg_quality image_filter_transparency imap_auth imap_capabilities imap_client_buffer index ip_hash keepalive_requests keepalive_timeout kqueue_changes kqueue_events large_client_header_buffers limit_conn limit_conn_log_level limit_rate limit_rate_after limit_req limit_req_log_level limit_req_zone limit_zone lingering_time lingering_timeout lock_file log_format log_not_found log_subrequest map_hash_bucket_size map_hash_max_size master_process memcached_bind memcached_buffer_size memcached_connect_timeout memcached_next_upstream memcached_read_timeout memcached_send_timeout memcached_upstream_fail_timeout memcached_upstream_max_fails merge_slashes min_delete_depth modern_browser modern_browser_value msie_padding msie_refresh multi_accept open_file_cache open_file_cache_errors open_file_cache_events open_file_cache_min_uses open_file_cache_valid open_log_file_cache output_buffers override_charset perl perl_modules perl_require perl_set pid pop3_auth pop3_capabilities port_in_redirect postpone_gzipping postpone_output protocol proxy proxy_bind proxy_buffer proxy_buffer_size proxy_buffering proxy_buffers proxy_busy_buffers_size proxy_cache proxy_cache_key proxy_cache_methods proxy_cache_min_uses proxy_cache_path proxy_cache_use_stale proxy_cache_valid proxy_connect_timeout proxy_headers_hash_bucket_size proxy_headers_hash_max_size proxy_hide_header proxy_ignore_client_abort proxy_ignore_headers proxy_intercept_errors proxy_max_temp_file_size proxy_method proxy_next_upstream proxy_pass_error_message proxy_pass_header proxy_pass_request_body proxy_pass_request_headers proxy_read_timeout proxy_redirect proxy_send_lowat proxy_send_timeout proxy_set_body proxy_set_header proxy_ssl_session_reuse proxy_store proxy_store_access proxy_temp_file_write_size proxy_temp_path proxy_timeout proxy_upstream_fail_timeout proxy_upstream_max_fails random_index read_ahead real_ip_header recursive_error_pages request_pool_size reset_timedout_connection resolver resolver_timeout rewrite_log rtsig_overflow_events rtsig_overflow_test rtsig_overflow_threshold rtsig_signo satisfy secure_link_secret send_lowat send_timeout sendfile sendfile_max_chunk server_name_in_redirect server_names_hash_bucket_size server_names_hash_max_size server_tokens set_real_ip_from smtp_auth smtp_capabilities smtp_client_buffer smtp_greeting_delay so_keepalive source_charset ssi ssi_ignore_recycled_buffers ssi_min_file_chunk ssi_silent_errors ssi_types ssi_value_length ssl ssl_certificate ssl_certificate_key ssl_ciphers ssl_client_certificate ssl_crl ssl_dhparam ssl_engine ssl_prefer_server_ciphers ssl_protocols ssl_session_cache ssl_session_timeout ssl_verify_client ssl_verify_depth starttls stub_status sub_filter sub_filter_once sub_filter_types tcp_nodelay tcp_nopush thread_stack_size timeout timer_resolution types_hash_bucket_size types_hash_max_size underscores_in_headers uninitialized_variable_warn use user userid userid_domain userid_expires userid_mark userid_name userid_p3p userid_path userid_service valid_referers variables_hash_bucket_size variables_hash_max_size worker_connections worker_cpu_affinity worker_priority worker_processes worker_rlimit_core worker_rlimit_nofile worker_rlimit_sigpending worker_threads working_directory xclient xml_entities xslt_stylesheet xslt_typesdrew@li229-23" ); var keywords_block = words( /* ngxDirectiveBlock */ "http mail events server types location upstream charset_map limit_except if geo map" ); var keywords_important = words( /* ngxDirectiveImportant */ "include root server server_name listen internal proxy_pass memcached_pass fastcgi_pass try_files" ); var indentUnit = config.indentUnit, type; function ret(style, tp) {type = tp; return style;} function tokenBase(stream, state) { stream.eatWhile(/[\w\$_]/); var cur = stream.current(); if (keywords.propertyIsEnumerable(cur)) { return "keyword"; } else if (keywords_block.propertyIsEnumerable(cur)) { return "variable-2"; } else if (keywords_important.propertyIsEnumerable(cur)) { return "string-2"; } /**/ var ch = stream.next(); if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("meta", stream.current());} else if (ch == "/" && stream.eat("*")) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } else if (ch == "<" && stream.eat("!")) { state.tokenize = tokenSGMLComment; return tokenSGMLComment(stream, state); } else if (ch == "=") ret(null, "compare"); else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare"); else if (ch == "\"" || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (ch == "#") { stream.skipToEnd(); return ret("comment", "comment"); } else if (ch == "!") { stream.match(/^\s*\w*/); return ret("keyword", "important"); } else if (/\d/.test(ch)) { stream.eatWhile(/[\w.%]/); return ret("number", "unit"); } else if (/[,.+>*\/]/.test(ch)) { return ret(null, "select-op"); } else if (/[;{}:\[\]]/.test(ch)) { return ret(null, ch); } else { stream.eatWhile(/[\w\\\-]/); return ret("variable", "variable"); } } function tokenCComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (maybeEnd && ch == "/") { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return ret("comment", "comment"); } function tokenSGMLComment(stream, state) { var dashes = 0, ch; while ((ch = stream.next()) != null) { if (dashes >= 2 && ch == ">") { state.tokenize = tokenBase; break; } dashes = (ch == "-") ? dashes + 1 : 0; } return ret("comment", "comment"); } function tokenString(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) break; escaped = !escaped && ch == "\\"; } if (!escaped) state.tokenize = tokenBase; return ret("string", "string"); }; } return { startState: function(base) { return {tokenize: tokenBase, baseIndent: base || 0, stack: []}; }, token: function(stream, state) { if (stream.eatSpace()) return null; type = null; var style = state.tokenize(stream, state); var context = state.stack[state.stack.length-1]; if (type == "hash" && context == "rule") style = "atom"; else if (style == "variable") { if (context == "rule") style = "number"; else if (!context || context == "@media{") style = "tag"; } if (context == "rule" && /^[\{\};]$/.test(type)) state.stack.pop(); if (type == "{") { if (context == "@media") state.stack[state.stack.length-1] = "@media{"; else state.stack.push("{"); } else if (type == "}") state.stack.pop(); else if (type == "@media") state.stack.push("@media"); else if (context == "{" && type != "comment") state.stack.push("rule"); return style; }, indent: function(state, textAfter) { var n = state.stack.length; if (/^\}/.test(textAfter)) n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1; return state.baseIndent + n * indentUnit; }, electricChars: "}" }; }); CodeMirror.defineMIME("text/nginx", "text/x-nginx-conf"); ================================================ FILE: public/packages/codemirror-3.19/mode/ntriples/index.html ================================================ CodeMirror: NTriples mode

            NTriples mode

            MIME types defined: text/n-triples.

            ================================================ FILE: public/packages/codemirror-3.19/mode/ntriples/ntriples.js ================================================ /********************************************************** * 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/ocaml/index.html ================================================ CodeMirror: OCaml mode

            OCaml mode

            MIME types defined: text/x-ocaml.

            ================================================ FILE: public/packages/codemirror-3.19/mode/ocaml/ocaml.js ================================================ 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); }, blockCommentStart: "(*", blockCommentEnd: "*)" }; }); CodeMirror.defineMIME('text/x-ocaml', 'ocaml'); ================================================ FILE: public/packages/codemirror-3.19/mode/octave/index.html ================================================ CodeMirror: Octave mode

            Octave mode

            MIME types defined: text/x-octave.

            ================================================ FILE: public/packages/codemirror-3.19/mode/octave/octave.js ================================================ CodeMirror.defineMode("octave", function() { function wordRegexp(words) { return new RegExp("^((" + words.join(")|(") + "))\\b"); } var singleOperators = new RegExp("^[\\+\\-\\*/&|\\^~<>!@'\\\\]"); var singleDelimiters = new RegExp('^[\\(\\[\\{\\},:=;]'); var doubleOperators = new RegExp("^((==)|(~=)|(<=)|(>=)|(<<)|(>>)|(\\.[\\+\\-\\*/\\^\\\\]))"); var doubleDelimiters = new RegExp("^((!=)|(\\+=)|(\\-=)|(\\*=)|(/=)|(&=)|(\\|=)|(\\^=))"); var tripleDelimiters = new RegExp("^((>>=)|(<<=))"); var expressionEnd = new RegExp("^[\\]\\)]"); var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*"); var builtins = wordRegexp([ 'error', 'eval', 'function', 'abs', 'acos', 'atan', 'asin', 'cos', 'cosh', 'exp', 'log', 'prod', 'log10', 'max', 'min', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'reshape', 'break', 'zeros', 'default', 'margin', 'round', 'ones', 'rand', 'syn', 'ceil', 'floor', 'size', 'clear', 'zeros', 'eye', 'mean', 'std', 'cov', 'det', 'eig', 'inv', 'norm', 'rank', 'trace', 'expm', 'logm', 'sqrtm', 'linspace', 'plot', 'title', 'xlabel', 'ylabel', 'legend', 'text', 'meshgrid', 'mesh', 'num2str' ]); var keywords = wordRegexp([ 'return', 'case', 'switch', 'else', 'elseif', 'end', 'endif', 'endfunction', 'if', 'otherwise', 'do', 'for', 'while', 'try', 'catch', 'classdef', 'properties', 'events', 'methods', 'global', 'persistent', 'endfor', 'endwhile', 'printf', 'disp', 'until', 'continue' ]); // tokenizers function tokenTranspose(stream, state) { if (!stream.sol() && stream.peek() === '\'') { stream.next(); state.tokenize = tokenBase; return 'operator'; } state.tokenize = tokenBase; return tokenBase(stream, state); } function tokenComment(stream, state) { if (stream.match(/^.*%}/)) { state.tokenize = tokenBase; return 'comment'; }; stream.skipToEnd(); return 'comment'; } function tokenBase(stream, state) { // whitespaces if (stream.eatSpace()) return null; // Handle one line Comments if (stream.match('%{')){ state.tokenize = tokenComment; stream.skipToEnd(); return 'comment'; } if (stream.match(/^(%)|(\.\.\.)/)){ stream.skipToEnd(); return 'comment'; } // Handle Number Literals if (stream.match(/^[0-9\.+-]/, false)) { if (stream.match(/^[+-]?0x[0-9a-fA-F]+[ij]?/)) { stream.tokenize = tokenBase; return 'number'; }; if (stream.match(/^[+-]?\d*\.\d+([EeDd][+-]?\d+)?[ij]?/)) { return 'number'; }; if (stream.match(/^[+-]?\d+([EeDd][+-]?\d+)?[ij]?/)) { return 'number'; }; } if (stream.match(wordRegexp(['nan','NaN','inf','Inf']))) { return 'number'; }; // Handle Strings if (stream.match(/^"([^"]|(""))*"/)) { return 'string'; } ; if (stream.match(/^'([^']|(''))*'/)) { return 'string'; } ; // Handle words if (stream.match(keywords)) { return 'keyword'; } ; if (stream.match(builtins)) { return 'builtin'; } ; if (stream.match(identifiers)) { return 'variable'; } ; if (stream.match(singleOperators) || stream.match(doubleOperators)) { return 'operator'; }; if (stream.match(singleDelimiters) || stream.match(doubleDelimiters) || stream.match(tripleDelimiters)) { return null; }; if (stream.match(expressionEnd)) { state.tokenize = tokenTranspose; return null; }; // Handle non-detected items stream.next(); return 'error'; }; return { startState: function() { return { tokenize: tokenBase }; }, token: function(stream, state) { var style = state.tokenize(stream, state); if (style === 'number' || style === 'variable'){ state.tokenize = tokenTranspose; } return style; } }; }); CodeMirror.defineMIME("text/x-octave", "octave"); ================================================ FILE: public/packages/codemirror-3.19/mode/pascal/index.html ================================================ CodeMirror: Pascal mode

            Pascal mode

            MIME types defined: text/x-pascal.

            ================================================ FILE: public/packages/codemirror-3.19/mode/pascal/pascal.js ================================================ 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/perl/index.html ================================================ CodeMirror: Perl mode

            Perl mode

            MIME types defined: text/x-perl.

            ================================================ FILE: public/packages/codemirror-3.19/mode/perl/perl.js ================================================ // 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;}; ================================================ FILE: public/packages/codemirror-3.19/mode/php/index.html ================================================ CodeMirror: PHP mode

            PHP mode

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

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/php/php.js ================================================ (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 yield insteadof finally"), blockKeywords: keywords("catch do else elseif for foreach if switch try while finally"), atoms: keywords("true false null TRUE FALSE NULL __CLASS__ __DIR__ __FILE__ __LINE__ __METHOD__ __FUNCTION__ __NAMESPACE__ __TRAIT__"), 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 hex2bin sleep usleep time mktime gmmktime strftime gmstrftime strtotime date gmdate getdate localtime checkdate flush wordwrap htmlspecialchars htmlentities html_entity_decode md5 md5_file crc32 getimagesize image_type_to_mime_type phpinfo phpversion phpcredits strnatcmp strnatcasecmp substr_count strspn strcspn strtok strtoupper strtolower strpos strrpos strrev hebrev hebrevc nl2br basename dirname pathinfo stripslashes stripcslashes strstr stristr strrchr str_shuffle str_word_count strcoll substr substr_replace quotemeta ucfirst ucwords strtr addslashes addcslashes rtrim str_replace str_repeat count_chars chunk_split trim ltrim strip_tags similar_text explode implode setlocale localeconv parse_str str_pad chop strchr sprintf printf vprintf vsprintf sscanf fscanf parse_url urlencode urldecode rawurlencode rawurldecode readlink linkinfo link unlink exec system escapeshellcmd escapeshellarg passthru shell_exec proc_open proc_close rand srand getrandmax mt_rand mt_srand mt_getrandmax base64_decode base64_encode abs ceil floor round is_finite is_nan is_infinite bindec hexdec octdec decbin decoct dechex base_convert number_format fmod ip2long long2ip getenv putenv getopt microtime gettimeofday getrusage uniqid quoted_printable_decode set_time_limit get_cfg_var magic_quotes_runtime set_magic_quotes_runtime get_magic_quotes_gpc get_magic_quotes_runtime import_request_variables error_log serialize unserialize memory_get_usage var_dump var_export debug_zval_dump print_r highlight_file show_source highlight_string ini_get ini_get_all ini_set ini_alter ini_restore get_include_path set_include_path restore_include_path setcookie header headers_sent connection_aborted connection_status ignore_user_abort parse_ini_file is_uploaded_file move_uploaded_file intval floatval doubleval strval gettype settype is_null is_resource is_bool is_long is_float is_int is_integer is_double is_real is_numeric is_string is_array is_object is_scalar ereg ereg_replace eregi eregi_replace split spliti join sql_regcase dl pclose popen readfile rewind rmdir umask fclose feof fgetc fgets fgetss fread fopen fpassthru ftruncate fstat fseek ftell fflush fwrite fputs mkdir rename copy tempnam tmpfile file file_get_contents 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 http_response_code get_declared_traits getimagesizefromstring socket_import_stream stream_set_chunk_size trait_exists header_register_callback class_uses session_status session_register_shutdown echo print global static exit array empty eval isset unset die include require include_once require_once"), 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: "/{}:", blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: "//", innerMode: function(state) { return {state: state.curState, mode: state.curMode}; } }; }, "htmlmixed", "clike"); CodeMirror.defineMIME("application/x-httpd-php", "php"); CodeMirror.defineMIME("application/x-httpd-php-open", {name: "php", startOpen: true}); CodeMirror.defineMIME("text/x-php", phpConfig); })(); ================================================ FILE: public/packages/codemirror-3.19/mode/pig/index.html ================================================ CodeMirror: Pig Latin mode

            Pig Latin mode

            Simple mode that handles Pig Latin language.

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/pig/pig.js ================================================ /* * 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) }); }()); ================================================ FILE: public/packages/codemirror-3.19/mode/properties/index.html ================================================ CodeMirror: Properties files mode

            Properties files mode

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/properties/properties.js ================================================ 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/python/index.html ================================================ CodeMirror: Python mode

            Python mode

            Cython mode

            Configuration Options for Python mode:

            • version - 2/3 - The version of Python to recognize. Default is 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]*
            • extra_keywords - list of string - List of extra words ton consider as keywords
            • extra_builtins - list of string - List of extra words ton consider as builtins

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/python/python.js ================================================ 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.extra_keywords != undefined){ commonkeywords = commonkeywords.concat(parserConf.extra_keywords); } if(parserConf.extra_builtins != undefined){ commonBuiltins = commonBuiltins.concat(parserConf.extra_builtins); } 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)) { if (state.lastToken == 'def' || state.lastToken == 'class') { return 'def'; } 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.lastStyle === '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.lastStyle === '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'}], lastStyle: null, lastToken: null, lambda: false, dedent: 0 }; }, token: function(stream, state) { var style = tokenLexer(stream, state); state.lastStyle = style; var current = stream.current(); if (current && style) { state.lastToken = current; } if (stream.eol() && state.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; }, lineComment: "#", fold: "indent" }; return external; }); CodeMirror.defineMIME("text/x-python", "python"); (function() { "use strict"; var words = function(str){return str.split(' ');}; CodeMirror.defineMIME("text/x-cython", { name: "python", extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+ "extern gil include nogil property public"+ "readonly struct union DEF IF ELIF ELSE") }); })(); ================================================ FILE: public/packages/codemirror-3.19/mode/q/index.html ================================================ CodeMirror: Q mode

            Q mode

            MIME type defined: text/x-q.

            ================================================ FILE: public/packages/codemirror-3.19/mode/q/q.js ================================================ 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/r/index.html ================================================ CodeMirror: R mode

            R mode

            MIME types defined: text/x-rsrc.

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/r/r.js ================================================ 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/rpm/changes/changes.js ================================================ 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/rpm/changes/index.html ================================================ CodeMirror: RPM changes mode

            RPM changes mode

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/rpm/spec/index.html ================================================ CodeMirror: RPM spec mode

            RPM spec mode

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/rpm/spec/spec.css ================================================ .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;} ================================================ FILE: public/packages/codemirror-3.19/mode/rpm/spec/spec.js ================================================ // 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/rst/index.html ================================================ CodeMirror: reStructuredText mode

            reStructuredText mode

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

            MIME types defined: text/x-rst.

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

            Ruby mode

            MIME types defined: text/x-ruby.

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/ruby/ruby.js ================================================ CodeMirror.defineMode("ruby", function(config) { function wordObj(words) { var o = {}; for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true; return o; } var keywords = wordObj([ "alias", "and", "BEGIN", "begin", "break", "case", "class", "def", "defined?", "do", "else", "elsif", "END", "end", "ensure", "false", "for", "if", "in", "module", "next", "not", "or", "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless", "until", "when", "while", "yield", "nil", "raise", "throw", "catch", "fail", "loop", "callcc", "caller", "lambda", "proc", "public", "protected", "private", "require", "load", "require_relative", "extend", "autoload", "__END__", "__FILE__", "__LINE__", "__dir__" ]); var indentWords = wordObj(["def", "class", "case", "for", "while", "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 == '"') { return chain(readQuoted(ch, "string", ch == '"' || ch == "`"), stream, state); } else if (ch == "/" && !stream.eol() && stream.peek() != " ") { return chain(readQuoted(ch, "string-2", true), stream, state); } else if (ch == "%") { var style = "string", embed = true; if (stream.eat("s")) style = "atom"; else if (stream.eat(/[WQ]/)) style = "string"; else if (stream.eat(/[r]/)) style = "string-2"; else if (stream.eat(/[wxq]/)) { style = "string"; embed = false; } var delim = stream.eat(/[^\w\s]/); if (!delim) return "operator"; if (matching.propertyIsEnumerable(delim)) delim = matching[delim]; return chain(readQuoted(delim, style, embed, true), stream, state); } else if (ch == "#") { stream.skipToEnd(); return "comment"; } else if (ch == "<" && (m = stream.match(/^<-?[\`\"\']?([a-zA-Z_?]\w*)[\`\"\']?(?:;|$)/))) { return chain(readHereDoc(m[1]), stream, state); } else if (ch == "0") { if (stream.eat("x")) stream.eatWhile(/[\da-fA-F]/); else if (stream.eat("b")) stream.eatWhile(/[01]/); else stream.eatWhile(/[0-7]/); return "number"; } else if (/\d/.test(ch)) { stream.match(/^[\d_]*(?:\.[\d_]+)?(?:[eE][+\-]?[\d_]+)?/); return "number"; } else if (ch == "?") { while (stream.match(/^\\[CM]-/)) {} if (stream.eat("\\")) stream.eatWhile(/\w/); else stream.next(); return "string"; } else if (ch == ":") { if (stream.eat("'")) return chain(readQuoted("'", "atom", false), stream, state); if (stream.eat('"')) return chain(readQuoted('"', "atom", true), stream, state); // :> :>> :< :<< are valid symbols if (stream.eat(/[\<\>]/)) { stream.eat(/[\<\>]/); return "atom"; } // :+ :- :/ :* :| :& :! are valid symbols if (stream.eat(/[\+\-\*\/\&\|\:\!]/)) { return "atom"; } // Symbols can't start by a digit if (stream.eat(/[a-zA-Z$@_]/)) { stream.eatWhile(/[\w]/); // Only one ? ! = is allowed and only as the last character stream.eat(/[\?\!\=]/); return "atom"; } return "operator"; } else if (ch == "@" && stream.match(/^@?[a-zA-Z_]/)) { stream.eat("@"); stream.eatWhile(/[\w]/); return "variable-2"; } else if (ch == "$") { if (stream.eat(/[a-zA-Z_]/)) { stream.eatWhile(/[\w]/); } else if (stream.eat(/\d/)) { stream.eat(/\d/); } else { stream.next(); // Must be a special global like $: or $! } return "variable-3"; } else if (/[a-zA-Z_]/.test(ch)) { stream.eatWhile(/[\w]/); stream.eat(/[\?\!]/); if (stream.eat(":")) return "atom"; return "ident"; } else if (ch == "|" && (state.varList || state.lastTok == "{" || state.lastTok == "do")) { curPunc = "|"; return null; } else if (/[\(\)\[\]{}\\;]/.test(ch)) { curPunc = ch; return null; } else if (ch == "-" && stream.eat(">")) { return "arrow"; } else if (/[=+\-\/*:\.^%<>~|]/.test(ch)) { 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 tokenBaseOnce() { var alreadyCalled = false; return function(stream, state) { if (alreadyCalled) { state.tokenize.pop(); return state.tokenize[state.tokenize.length-1](stream, state); } alreadyCalled = true; return tokenBase(stream, state); }; } function readQuoted(quote, style, embed, unescaped) { return function(stream, state) { var escaped = false, ch; if (state.context.type === 'read-quoted-paused') { state.context = state.context.prev; stream.eat("}"); } while ((ch = stream.next()) != null) { if (ch == quote && (unescaped || !escaped)) { state.tokenize.pop(); break; } if (embed && ch == "#" && !escaped) { if (stream.eat("{")) { if (quote == "}") { state.context = {prev: state.context, type: 'read-quoted-paused'}; } state.tokenize.push(tokenBaseUntilBrace()); break; } else if (/[@\$]/.test(stream.peek())) { state.tokenize.push(tokenBaseOnce()); break; } } escaped = !escaped && ch == "\\"; } return style; }; } function readHereDoc(phrase) { 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 lineComment: "#" }; }); CodeMirror.defineMIME("text/x-ruby", "ruby"); ================================================ FILE: public/packages/codemirror-3.19/mode/rust/index.html ================================================ CodeMirror: Rust mode

            Rust mode

            MIME types defined: text/x-rustsrc.

            ================================================ FILE: public/packages/codemirror-3.19/mode/rust/rust.js ================================================ 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: "{}", blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: "//", fold: "brace" }; }); CodeMirror.defineMIME("text/x-rustsrc", "rust"); ================================================ FILE: public/packages/codemirror-3.19/mode/sass/index.html ================================================ CodeMirror: Sass mode

            Sass mode

            MIME types defined: text/x-sass.

            ================================================ FILE: public/packages/codemirror-3.19/mode/sass/sass.js ================================================ CodeMirror.defineMode("sass", function(config) { var tokenRegexp = function(words){ return new RegExp("^" + words.join("|")); }; var keywords = ["true", "false", "null", "auto"]; var keywordsRegexp = new RegExp("^" + keywords.join("|")); var operators = ["\\(", "\\)", "=", ">", "<", "==", ">=", "<=", "\\+", "-", "\\!=", "/", "\\*", "%", "and", "or", "not"]; var opRegexp = tokenRegexp(operators); var pseudoElementsRegexp = /^::?[\w\-]+/; var urlTokens = function(stream, state){ var ch = stream.peek(); if (ch === ")"){ stream.next(); state.tokenizer = tokenBase; return "operator"; }else if (ch === "("){ stream.next(); stream.eatSpace(); return "operator"; }else if (ch === "'" || ch === '"'){ state.tokenizer = buildStringTokenizer(stream.next()); return "string"; }else{ state.tokenizer = buildStringTokenizer(")", false); return "string"; } }; var multilineComment = function(stream, state) { if (stream.skipTo("*/")){ stream.next(); stream.next(); state.tokenizer = tokenBase; }else { stream.next(); } return "comment"; }; var buildStringTokenizer = function(quote, greedy){ if(greedy == null){ greedy = true; } function stringTokenizer(stream, state){ var nextChar = stream.next(); var peekChar = stream.peek(); var previousChar = stream.string.charAt(stream.pos-2); var endingString = ((nextChar !== "\\" && peekChar === quote) || (nextChar === quote && previousChar !== "\\")); /* console.log("previousChar: " + previousChar); console.log("nextChar: " + nextChar); console.log("peekChar: " + peekChar); console.log("ending: " + endingString); */ if (endingString){ if (nextChar !== quote && greedy) { stream.next(); } state.tokenizer = tokenBase; return "string"; }else if (nextChar === "#" && peekChar === "{"){ state.tokenizer = buildInterpolationTokenizer(stringTokenizer); stream.next(); return "operator"; }else { return "string"; } } return stringTokenizer; }; var buildInterpolationTokenizer = function(currentTokenizer){ return function(stream, state){ if (stream.peek() === "}"){ stream.next(); state.tokenizer = currentTokenizer; return "operator"; }else{ return tokenBase(stream, state); } }; }; var indent = function(state){ if (state.indentCount == 0){ state.indentCount++; var lastScopeOffset = state.scopes[0].offset; var currentOffset = lastScopeOffset + config.indentUnit; state.scopes.unshift({ offset:currentOffset }); } }; var dedent = function(state){ if (state.scopes.length == 1) { return; } state.scopes.shift(); }; var tokenBase = function(stream, state) { var ch = stream.peek(); // Single line Comment if (stream.match('//')) { stream.skipToEnd(); return "comment"; } // Multiline Comment if (stream.match('/*')){ state.tokenizer = multilineComment; return state.tokenizer(stream, state); } // Interpolation if (stream.match('#{')){ state.tokenizer = buildInterpolationTokenizer(tokenBase); return "operator"; } if (ch === "."){ stream.next(); // Match class selectors if (stream.match(/^[\w-]+/)){ indent(state); return "atom"; }else if (stream.peek() === "#"){ indent(state); return "atom"; }else{ return "operator"; } } if (ch === "#"){ stream.next(); // Hex numbers if (stream.match(/[0-9a-fA-F]{6}|[0-9a-fA-F]{3}/)){ return "number"; } // ID selectors if (stream.match(/^[\w-]+/)){ indent(state); return "atom"; } if (stream.peek() === "#"){ indent(state); return "atom"; } } // Numbers if (stream.match(/^-?[0-9\.]+/)){ return "number"; } // Units if (stream.match(/^(px|em|in)\b/)){ return "unit"; } if (stream.match(keywordsRegexp)){ return "keyword"; } if (stream.match(/^url/) && stream.peek() === "("){ state.tokenizer = urlTokens; return "atom"; } // Variables if (ch === "$"){ stream.next(); stream.eatWhile(/[\w-]/); if (stream.peek() === ":"){ stream.next(); return "variable-2"; }else{ return "variable-3"; } } if (ch === "!"){ stream.next(); if (stream.match(/^[\w]+/)){ return "keyword"; } return "operator"; } if (ch === "="){ stream.next(); // Match shortcut mixin definition if (stream.match(/^[\w-]+/)){ indent(state); return "meta"; }else { return "operator"; } } if (ch === "+"){ stream.next(); // Match shortcut mixin definition if (stream.match(/^[\w-]+/)){ return "variable-3"; }else { return "operator"; } } // Indent Directives if (stream.match(/^@(else if|if|media|else|for|each|while|mixin|function)/)){ indent(state); return "meta"; } // Other Directives if (ch === "@"){ stream.next(); stream.eatWhile(/[\w-]/); return "meta"; } // Strings if (ch === '"' || ch === "'"){ stream.next(); state.tokenizer = buildStringTokenizer(ch); return "string"; } // Pseudo element selectors if (ch == ':' && stream.match(pseudoElementsRegexp)){ return "keyword"; } // atoms if (stream.eatWhile(/[\w-&]/)){ // matches a property definition if (stream.peek() === ":" && !stream.match(pseudoElementsRegexp, false)) return "property"; else return "atom"; } if (stream.match(opRegexp)){ return "operator"; } // If we haven't returned by now, we move 1 character // and return an error stream.next(); return null; }; var tokenLexer = function(stream, state) { if (stream.sol()){ state.indentCount = 0; } var style = state.tokenizer(stream, state); var current = stream.current(); if (current === "@return"){ dedent(state); } if (style === "atom"){ indent(state); } if (style !== null){ var startOfToken = stream.pos - current.length; var withCurrentIndent = startOfToken + (config.indentUnit * state.indentCount); var newScopes = []; for (var i = 0; i < state.scopes.length; i++){ var scope = state.scopes[i]; if (scope.offset <= withCurrentIndent){ newScopes.push(scope); } } state.scopes = newScopes; } return style; }; return { startState: function() { return { tokenizer: tokenBase, scopes: [{offset: 0, type: 'sass'}], definedVars: [], definedMixins: [] }; }, token: function(stream, state) { var style = tokenLexer(stream, state); state.lastToken = { style: style, content: stream.current() }; return style; }, indent: function(state) { return state.scopes[0].offset; } }; }); CodeMirror.defineMIME("text/x-sass", "sass"); ================================================ FILE: public/packages/codemirror-3.19/mode/scheme/index.html ================================================ CodeMirror: Scheme mode

            Scheme mode

            MIME types defined: text/x-scheme.

            ================================================ FILE: public/packages/codemirror-3.19/mode/scheme/scheme.js ================================================ /** * 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; }, lineComment: ";;" }; }); CodeMirror.defineMIME("text/x-scheme", "scheme"); ================================================ FILE: public/packages/codemirror-3.19/mode/shell/index.html ================================================ CodeMirror: Shell mode

            Shell mode

            MIME types defined: text/x-sh.

            ================================================ FILE: public/packages/codemirror-3.19/mode/shell/shell.js ================================================ 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'); ================================================ FILE: public/packages/codemirror-3.19/mode/sieve/index.html ================================================ CodeMirror: Sieve (RFC5228) mode

            Sieve (RFC5228) mode

            MIME types defined: application/sieve.

            ================================================ FILE: public/packages/codemirror-3.19/mode/sieve/sieve.js ================================================ /* * 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/smalltalk/index.html ================================================ CodeMirror: Smalltalk mode

            Smalltalk mode

            Simple Smalltalk mode.

            MIME types defined: text/x-stsrc.

            ================================================ FILE: public/packages/codemirror-3.19/mode/smalltalk/smalltalk.js ================================================ CodeMirror.defineMode('smalltalk', function(config) { var specialChars = /[+\-\/\\*~<>=@%|&?!.,:;^]/; var keywords = /true|false|nil|self|super|thisContext/; var Context = function(tokenizer, parent) { this.next = tokenizer; this.parent = parent; }; var Token = function(name, context, eos) { this.name = name; this.context = context; this.eos = eos; }; var State = function() { this.context = new Context(next, null); this.expectVariable = true; this.indentation = 0; this.userIndentationDelta = 0; }; State.prototype.userIndent = function(indentation) { this.userIndentationDelta = indentation > 0 ? (indentation / config.indentUnit - this.indentation) : 0; }; var next = function(stream, context, state) { var token = new Token(null, context, false); var aChar = stream.next(); if (aChar === '"') { token = nextComment(stream, new Context(nextComment, context)); } else if (aChar === '\'') { token = nextString(stream, new Context(nextString, context)); } else if (aChar === '#') { if (stream.peek() === '\'') { stream.next(); token = nextSymbol(stream, new Context(nextSymbol, context)); } else { stream.eatWhile(/[^ .\[\]()]/); token.name = 'string-2'; } } else if (aChar === '$') { if (stream.next() === '<') { stream.eatWhile(/[^ >]/); stream.next(); } token.name = 'string-2'; } else if (aChar === '|' && state.expectVariable) { token.context = new Context(nextTemporaries, context); } else if (/[\[\]{}()]/.test(aChar)) { token.name = 'bracket'; token.eos = /[\[{(]/.test(aChar); if (aChar === '[') { state.indentation++; } else if (aChar === ']') { state.indentation = Math.max(0, state.indentation - 1); } } else if (specialChars.test(aChar)) { stream.eatWhile(specialChars); token.name = 'operator'; token.eos = aChar !== ';'; // ; cascaded message expression } else if (/\d/.test(aChar)) { stream.eatWhile(/[\w\d]/); token.name = 'number'; } else if (/[\w_]/.test(aChar)) { stream.eatWhile(/[\w\d_]/); token.name = state.expectVariable ? (keywords.test(stream.current()) ? 'keyword' : 'variable') : null; } else { token.eos = state.expectVariable; } return token; }; var nextComment = function(stream, context) { stream.eatWhile(/[^"]/); return new Token('comment', stream.eat('"') ? context.parent : context, true); }; var nextString = function(stream, context) { stream.eatWhile(/[^']/); return new Token('string', stream.eat('\'') ? context.parent : context, false); }; var nextSymbol = function(stream, context) { stream.eatWhile(/[^']/); return new Token('string-2', stream.eat('\'') ? context.parent : context, false); }; var nextTemporaries = function(stream, context) { var token = new Token(null, context, false); var aChar = stream.next(); if (aChar === '|') { token.context = context.parent; token.eos = true; } else { stream.eatWhile(/[^|]/); token.name = 'variable'; } return token; }; return { startState: function() { return new State; }, token: function(stream, state) { state.userIndent(stream.indentation()); if (stream.eatSpace()) { return null; } var token = state.context.next(stream, state.context, state); state.context = token.context; state.expectVariable = token.eos; return token.name; }, blankLine: function(state) { state.userIndent(0); }, indent: function(state, textAfter) { var i = state.context.next === next && textAfter && textAfter.charAt(0) === ']' ? -1 : state.userIndentationDelta; return (state.indentation + i) * config.indentUnit; }, electricChars: ']' }; }); CodeMirror.defineMIME('text/x-stsrc', {name: 'smalltalk'}); ================================================ FILE: public/packages/codemirror-3.19/mode/smarty/index.html ================================================ CodeMirror: Smarty mode

            Smarty mode


            Smarty 2, custom delimiters


            Smarty 3

            A plain text/Smarty version 2 or 3 mode, which allows for custom delimiter tags.

            MIME types defined: text/x-smarty

            ================================================ FILE: public/packages/codemirror-3.19/mode/smarty/smarty.js ================================================ /** * Smarty 2 and 3 mode. */ CodeMirror.defineMode("smarty", function(config) { "use strict"; // our default settings; check to see if they're overridden var settings = { rightDelimiter: '}', leftDelimiter: '{', smartyVersion: 2 // for backward compatibility }; if (config.hasOwnProperty("leftDelimiter")) { settings.leftDelimiter = config.leftDelimiter; } if (config.hasOwnProperty("rightDelimiter")) { settings.rightDelimiter = config.rightDelimiter; } if (config.hasOwnProperty("smartyVersion") && config.smartyVersion === 3) { settings.smartyVersion = 3; } var keyFunctions = ["debug", "extends", "function", "include", "literal"]; var last; var regs = { operatorChars: /[+\-*&%=<>!?]/, validIdentifier: /[a-zA-Z0-9_]/, stringChar: /['"]/ }; var helpers = { cont: function(style, lastType) { last = lastType; return style; }, chain: function(stream, state, parser) { state.tokenize = parser; return parser(stream, state); } }; // our various parsers var parsers = { // the main tokenizer tokenizer: function(stream, state) { if (stream.match(settings.leftDelimiter, true)) { if (stream.eat("*")) { return helpers.chain(stream, state, parsers.inBlock("comment", "*" + settings.rightDelimiter)); } else { // Smarty 3 allows { and } surrounded by whitespace to NOT slip into Smarty mode state.depth++; var isEol = stream.eol(); var isFollowedByWhitespace = /\s/.test(stream.peek()); if (settings.smartyVersion === 3 && settings.leftDelimiter === "{" && (isEol || isFollowedByWhitespace)) { state.depth--; return null; } else { state.tokenize = parsers.smarty; last = "startTag"; return "tag"; } } } else { stream.next(); return null; } }, // parsing Smarty content smarty: function(stream, state) { if (stream.match(settings.rightDelimiter, true)) { if (settings.smartyVersion === 3) { state.depth--; if (state.depth <= 0) { state.tokenize = parsers.tokenizer; } } else { state.tokenize = parsers.tokenizer; } return helpers.cont("tag", null); } if (stream.match(settings.leftDelimiter, true)) { state.depth++; return helpers.cont("tag", "startTag"); } var ch = stream.next(); if (ch == "$") { stream.eatWhile(regs.validIdentifier); return helpers.cont("variable-2", "variable"); } else if (ch == "|") { return helpers.cont("operator", "pipe"); } else if (ch == ".") { return helpers.cont("operator", "property"); } else if (regs.stringChar.test(ch)) { state.tokenize = parsers.inAttribute(ch); return helpers.cont("string", "string"); } else if (regs.operatorChars.test(ch)) { stream.eatWhile(regs.operatorChars); return helpers.cont("operator", "operator"); } else if (ch == "[" || ch == "]") { return helpers.cont("bracket", "bracket"); } else if (ch == "(" || ch == ")") { return helpers.cont("bracket", "operator"); } else if (/\d/.test(ch)) { stream.eatWhile(/\d/); return helpers.cont("number", "number"); } else { if (state.last == "variable") { if (ch == "@") { stream.eatWhile(regs.validIdentifier); return helpers.cont("property", "property"); } else if (ch == "|") { stream.eatWhile(regs.validIdentifier); return helpers.cont("qualifier", "modifier"); } } else if (state.last == "pipe") { stream.eatWhile(regs.validIdentifier); return helpers.cont("qualifier", "modifier"); } else if (state.last == "whitespace") { stream.eatWhile(regs.validIdentifier); return helpers.cont("attribute", "modifier"); } if (state.last == "property") { stream.eatWhile(regs.validIdentifier); return helpers.cont("property", null); } else if (/\s/.test(ch)) { last = "whitespace"; return null; } var str = ""; if (ch != "/") { str += ch; } var c = null; while (c = stream.eat(regs.validIdentifier)) { str += c; } for (var i=0, j=keyFunctions.length; i CodeMirror: Smarty mixed mode

            Smarty mixed mode

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

            It takes the same options, as Smarty and HTML mixed modes.

            MIME types defined: text/x-smarty.

            ================================================ FILE: public/packages/codemirror-3.19/mode/smartymixed/smartymixed.js ================================================ /** * @file smartymixed.js * @brief Smarty Mixed Codemirror mode (Smarty + Mixed HTML) * @author Ruslan Osmanov * @version 3.0 * @date 05.07.2013 */ CodeMirror.defineMode("smartymixed", function(config) { var settings, regs, helpers, parsers, htmlMixedMode = CodeMirror.getMode(config, "htmlmixed"), smartyMode = CodeMirror.getMode(config, "smarty"), settings = { rightDelimiter: '}', leftDelimiter: '{' }; if (config.hasOwnProperty("leftDelimiter")) { settings.leftDelimiter = config.leftDelimiter; } if (config.hasOwnProperty("rightDelimiter")) { settings.rightDelimiter = config.rightDelimiter; } regs = { smartyComment: new RegExp("^" + settings.leftDelimiter + "\\*"), literalOpen: new RegExp(settings.leftDelimiter + "literal" + settings.rightDelimiter), literalClose: new RegExp(settings.leftDelimiter + "\/literal" + settings.rightDelimiter), hasLeftDelimeter: new RegExp(".*" + settings.leftDelimiter), htmlHasLeftDelimeter: new RegExp("[^<>]*" + settings.leftDelimiter) }; helpers = { chain: function(stream, state, parser) { state.tokenize = parser; return parser(stream, state); }, cleanChain: function(stream, state, parser) { state.tokenize = null; state.localState = null; state.localMode = null; return (typeof parser == "string") ? (parser ? parser : null) : parser(stream, state); }, maybeBackup: function(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; } }; parsers = { html: function(stream, state) { if (!state.inLiteral && stream.match(regs.htmlHasLeftDelimeter, false) && state.htmlMixedState.htmlState.tagName === null) { state.tokenize = parsers.smarty; state.localMode = smartyMode; state.localState = smartyMode.startState(htmlMixedMode.indent(state.htmlMixedState, "")); return helpers.maybeBackup(stream, settings.leftDelimiter, smartyMode.token(stream, state.localState)); } else if (!state.inLiteral && stream.match(settings.leftDelimiter, false)) { state.tokenize = parsers.smarty; state.localMode = smartyMode; state.localState = smartyMode.startState(htmlMixedMode.indent(state.htmlMixedState, "")); return helpers.maybeBackup(stream, settings.leftDelimiter, smartyMode.token(stream, state.localState)); } return htmlMixedMode.token(stream, state.htmlMixedState); }, smarty: function(stream, state) { if (stream.match(settings.leftDelimiter, false)) { if (stream.match(regs.smartyComment, false)) { return helpers.chain(stream, state, parsers.inBlock("comment", "*" + settings.rightDelimiter)); } } else if (stream.match(settings.rightDelimiter, false)) { stream.eat(settings.rightDelimiter); state.tokenize = parsers.html; state.localMode = htmlMixedMode; state.localState = state.htmlMixedState; return "tag"; } return helpers.maybeBackup(stream, settings.rightDelimiter, smartyMode.token(stream, state.localState)); }, inBlock: function(style, terminator) { return function(stream, state) { while (!stream.eol()) { if (stream.match(terminator)) { helpers.cleanChain(stream, state, ""); break; } stream.next(); } return style; }; } }; return { startState: function() { var state = htmlMixedMode.startState(); return { token: parsers.html, localMode: null, localState: null, htmlMixedState: state, tokenize: null, inLiteral: false }; }, copyState: function(state) { var local = null, tok = (state.tokenize || state.token); if (state.localState) { local = CodeMirror.copyState((tok != parsers.html ? smartyMode : htmlMixedMode), state.localState); } return { token: state.token, tokenize: state.tokenize, localMode: state.localMode, localState: local, htmlMixedState: CodeMirror.copyState(htmlMixedMode, state.htmlMixedState), inLiteral: state.inLiteral }; }, token: function(stream, state) { if (stream.match(settings.leftDelimiter, false)) { if (!state.inLiteral && stream.match(regs.literalOpen, true)) { state.inLiteral = true; return "keyword"; } else if (state.inLiteral && stream.match(regs.literalClose, true)) { state.inLiteral = false; return "keyword"; } } if (state.inLiteral && state.localState != state.htmlMixedState) { state.tokenize = parsers.html; state.localMode = htmlMixedMode; state.localState = state.htmlMixedState; } var style = (state.tokenize || state.token)(stream, state); return style; }, indent: function(state, textAfter) { if (state.localMode == smartyMode || (state.inLiteral && !state.localMode) || regs.hasLeftDelimeter.test(textAfter)) { return CodeMirror.Pass; } return htmlMixedMode.indent(state.htmlMixedState, textAfter); }, electricChars: "/{}:", innerMode: function(state) { return { state: state.localState || state.htmlMixedState, mode: state.localMode || htmlMixedMode }; } }; }, "htmlmixed"); CodeMirror.defineMIME("text/x-smarty", "smartymixed"); // vim: et ts=2 sts=2 sw=2 ================================================ FILE: public/packages/codemirror-3.19/mode/sparql/index.html ================================================ CodeMirror: SPARQL mode

            SPARQL mode

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/sparql/sparql.js ================================================ 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", "a"]); var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe", "ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional", "graph", "by", "asc", "desc", "as", "having", "undef", "values", "group", "minus", "in", "not", "service", "silent", "using", "insert", "delete", "union", "data", "copy", "to", "move", "add", "create", "drop", "clear", "load"]); 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/sql/index.html ================================================ CodeMirror: SQL Mode for CodeMirror

            SQL Mode for CodeMirror

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/sql/sql.js ================================================ 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 (support.hexNumber == true && ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/)) || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) { // hex // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html return "number"; } else if (support.binaryNumber == true && (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/)) || (ch == "0" && stream.match(/^b[01]+/)))) { // bitstring // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html return "number"; } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) { // numbers // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html stream.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/); support.decimallessFloat == true && stream.eat('.'); return "number"; } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) { // placeholders return "variable-3"; } else if (ch == "'" || (ch == '"' && support.doubleQuote)) { // strings // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html state.tokenize = tokenLiteral(ch); return state.tokenize(stream, state); } else if ((((support.nCharCast == true && (ch == "n" || ch == "N")) || (support.charsetCast == true && ch == "_" && stream.match(/[a-z][a-z0-9]*/i))) && (stream.peek() == "'" || stream.peek() == '"'))) { // charset casting: _utf8'str', N'str', n'str' // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html return "keyword"; } else if (/^[\(\),\;\[\]]/.test(ch)) { // no highlightning return null; } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) { // 1-line comment stream.skipToEnd(); return "comment"; } else if ((support.commentHash && ch == "#") || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) { // 1-line comments // ref: https://kb.askmonty.org/en/comment-syntax/ stream.skipToEnd(); return "comment"; } else if (ch == "/" && stream.eat("*")) { // multi-line comments // ref: https://kb.askmonty.org/en/comment-syntax/ state.tokenize = tokenComment; return state.tokenize(stream, state); } else if (ch == ".") { // .1 for 0.1 if (support.zerolessFloat == true && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) { return "number"; } // .table_name (ODBC) // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html if (support.ODBCdotTable == true && stream.match(/^[a-zA-Z_]+/)) { 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) // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html return "number"; } else { stream.eatWhile(/^[_\w\d]/); var word = stream.current().toLowerCase(); // dates (standard SQL syntax) // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/))) return "number"; if (atoms.hasOwnProperty(word)) return "atom"; if (builtin.hasOwnProperty(word)) return "builtin"; if (keywords.hasOwnProperty(word)) return "keyword"; if (client.hasOwnProperty(word)) return "string-2"; return null; } } // 'string', with char specified in quote escaped by '\' function tokenLiteral(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) { state.tokenize = tokenBase; break; } escaped = !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; }, blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : null }; }); (function() { "use strict"; // `identifier` function hookIdentifier(stream) { // MySQL/MariaDB identifiers // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html var ch; while ((ch = stream.next()) != null) { if (ch == "`" && !stream.eat("`")) return "variable-2"; } return null; } // variable token function hookVar(stream) { // variables // @@prefix.varName @varName // varName can be quoted with ` or ' or " // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html if (stream.eat("@")) { stream.match(/^session\./); stream.match(/^local\./); stream.match(/^global\./); } if (stream.eat("'")) { stream.match(/^.*'/); return "variable-2"; } else if (stream.eat('"')) { stream.match(/^.*"/); return "variable-2"; } else if (stream.eat("`")) { stream.match(/^.*`/); return "variable-2"; } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) { return "variable-2"; } return null; }; // short client keyword token function hookClient(stream) { // \N means NULL // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html if (stream.eat("N")) { return "atom"; } // \g, etc // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null; } // these keywords are used by all SQL dialects (however, a mode can still overwrite it) var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from having in insert into is join like not on or order select set table union update values where "; // turn a space-separated list into an array function set(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } // A generic SQL Mode. It's not a standard, it just try to support what is generally supported CodeMirror.defineMIME("text/x-sql", { name: "sql", keywords: set(sqlKeywords + "begin"), builtin: set("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 doubleQuote binaryNumber hexNumber") }); CodeMirror.defineMIME("text/x-mssql", { 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 + "begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered"), builtin: set("bigint numeric bit smallint decimal smallmoney int tinyint money float real char varchar text nchar nvarchar ntext binary varbinary image cursor timestamp hierarchyid uniqueidentifier sql_variant xml table "), atoms: set("false true null unknown"), operatorChars: /^[*+\-%<>!=]/, dateSQL: set("date datetimeoffset datetime2 smalldatetime datetime time"), hooks: { "@": hookVar } }); CodeMirror.defineMIME("text/x-mysql", { name: "sql", client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"), keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group 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 install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"), builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"), atoms: set("false true null unknown"), operatorChars: /^[*+\-%<>!=&|^]/, dateSQL: set("date time timestamp"), support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"), hooks: { "@": hookVar, "`": hookIdentifier, "\\": hookClient } }); CodeMirror.defineMIME("text/x-mariadb", { name: "sql", client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"), keywords: set(sqlKeywords + "accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated get global grant grants group groupby_concat handler hard hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show shutdown signal slave slow smallint snapshot soft soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"), builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"), atoms: set("false true null unknown"), operatorChars: /^[*+\-%<>!=&|^]/, dateSQL: set("date time timestamp"), support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"), hooks: { "@": hookVar, "`": hookIdentifier, "\\": hookClient } }); // the query language used by Apache Cassandra is called CQL, but this mime type // is called Cassandra to avoid confusion with Contextual Query Language CodeMirror.defineMIME("text/x-cassandra", { name: "sql", client: { }, keywords: set("use select from using consistency where limit first reversed first and in insert into values using consistency ttl update set delete truncate begin batch apply create keyspace with columnfamily primary key index on drop alter type add any one quorum all local_quorum each_quorum"), builtin: set("ascii bigint blob boolean counter decimal double float int text timestamp uuid varchar varint"), atoms: set("false true"), operatorChars: /^[<>=]/, dateSQL: { }, support: set("commentSlashSlash decimallessFloat"), hooks: { } }); // this is based on Peter Raganitsch's 'plsql' mode CodeMirror.defineMIME("text/x-plsql", { name: "sql", client: set("appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap"), keywords: set("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else 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"), 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 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"), operatorChars: /^[*+\-%<>!=~]/, dateSQL: set("date time timestamp"), support: set("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber") }); }()); /* How Properties of Mime Types are used by SQL Mode ================================================= keywords: A list of keywords you want to be highlighted. functions: A list of function names you want to be highlighted. builtin: A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword"). operatorChars: All characters that must be handled as operators. client: Commands parsed and executed by the client (not the server). support: A list of supported syntaxes which are not common, but are supported by more than 1 DBMS. * ODBCdotTable: .tableName * zerolessFloat: .1 * doubleQuote * nCharCast: N'string' * charsetCast: _utf8'string' * commentHash: use # char for comments * commentSlashSlash: use // for comments * commentSpaceRequired: require a space after -- for comments atoms: Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others: UNKNOWN, INFINITY, UNDERFLOW, NaN... dateSQL: Used for date/time SQL standard syntax, because not all DBMS's support same temporal types. */ ================================================ FILE: public/packages/codemirror-3.19/mode/stex/index.html ================================================ CodeMirror: sTeX mode

            sTeX mode

            MIME types defined: text/x-stex.

            Parsing/Highlighting Tests: normal, verbose.

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

            Tcl mode

            MIME types defined: text/x-tcl.

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

            TiddlyWiki mode

            TiddlyWiki mode supports a single configuration.

            MIME types defined: text/x-tiddlywiki.

            ================================================ FILE: public/packages/codemirror-3.19/mode/tiddlywiki/tiddlywiki.css ================================================ span.cm-underlined { text-decoration: underline; } span.cm-strikethrough { text-decoration: line-through; } span.cm-brace { color: #170; font-weight: bold; } span.cm-table { color: blue; font-weight: bold; } ================================================ FILE: public/packages/codemirror-3.19/mode/tiddlywiki/tiddlywiki.js ================================================ /*** |''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"); //}}} ================================================ FILE: public/packages/codemirror-3.19/mode/tiki/index.html ================================================ CodeMirror: Tiki wiki mode

            Tiki wiki mode

            ================================================ FILE: public/packages/codemirror-3.19/mode/tiki/tiki.css ================================================ .cm-tw-syntaxerror { color: #FFF; background-color: #900; } .cm-tw-deleted { text-decoration: line-through; } .cm-tw-header5 { font-weight: bold; } .cm-tw-listitem:first-child { /*Added first child to fix duplicate padding when highlighting*/ padding-left: 10px; } .cm-tw-box { border-top-width: 0px ! important; border-style: solid; border-width: 1px; border-color: inherit; } .cm-tw-underline { text-decoration: underline; } ================================================ FILE: public/packages/codemirror-3.19/mode/tiki/tiki.js ================================================ 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: "/" }; }); CodeMirror.defineMIME("text/tiki", "tiki"); ================================================ FILE: public/packages/codemirror-3.19/mode/toml/index.html ================================================ CodeMirror: TOML Mode

            TOML Mode

            The TOML Mode

            Created by Forbes Lindesay.

            MIME type defined: text/x-toml.

            ================================================ FILE: public/packages/codemirror-3.19/mode/toml/toml.js ================================================ CodeMirror.defineMode("toml", function () { return { startState: function () { return { inString: false, stringType: "", lhs: true, inArray: 0 }; }, token: function (stream, state) { //check for state changes if (!state.inString && ((stream.peek() == '"') || (stream.peek() == "'"))) { state.stringType = stream.peek(); stream.next(); // Skip quote state.inString = true; // Update state } if (stream.sol() && state.inArray === 0) { state.lhs = true; } //return state if (state.inString) { while (state.inString && !stream.eol()) { if (stream.peek() === state.stringType) { stream.next(); // Skip quote state.inString = false; // Clear flag } else if (stream.peek() === '\\') { stream.next(); stream.next(); } else { stream.match(/^.[^\\\"\']*/); } } return state.lhs ? "property string" : "string"; // Token style } else if (state.inArray && stream.peek() === ']') { stream.next(); state.inArray--; return 'bracket'; } else if (state.lhs && stream.peek() === '[' && stream.skipTo(']')) { stream.next();//skip closing ] return "atom"; } else if (stream.peek() === "#") { stream.skipToEnd(); return "comment"; } else if (stream.eatSpace()) { return null; } else if (state.lhs && stream.eatWhile(function (c) { return c != '=' && c != ' '; })) { return "property"; } else if (state.lhs && stream.peek() === "=") { stream.next(); state.lhs = false; return null; } else if (!state.lhs && stream.match(/^\d\d\d\d[\d\-\:\.T]*Z/)) { return 'atom'; //date } else if (!state.lhs && (stream.match('true') || stream.match('false'))) { return 'atom'; } else if (!state.lhs && stream.peek() === '[') { state.inArray++; stream.next(); return 'bracket'; } else if (!state.lhs && stream.match(/^\-?\d+(?:\.\d+)?/)) { return 'number'; } else if (!stream.eatSpace()) { stream.next(); } return null; } }; }); CodeMirror.defineMIME('text/x-toml', 'toml'); ================================================ FILE: public/packages/codemirror-3.19/mode/turtle/index.html ================================================ CodeMirror: Turtle mode

            Turtle mode

            MIME types defined: text/turtle.

            ================================================ FILE: public/packages/codemirror-3.19/mode/turtle/turtle.js ================================================ 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/vb/index.html ================================================ CodeMirror: VB.NET mode

            VB.NET mode

            
              

            MIME type defined: text/x-vb.

            ================================================ FILE: public/packages/codemirror-3.19/mode/vb/vb.js ================================================ 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"); ================================================ FILE: public/packages/codemirror-3.19/mode/vbscript/index.html ================================================ CodeMirror: VBScript mode

            VBScript mode

            MIME types defined: text/vbscript.

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

            Velocity mode

            MIME types defined: text/velocity.

            ================================================ FILE: public/packages/codemirror-3.19/mode/velocity/velocity.js ================================================ CodeMirror.defineMode("velocity", function() { function parseWords(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var keywords = parseWords("#end #else #break #stop #[[ #]] " + "#{end} #{else} #{break} #{stop}"); var functions = parseWords("#if #elseif #foreach #set #include #parse #macro #define #evaluate " + "#{if} #{elseif} #{foreach} #{set} #{include} #{parse} #{macro} #{define} #{evaluate}"); var specials = parseWords("$foreach.count $foreach.hasNext $foreach.first $foreach.last $foreach.topmost $foreach.parent.count $foreach.parent.hasNext $foreach.parent.first $foreach.parent.last $foreach.parent $velocityCount $!bodyContent $bodyContent"); var isOperatorChar = /[+\-*&%=<>!?:\/|]/; function chain(stream, state, f) { state.tokenize = f; return f(stream, state); } function tokenBase(stream, state) { var beforeParams = state.beforeParams; state.beforeParams = false; var ch = stream.next(); // start of unparsed string? if ((ch == "'") && state.inParams) { state.lastTokenWasBuiltin = false; return chain(stream, state, tokenString(ch)); } // start of parsed string? else if ((ch == '"')) { state.lastTokenWasBuiltin = false; if (state.inString) { state.inString = false; return "string"; } else if (state.inParams) return chain(stream, state, tokenString(ch)); } // is it one of the special signs []{}().,;? Seperator? else if (/[\[\]{}\(\),;\.]/.test(ch)) { if (ch == "(" && beforeParams) state.inParams = true; else if (ch == ")") { state.inParams = false; state.lastTokenWasBuiltin = true; } return null; } // start of a number value? else if (/\d/.test(ch)) { state.lastTokenWasBuiltin = false; stream.eatWhile(/[\w\.]/); return "number"; } // multi line comment? else if (ch == "#" && stream.eat("*")) { state.lastTokenWasBuiltin = false; return chain(stream, state, tokenComment); } // unparsed content? else if (ch == "#" && stream.match(/ *\[ *\[/)) { state.lastTokenWasBuiltin = false; return chain(stream, state, tokenUnparsed); } // single line comment? else if (ch == "#" && stream.eat("#")) { state.lastTokenWasBuiltin = false; stream.skipToEnd(); return "comment"; } // variable? else if (ch == "$") { stream.eatWhile(/[\w\d\$_\.{}]/); // is it one of the specials? if (specials && specials.propertyIsEnumerable(stream.current())) { return "keyword"; } else { state.lastTokenWasBuiltin = true; state.beforeParams = true; return "builtin"; } } // is it a operator? else if (isOperatorChar.test(ch)) { state.lastTokenWasBuiltin = false; stream.eatWhile(isOperatorChar); return "operator"; } else { // get the whole word stream.eatWhile(/[\w\$_{}@]/); var word = stream.current(); // is it one of the listed keywords? if (keywords && keywords.propertyIsEnumerable(word)) return "keyword"; // is it one of the listed functions? if (functions && functions.propertyIsEnumerable(word) || (stream.current().match(/^#@?[a-z0-9_]+ *$/i) && stream.peek()=="(") && !(functions && functions.propertyIsEnumerable(word.toLowerCase()))) { state.beforeParams = true; state.lastTokenWasBuiltin = false; return "keyword"; } if (state.inString) { state.lastTokenWasBuiltin = false; return "string"; } if (stream.pos > word.length && stream.string.charAt(stream.pos-word.length-1)=="." && state.lastTokenWasBuiltin) return "builtin"; // default: just a "word" state.lastTokenWasBuiltin = false; return null; } } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if ((next == quote) && !escaped) { end = true; break; } if (quote=='"' && stream.peek() == '$' && !escaped) { state.inString = true; end = true; break; } escaped = !escaped && next == "\\"; } if (end) state.tokenize = tokenBase; return "string"; }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "#" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return "comment"; } function tokenUnparsed(stream, state) { var maybeEnd = 0, ch; while (ch = stream.next()) { if (ch == "#" && maybeEnd == 2) { state.tokenize = tokenBase; break; } if (ch == "]") maybeEnd++; else if (ch != " ") maybeEnd = 0; } return "meta"; } // Interface return { startState: function() { return { tokenize: tokenBase, beforeParams: false, inParams: false, inString: false, lastTokenWasBuiltin: false }; }, token: function(stream, state) { if (stream.eatSpace()) return null; return state.tokenize(stream, state); }, blockCommentStart: "#*", blockCommentEnd: "*#", lineComment: "##", fold: "velocity" }; }); CodeMirror.defineMIME("text/velocity", "velocity"); ================================================ FILE: public/packages/codemirror-3.19/mode/verilog/index.html ================================================ CodeMirror: Verilog mode

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/verilog/verilog.js ================================================ 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

            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.

            ================================================ FILE: public/packages/codemirror-3.19/mode/xml/xml.js ================================================ CodeMirror.defineMode("xml", function(config, parserConfig) { var indentUnit = config.indentUnit; var multilineTagIndentFactor = parserConfig.multilineTagIndentFactor || 1; var multilineTagIndentPastTag = parserConfig.multilineTagIndentPastTag || true; 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 "tag 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 (ch == "<") { state.tokenize = inText; var next = state.tokenize(stream, state); return next ? next + " error" : "error"; } else if (/[\'\"]/.test(ch)) { state.tokenize = inAttribute(ch); state.stringStartCol = stream.column(); return state.tokenize(stream, state); } else { stream.eatWhile(/[^\s\u00a0=<>\"\']/); return "word"; } } function inAttribute(quote) { var closure = function(stream, state) { while (!stream.eol()) { if (stream.next() == quote) { state.tokenize = inTag; break; } } return "string"; }; closure.isInAttribute = true; return closure; } function inBlock(style, terminator) { return function(stream, state) { while (!stream.eol()) { if (stream.match(terminator)) { state.tokenize = inText; break; } stream.next(); } return style; }; } function doctype(depth) { return function(stream, state) { var ch; while ((ch = stream.next()) != null) { if (ch == "<") { state.tokenize = doctype(depth + 1); return state.tokenize(stream, state); } else if (ch == ">") { if (depth == 1) { state.tokenize = inText; break; } else { state.tokenize = doctype(depth - 1); return state.tokenize(stream, state); } } } return "meta"; }; } var curState, curStream, 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; curState.tagStart = curStream.column(); 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 = curState.tagStart = 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 cont(attribute, attributes);} 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, tagStart: null, context: null}; }, token: function(stream, state) { if (!state.tagName && 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; curStream = stream; while (true) { var comb = state.cc.pop() || element; if (comb(type || style)) break; } } state.startOfLine = false; if (setStyle) style = setStyle == "error" ? style + " error" : setStyle; return style; }, indent: function(state, textAfter, fullLine) { var context = state.context; // Indent multi-line strings (e.g. css). if (state.tokenize.isInAttribute) { return state.stringStartCol + 1; } if ((state.tokenize != inTag && state.tokenize != inText) || context && context.noIndent) return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; // Indent the starts of attribute names. if (state.tagName) { if (multilineTagIndentPastTag) return state.tagStart + state.tagName.length + 2; else return state.tagStart + indentUnit * multilineTagIndentFactor; } if (alignCDATA && /", configuration: parserConfig.htmlMode ? "html" : "xml", helperType: parserConfig.htmlMode ? "html" : "xml" }; }); CodeMirror.defineMIME("text/xml", "xml"); CodeMirror.defineMIME("application/xml", "xml"); if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true}); ================================================ FILE: public/packages/codemirror-3.19/mode/xquery/index.html ================================================ CodeMirror: XQuery mode

            XQuery mode

            MIME types defined: application/xquery.

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

            ================================================ FILE: public/packages/codemirror-3.19/mode/xquery/test.js ================================================ // 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\\\"])"); })(); ================================================ FILE: public/packages/codemirror-3.19/mode/xquery/xquery.js ================================================ 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", 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; }, blockCommentStart: "(:", blockCommentEnd: ":)" }; }); CodeMirror.defineMIME("application/xquery", "xquery"); ================================================ FILE: public/packages/codemirror-3.19/mode/yaml/index.html ================================================ CodeMirror: YAML mode

            YAML mode

            MIME types defined: text/x-yaml.

            ================================================ FILE: public/packages/codemirror-3.19/mode/yaml/yaml.js ================================================ CodeMirror.defineMode("yaml", function() { var cons = ['true', 'false', 'on', 'off', 'yes', 'no']; var keywordRegex = new RegExp("\\b(("+cons.join(")|(")+"))$", 'i'); return { token: function(stream, state) { var ch = stream.peek(); var esc = state.escaped; state.escaped = false; /* comments */ if (ch == "#" && (stream.pos == 0 || /\s/.test(stream.string.charAt(stream.pos - 1)))) { stream.skipToEnd(); return "comment"; } if (state.literal && stream.indentation() > state.keyCol) { stream.skipToEnd(); return "string"; } else if (state.literal) { state.literal = false; } if (stream.sol()) { state.keyCol = 0; state.pair = false; state.pairStart = false; /* document start */ if(stream.match(/---/)) { return "def"; } /* document end */ if (stream.match(/\.\.\./)) { return "def"; } /* array list item */ if (stream.match(/\s*-\s+/)) { return 'meta'; } } /* inline pairs/lists */ if (stream.match(/^(\{|\}|\[|\])/)) { if (ch == '{') state.inlinePairs++; else if (ch == '}') state.inlinePairs--; else if (ch == '[') state.inlineList++; else state.inlineList--; return 'meta'; } /* list seperator */ if (state.inlineList > 0 && !esc && ch == ',') { stream.next(); return 'meta'; } /* pairs seperator */ if (state.inlinePairs > 0 && !esc && ch == ',') { state.keyCol = 0; state.pair = false; state.pairStart = false; stream.next(); return 'meta'; } /* start of value of a pair */ if (state.pairStart) { /* block literals */ if (stream.match(/^\s*(\||\>)\s*/)) { state.literal = true; return 'meta'; }; /* references */ if (stream.match(/^\s*(\&|\*)[a-z0-9\._-]+\b/i)) { return 'variable-2'; } /* numbers */ if (state.inlinePairs == 0 && stream.match(/^\s*-?[0-9\.\,]+\s?$/)) { return 'number'; } if (state.inlinePairs > 0 && stream.match(/^\s*-?[0-9\.\,]+\s?(?=(,|}))/)) { return 'number'; } /* keywords */ if (stream.match(keywordRegex)) { return 'keyword'; } } /* pairs (associative arrays) -> key */ if (!state.pair && stream.match(/^\s*\S+(?=\s*:($|\s))/i)) { state.pair = true; state.keyCol = stream.indentation(); return "atom"; } if (state.pair && stream.match(/^:\s*/)) { state.pairStart = true; return 'meta'; } /* nothing found, continue */ state.pairStart = false; state.escaped = (ch == '\\'); stream.next(); return null; }, startState: function() { return { pair: false, pairStart: false, keyCol: 0, inlinePairs: 0, inlineList: 0, literal: false, escaped: false }; } }; }); CodeMirror.defineMIME("text/x-yaml", "yaml"); ================================================ FILE: public/packages/codemirror-3.19/mode/z80/index.html ================================================ CodeMirror: Z80 assembly mode

            Z80 assembly mode

            MIME type defined: text/x-z80.

            ================================================ FILE: public/packages/codemirror-3.19/mode/z80/z80.js ================================================ 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"); ================================================ FILE: public/packages/codemirror-3.19/package.json ================================================ { "name": "codemirror", "version":"3.19.0", "main": "lib/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"}], "repository": {"type": "git", "url": "http://marijnhaverbeke.nl/git/codemirror"} } ================================================ FILE: public/packages/codemirror-3.19/test/comment_test.js ================================================ namespace = "comment_"; (function() { function test(name, mode, run, before, after) { return testCM(name, function(cm) { run(cm); eq(cm.getValue(), after); }, {value: before, mode: mode}); } var simpleProg = "function foo() {\n return bar;\n}"; test("block", "javascript", function(cm) { cm.blockComment(Pos(0, 3), Pos(3, 0), {blockCommentLead: " *"}); }, simpleProg + "\n", "/* function foo() {\n * return bar;\n * }\n */"); test("blockToggle", "javascript", function(cm) { cm.blockComment(Pos(0, 3), Pos(2, 0), {blockCommentLead: " *"}); cm.uncomment(Pos(0, 3), Pos(2, 0), {blockCommentLead: " *"}); }, simpleProg, simpleProg); test("line", "javascript", function(cm) { cm.lineComment(Pos(1, 1), Pos(1, 1)); }, simpleProg, "function foo() {\n// return bar;\n}"); test("lineToggle", "javascript", function(cm) { cm.lineComment(Pos(0, 0), Pos(2, 1)); cm.uncomment(Pos(0, 0), Pos(2, 1)); }, simpleProg, simpleProg); test("fallbackToBlock", "css", function(cm) { cm.lineComment(Pos(0, 0), Pos(2, 1)); }, "html {\n border: none;\n}", "/* html {\n border: none;\n} */"); test("fallbackToLine", "ruby", function(cm) { cm.blockComment(Pos(0, 0), Pos(1)); }, "def blah()\n return hah\n", "# def blah()\n# return hah\n"); test("commentRange", "javascript", function(cm) { cm.blockComment(Pos(1, 2), Pos(1, 13), {fullLines: false}); }, simpleProg, "function foo() {\n /*return bar;*/\n}"); test("indented", "javascript", function(cm) { cm.lineComment(Pos(1, 0), Pos(2), {indent: true}); }, simpleProg, "function foo() {\n // return bar;\n // }"); test("singleEmptyLine", "javascript", function(cm) { cm.setCursor(1); cm.execCommand("toggleComment"); }, "a;\n\nb;", "a;\n// \nb;"); })(); ================================================ FILE: public/packages/codemirror-3.19/test/doc_test.js ================================================ (function() { // A minilanguage for instantiating linked CodeMirror instances and Docs function instantiateSpec(spec, place, opts) { var names = {}, pos = 0, l = spec.length, editors = []; while (spec) { var m = spec.match(/^(\w+)(\*?)(?:='([^\']*)'|<(~?)(\w+)(?:\/(\d+)-(\d+))?)\s*/); var name = m[1], isDoc = m[2], cur; if (m[3]) { cur = isDoc ? CodeMirror.Doc(m[3]) : CodeMirror(place, clone(opts, {value: m[3]})); } else { var other = m[5]; if (!names.hasOwnProperty(other)) { names[other] = editors.length; editors.push(CodeMirror(place, opts)); } var doc = editors[names[other]].linkedDoc({ sharedHist: !m[4], from: m[6] ? Number(m[6]) : null, to: m[7] ? Number(m[7]) : null }); cur = isDoc ? doc : CodeMirror(place, clone(opts, {value: doc})); } names[name] = editors.length; editors.push(cur); spec = spec.slice(m[0].length); } return editors; } function clone(obj, props) { if (!obj) return; clone.prototype = obj; var inst = new clone(); if (props) for (var n in props) if (props.hasOwnProperty(n)) inst[n] = props[n]; return inst; } function eqAll(val) { var end = arguments.length, msg = null; if (typeof arguments[end-1] == "string") msg = arguments[--end]; if (i == end) throw new Error("No editors provided to eqAll"); for (var i = 1; i < end; ++i) eq(arguments[i].getValue(), val, msg) } function testDoc(name, spec, run, opts, expectFail) { if (!opts) opts = {}; return test("doc_" + name, function() { var place = document.getElementById("testground"); var editors = instantiateSpec(spec, place, opts); var successful = false; try { run.apply(null, editors); successful = true; } finally { if ((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; } ================================================ FILE: public/packages/codemirror-3.19/test/emacs_test.js ================================================ (function() { "use strict"; var Pos = CodeMirror.Pos; namespace = "emacs_"; var eventCache = {}; function fakeEvent(keyName) { var event = eventCache[key]; if (event) return event; var ctrl, shift, alt; var key = keyName.replace(/\w+-/g, function(type) { if (type == "Ctrl-") ctrl = true; else if (type == "Alt-") alt = true; else if (type == "Shift-") shift = true; return ""; }); var code; for (var c in CodeMirror.keyNames) if (CodeMirror.keyNames[c] == key) { code = c; break; } if (c == null) throw new Error("Unknown key: " + key); return eventCache[keyName] = { type: "keydown", keyCode: code, ctrlKey: ctrl, shiftKey: shift, altKey: alt, preventDefault: function(){}, stopPropagation: function(){} }; } function sim(name, start /*, actions... */) { var keys = Array.prototype.slice.call(arguments, 2); testCM(name, function(cm) { for (var i = 0; i < keys.length; ++i) { var cur = keys[i]; if (cur instanceof Pos) cm.setCursor(cur); else if (cur.call) cur(cm); else cm.triggerOnKeyDown(fakeEvent(cur)); } }, {keyMap: "emacs", value: start, mode: "javascript"}); } function at(line, ch) { return function(cm) { eqPos(cm.getCursor(), Pos(line, ch)); }; } function txt(str) { return function(cm) { eq(cm.getValue(), str); }; } sim("motionHSimple", "abc", "Ctrl-F", "Ctrl-F", "Ctrl-B", at(0, 1)); sim("motionHMulti", "abcde", "Ctrl-4", "Ctrl-F", at(0, 4), "Ctrl--", "Ctrl-2", "Ctrl-F", at(0, 2), "Ctrl-5", "Ctrl-B", at(0, 0)); sim("motionHWord", "abc. def ghi", "Alt-F", at(0, 3), "Alt-F", at(0, 8), "Ctrl-B", "Alt-B", at(0, 5), "Alt-B", at(0, 0)); sim("motionHWordMulti", "abc. def ghi ", "Ctrl-3", "Alt-F", at(0, 12), "Ctrl-2", "Alt-B", at(0, 5), "Ctrl--", "Alt-B", at(0, 8)); sim("motionVSimple", "a\nb\nc\n", "Ctrl-N", "Ctrl-N", "Ctrl-P", at(1, 0)); sim("motionVMulti", "a\nb\nc\nd\ne\n", "Ctrl-2", "Ctrl-N", at(2, 0), "Ctrl-F", "Ctrl--", "Ctrl-N", at(1, 1), "Ctrl--", "Ctrl-3", "Ctrl-P", at(4, 1)); sim("killYank", "abc\ndef\nghi", "Ctrl-F", "Ctrl-Space", "Ctrl-N", "Ctrl-N", "Ctrl-W", "Ctrl-E", "Ctrl-Y", txt("ahibc\ndef\ng")); sim("killRing", "abcdef", "Ctrl-Space", "Ctrl-F", "Ctrl-W", "Ctrl-Space", "Ctrl-F", "Ctrl-W", "Ctrl-Y", "Alt-Y", txt("acdef")); sim("copyYank", "abcd", "Ctrl-Space", "Ctrl-E", "Alt-W", "Ctrl-Y", txt("abcdabcd")); sim("killLineSimple", "foo\nbar", "Ctrl-F", "Ctrl-K", txt("f\nbar")); sim("killLineEmptyLine", "foo\n \nbar", "Ctrl-N", "Ctrl-K", txt("foo\nbar")); sim("killLineMulti", "foo\nbar\nbaz", "Ctrl-F", "Ctrl-F", "Ctrl-K", "Ctrl-K", "Ctrl-K", "Ctrl-A", "Ctrl-Y", txt("o\nbarfo\nbaz")); sim("moveByParagraph", "abc\ndef\n\n\nhij\nklm\n\n", "Ctrl-F", "Ctrl-Down", at(2, 0), "Ctrl-Down", at(6, 0), "Ctrl-N", "Ctrl-Up", at(3, 0), "Ctrl-Up", at(0, 0), Pos(1, 2), "Ctrl-Down", at(2, 0), Pos(4, 2), "Ctrl-Up", at(3, 0)); sim("moveByParagraphMulti", "abc\n\ndef\n\nhij\n\nklm", "Ctrl-U", "2", "Ctrl-Down", at(3, 0), "Shift-Alt-.", "Ctrl-3", "Ctrl-Up", at(1, 0)); sim("moveBySentence", "sentence one! sentence\ntwo\n\nparagraph two", "Alt-E", at(0, 13), "Alt-E", at(1, 3), "Ctrl-F", "Alt-A", at(0, 13)); sim("moveByExpr", "function foo(a, b) {}", "Ctrl-Alt-F", at(0, 8), "Ctrl-Alt-F", at(0, 12), "Ctrl-Alt-F", at(0, 18), "Ctrl-Alt-B", at(0, 12), "Ctrl-Alt-B", at(0, 9)); sim("moveByExprMulti", "foo bar baz bug", "Ctrl-2", "Ctrl-Alt-F", at(0, 7), "Ctrl--", "Ctrl-Alt-F", at(0, 4), "Ctrl--", "Ctrl-2", "Ctrl-Alt-B", at(0, 11)); sim("delExpr", "var x = [\n a,\n b\n c\n];", Pos(0, 8), "Ctrl-Alt-K", txt("var x = ;"), "Ctrl-/", Pos(4, 1), "Ctrl-Alt-Backspace", txt("var x = ;")); sim("delExprMulti", "foo bar baz", "Ctrl-2", "Ctrl-Alt-K", txt(" baz"), "Ctrl-/", "Ctrl-E", "Ctrl-2", "Ctrl-Alt-Backspace", txt("foo ")); sim("justOneSpace", "hi bye ", Pos(0, 4), "Alt-Space", txt("hi bye "), Pos(0, 4), "Alt-Space", txt("hi b ye "), "Ctrl-A", "Alt-Space", "Ctrl-E", "Alt-Space", txt(" hi b ye ")); sim("openLine", "foo bar", "Alt-F", "Ctrl-O", txt("foo\n bar")) sim("transposeChar", "abcd\n\ne", "Ctrl-F", "Ctrl-T", "Ctrl-T", txt("bcad\n\ne"), at(0, 3), "Ctrl-F", "Ctrl-T", "Ctrl-T", "Ctrl-T", txt("bcda\n\ne"), at(0, 4), "Ctrl-F", "Ctrl-T", txt("bcd\na\ne"), at(1, 1)); sim("manipWordCase", "foo BAR bAZ", "Alt-C", "Alt-L", "Alt-U", txt("Foo bar BAZ"), "Ctrl-A", "Alt-U", "Alt-L", "Alt-C", txt("FOO bar Baz")); sim("manipWordCaseMulti", "foo Bar bAz", "Ctrl-2", "Alt-U", txt("FOO BAR bAz"), "Ctrl-A", "Ctrl-3", "Alt-C", txt("Foo Bar Baz")); sim("upExpr", "foo {\n bar[];\n baz(blah);\n}", Pos(2, 7), "Ctrl-Alt-U", at(2, 5), "Ctrl-Alt-U", at(0, 4)); sim("transposeExpr", "do foo[bar] dah", Pos(0, 6), "Ctrl-Alt-T", txt("do [bar]foo dah")); testCM("save", function(cm) { var saved = false; CodeMirror.commands.save = function(cm) { saved = cm.getValue(); }; cm.triggerOnKeyDown(fakeEvent("Ctrl-X")); cm.triggerOnKeyDown(fakeEvent("Ctrl-S")); is(saved, "hi"); }, {value: "hi", keyMap: "emacs"}); })(); ================================================ FILE: public/packages/codemirror-3.19/test/index.html ================================================ CodeMirror: Test Suite

            Test Suite

            A limited set of programmatic sanity tests for CodeMirror.

            Ran 0 of 0 tests

            Please enable JavaScript...

            ================================================ FILE: public/packages/codemirror-3.19/test/lint/acorn.js ================================================ // 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); ================================================ FILE: public/packages/codemirror-3.19/test/lint/lint.js ================================================ /* 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 - access to non-whitelisted globals (use a '// declare global: foo, bar' comment to declare extra globals in a file) [1]: https://github.com/marijnh/acorn/ */ var topAllowedGlobals = Object.create(null); ("Error RegExp Number String Array Function Object Math Date undefined " + "parseInt parseFloat Infinity NaN isNaN " + "window document navigator prompt alert confirm console " + "FileReader Worker postMessage importScripts " + "setInterval clearInterval setTimeout clearTimeout " + "CodeMirror test") .split(" ").forEach(function(n) { topAllowedGlobals[n] = true; }); 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"), notAllowed; if (notAllowed = file.match(/[\x00-\x08\x0b\x0c\x0e-\x19\uFEFF\t]|[ \t]\n/)) { var msg; if (notAllowed[0] == "\t") msg = "Found tab character"; else if (notAllowed[0].indexOf("\n") > -1) msg = "Trailing whitespace"; else msg = "Undesirable character " + notAllowed[0].charCodeAt(0); var info = acorn.getLineInfo(file, notAllowed.index); fail(msg + " at line " + info.line + ", column " + info.column, {source: fileName}); } var globalsSeen = Object.create(null); 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) { if (node.name == "arguments") return; // Mark used identifiers for (var cur = scope; cur; cur = cur.prev) if (node.name in cur.vars) { cur.vars[node.name].used = true; return; } globalsSeen[node.name] = node.loc; }, FunctionExpression: function(node) { if (node.id) fail("Named function expression", node.loc); } }, scopePasser); if (!globalsSeen.exports) { var allowedGlobals = Object.create(topAllowedGlobals), m; if (m = file.match(/\/\/ declare global:\s+(.*)/)) m[1].split(/,\s*/g).forEach(function(n) { allowedGlobals[n] = true; }); for (var glob in globalsSeen) if (!(glob in allowedGlobals)) fail("Access to global variable " + glob + ". Add a '// declare global: " + glob + "' comment or add this variable in test/lint/lint.js.", globalsSeen[glob]); } 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 + ": " + msg); failed = true; } function checkDir(dir) { fs.readdirSync(dir).forEach(function(file) { var fname = dir + "/" + file; if (/\.js$/.test(file)) checkFile(fname); else if (file != "dep" && fs.lstatSync(fname).isDirectory()) checkDir(fname); }); } exports.checkDir = checkDir; exports.checkFile = checkFile; exports.success = function() { return !failed; }; ================================================ FILE: public/packages/codemirror-3.19/test/lint/walk.js ================================================ // 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); ================================================ FILE: public/packages/codemirror-3.19/test/mode_test.css ================================================ .mt-output .mt-token { border: 1px solid #ddd; white-space: pre; font-family: "Consolas", monospace; text-align: center; } .mt-output .mt-style { font-size: x-small; } ================================================ FILE: public/packages/codemirror-3.19/test/mode_test.js ================================================ /** * Helper to test CodeMirror highlighting modes. It pretty prints output of the * highlighter and can check against expected styles. * * Mode tests are registered by calling test.mode(testName, mode, * tokens), where mode is a mode object as returned by * CodeMirror.getMode, and tokens is an array of lines that make up * the test. * * These lines are strings, in which styled stretches of code are * enclosed in brackets `[]`, and prefixed by their style. For * example, `[keyword if]`. Brackets in the code itself must be * duplicated to prevent them from being interpreted as token * boundaries. For example `a[[i]]` for `a[i]`. If a token has * multiple styles, the styles must be separated by ampersands, for * example `[tag&error ]`. * * See the test.js files in the css, markdown, gfm, and stex mode * directories for examples. */ (function() { function findSingle(str, pos, ch) { for (;;) { var found = str.indexOf(ch, pos); if (found == -1) return null; if (str.charAt(found + 1) != ch) return found; pos = found + 2; } } var styleName = /[\w&-_]+/g; function parseTokens(strs) { var tokens = [], plain = ""; for (var i = 0; i < strs.length; ++i) { if (i) plain += "\n"; var str = strs[i], pos = 0; while (pos < str.length) { var style = null, text; if (str.charAt(pos) == "[" && str.charAt(pos+1) != "[") { styleName.lastIndex = pos + 1; var m = styleName.exec(str); style = m[0].replace(/&/g, " "); var textStart = pos + style.length + 2; var end = findSingle(str, textStart, "]"); if (end == null) throw new Error("Unterminated token at " + pos + " in '" + str + "'" + style); text = str.slice(textStart, end); pos = end + 1; } else { var end = findSingle(str, pos, "["); if (end == null) end = str.length; text = str.slice(pos, end); pos = end; } text = text.replace(/\[\[|\]\]/g, function(s) {return s.charAt(0);}); tokens.push(style, text); plain += text; } } return {tokens: tokens, plain: plain}; } test.indentation = function(name, mode, tokens, modeName) { var data = parseTokens(tokens); return test((modeName || mode.name) + "_indent_" + name, function() { return compare(data.plain, data.tokens, mode, true); }); }; test.mode = function(name, mode, tokens, modeName) { var data = parseTokens(tokens); return test((modeName || mode.name) + "_" + name, function() { return compare(data.plain, data.tokens, mode); }); }; function compare(text, expected, mode, compareIndentation) { 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, compareIndentation); var pass, passStyle = ""; pass = highlightOutputsEqual(expectedOutput, observedOutput); passStyle = pass ? 'mt-pass' : 'mt-fail'; var s = ''; if (pass) { s += '
            '; s += '
            ' + text.replace('&', '&').replace('<', '<') + '
            '; s += '
            '; s += prettyPrintOutputTable(observedOutput); s += '
            '; s += '
            '; return s; } else { s += '
            '; s += '
            ' + text.replace('&', '&').replace('<', '<') + '
            '; 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, compareIndentation) { 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 compare = mode.token(stream, state), substr = stream.current(); if(compareIndentation) compare = mode.indent(state) || null; else if (compare && compare.indexOf(" ") > -1) compare = compare.split(' ').sort().join(' '); stream.start = stream.pos; if (pos && st[pos-2] == compare && !newLine) { st[pos-1] += substr; } else if (substr) { st[pos++] = compare; 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').replace('&', '&').replace('<', '<') + '' + '
            ' + (output[i] || null) + '
            '; return s; } })(); ================================================ FILE: public/packages/codemirror-3.19/test/phantom_driver.js ================================================ var page = require('webpage').create(); page.open("http://localhost:3000/test/index.html", function (status) { if (status != "success") { console.log("page couldn't be loaded successfully"); phantom.exit(1); } waitFor(function () { return page.evaluate(function () { var output = document.getElementById('status'); if (!output) { return false; } return (/^(\d+ failures?|all passed)/i).test(output.innerText); }); }, function () { var failed = page.evaluate(function () { return window.failed; }); var output = page.evaluate(function () { return document.getElementById('output').innerText + "\n" + document.getElementById('status').innerText; }); console.log(output); phantom.exit(failed > 0 ? 1 : 0); }); }); function waitFor (test, cb) { if (test()) { cb(); } else { setTimeout(function () { waitFor(test, cb); }, 250); } } ================================================ FILE: public/packages/codemirror-3.19/test/run.js ================================================ #!/usr/bin/env node var lint = require("./lint/lint"); lint.checkDir("mode"); lint.checkDir("lib"); lint.checkDir("addon"); lint.checkDir("keymap"); 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); }); }); }); ================================================ FILE: public/packages/codemirror-3.19/test/test.js ================================================ var Pos = CodeMirror.Pos; CodeMirror.defaults.rtlMoveVisually = true; function forEach(arr, f) { for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); } 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); namespace = "core_"; test("core_fromTextArea", function() { var te = document.getElementById("code"); te.value = "CONTENT"; var cm = CodeMirror.fromTextArea(te); is(!te.offsetHeight); eq(cm.getValue(), "CONTENT"); cm.setValue("foo\nbar"); eq(cm.getValue(), "foo\nbar"); cm.save(); is(/^foo\r?\nbar$/.test(te.value)); cm.setValue("xxx"); cm.toTextArea(); is(te.offsetHeight); eq(te.value, "xxx"); }); testCM("getRange", function(cm) { eq(cm.getLine(0), "1234"); eq(cm.getLine(1), "5678"); eq(cm.getLine(2), null); eq(cm.getLine(-1), null); eq(cm.getRange(Pos(0, 0), Pos(0, 3)), "123"); eq(cm.getRange(Pos(0, -1), Pos(0, 200)), "1234"); eq(cm.getRange(Pos(0, 2), Pos(1, 2)), "34\n56"); eq(cm.getRange(Pos(1, 2), Pos(100, 0)), "78"); }, {value: "1234\n5678"}); testCM("replaceRange", function(cm) { eq(cm.getValue(), ""); cm.replaceRange("foo\n", Pos(0, 0)); eq(cm.getValue(), "foo\n"); cm.replaceRange("a\nb", Pos(0, 1)); eq(cm.getValue(), "fa\nboo\n"); eq(cm.lineCount(), 3); cm.replaceRange("xyzzy", Pos(0, 0), Pos(1, 1)); eq(cm.getValue(), "xyzzyoo\n"); cm.replaceRange("abc", Pos(0, 0), Pos(10, 0)); eq(cm.getValue(), "abc"); eq(cm.lineCount(), 1); }); testCM("selection", function(cm) { cm.setSelection(Pos(0, 4), Pos(2, 2)); is(cm.somethingSelected()); eq(cm.getSelection(), "11\n222222\n33"); 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}); testCM("indentByNumber", function(cm) { cm.indentLine(0, 2); eq(cm.getLine(0), " foo"); cm.indentLine(0, -200); eq(cm.getLine(0), "foo"); cm.setSelection(Pos(0, 0), Pos(1, 2)); cm.indentSelection(3); eq(cm.getValue(), " foo\n bar\nbaz"); }, {value: "foo\nbar\nbaz"}); test("core_defaults", function() { var defsCopy = {}, defs = CodeMirror.defaults; for (var opt in defs) defsCopy[opt] = defs[opt]; defs.indentUnit = 5; defs.value = "uu"; defs.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 i = 0; i < 2; ++i) { var sys = i ? "local" : "page"; for (var ch = 0; ch <= 35; ch += 5) { for (var line = 0; line < 70; line += 5) { cm.setCursor(line, ch); var coords = cm.charCoords(Pos(line, ch), sys); var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys); eqPos(pos, Pos(line, ch)); } } } }, {lineNumbers: true}); 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("deleteSpanCollapsedInclusiveLeft", function(cm) { var from = Pos(1, 0), to = Pos(1, 1); var m = cm.markText(from, to, {collapsed: true, inclusiveLeft: true}); // Delete collapsed span. cm.replaceRange("", from, to); }, {value: "abc\nX\ndef"}); testCM("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("bookmarkCursor", function(cm) { var pos01 = cm.cursorCoords(Pos(0, 1)), pos11 = cm.cursorCoords(Pos(1, 1)), pos20 = cm.cursorCoords(Pos(2, 0)), pos30 = cm.cursorCoords(Pos(3, 0)), pos41 = cm.cursorCoords(Pos(4, 1)); cm.setBookmark(Pos(0, 1), {widget: document.createTextNode("←"), insertLeft: true}); cm.setBookmark(Pos(2, 0), {widget: document.createTextNode("←"), insertLeft: true}); cm.setBookmark(Pos(1, 1), {widget: document.createTextNode("→")}); cm.setBookmark(Pos(3, 0), {widget: document.createTextNode("→")}); var new01 = cm.cursorCoords(Pos(0, 1)), new11 = cm.cursorCoords(Pos(1, 1)), new20 = cm.cursorCoords(Pos(2, 0)), new30 = cm.cursorCoords(Pos(3, 0)); is(new01.left == pos01.left && new01.top == pos01.top, "at left, middle of line"); is(new11.left > pos11.left && new11.top == pos11.top, "at right, middle of line"); is(new20.left == pos20.left && new20.top == pos20.top, "at left, empty line"); is(new30.left > pos30.left && new30.top == pos30.top, "at right, empty line"); cm.setBookmark(Pos(4, 0), {widget: document.createTextNode("→")}); is(cm.cursorCoords(Pos(4, 1)).left > pos41.left, "single-char bug"); }, {value: "foo\nbar\n\n\nx\ny"}); testCM("multiBookmarkCursor", function(cm) { if (phantom) return; var ms = [], m; function add(insertLeft) { for (var i = 0; i < 3; ++i) { var node = document.createElement("span"); node.innerHTML = "X"; ms.push(cm.setBookmark(Pos(0, 1), {widget: node, insertLeft: insertLeft})); } } var base1 = cm.cursorCoords(Pos(0, 1)).left, base4 = cm.cursorCoords(Pos(0, 4)).left; add(true); is(Math.abs(base1 - cm.cursorCoords(Pos(0, 1)).left) < .1); while (m = ms.pop()) m.clear(); add(false); is(Math.abs(base4 - cm.cursorCoords(Pos(0, 1)).left) < .1); }, {value: "abcdefg"}); testCM("getAllMarks", function(cm) { addDoc(cm, 10, 10); var m1 = cm.setBookmark(Pos(0, 2)); var m2 = cm.markText(Pos(0, 2), Pos(3, 2)); var m3 = cm.markText(Pos(1, 2), Pos(1, 8)); var m4 = cm.markText(Pos(8, 0), Pos(9, 0)); eq(cm.getAllMarks().length, 4); m1.clear(); m3.clear(); eq(cm.getAllMarks().length, 2); }); testCM("bug577", function(cm) { cm.setValue("a\nb"); cm.clearHistory(); cm.setValue("fooooo"); cm.undo(); }); testCM("scrollSnap", function(cm) { cm.setSize(100, 100); addDoc(cm, 200, 200); cm.setCursor(Pos(100, 180)); var info = cm.getScrollInfo(); is(info.left > 0 && info.top > 0); cm.setCursor(Pos(0, 0)); info = cm.getScrollInfo(); is(info.left == 0 && info.top == 0, "scrolled clean to top"); cm.setCursor(Pos(100, 180)); cm.setCursor(Pos(199, 0)); info = cm.getScrollInfo(); is(info.left == 0 && info.top + 2 > info.height - cm.getScrollerElement().clientHeight, "scrolled clean to bottom"); }); testCM("scrollIntoView", function(cm) { if (phantom) return; var outer = cm.getWrapperElement().getBoundingClientRect(); function test(line, ch) { var pos = Pos(line, ch); cm.scrollIntoView(pos); var box = cm.charCoords(pos, "window"); is(box.left >= outer.left && box.right <= outer.right && box.top >= outer.top && box.bottom <= outer.bottom); } addDoc(cm, 200, 200); test(199, 199); test(0, 0); test(100, 100); test(199, 0); test(0, 199); test(100, 100); }); testCM("selectionPos", function(cm) { if (phantom) return; cm.setSize(100, 100); addDoc(cm, 200, 100); cm.setSelection(Pos(1, 100), Pos(98, 100)); var lineWidth = cm.charCoords(Pos(0, 200), "local").left; var lineHeight = (cm.charCoords(Pos(99)).top - cm.charCoords(Pos(0)).top) / 100; cm.scrollTo(0, 0); var selElt = byClassName(cm.getWrapperElement(), "CodeMirror-selected"); var outer = cm.getWrapperElement().getBoundingClientRect(); var sawMiddle, sawTop, sawBottom; for (var i = 0, e = selElt.length; i < e; ++i) { var box = selElt[i].getBoundingClientRect(); var atLeft = box.left - outer.left < 30; var width = box.right - box.left; var atRight = box.right - outer.left > .8 * lineWidth; if (atLeft && atRight) { sawMiddle = true; is(box.bottom - box.top > 90 * lineHeight, "middle high"); is(width > .9 * lineWidth, "middle wide"); } else { is(width > .4 * lineWidth, "top/bot wide enough"); is(width < .6 * lineWidth, "top/bot slim enough"); if (atLeft) { sawBottom = true; is(box.top - outer.top > 96 * lineHeight, "bot below"); } else if (atRight) { sawTop = true; is(box.top - outer.top < 2.1 * lineHeight, "top above"); } } } is(sawTop && sawBottom && sawMiddle, "all parts"); }, null); testCM("restoreHistory", function(cm) { cm.setValue("abc\ndef"); cm.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) { if (phantom) return; addDoc(cm, 4, 8); var range = cm.markText(Pos(1, 2), Pos(6, 2), { replacedWith: document.createTextNode("Q") }); cm.setCursor(0, 3); CodeMirror.commands.goLineDown(cm); 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("M"), 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)); range = cm.markText(Pos(2, 0), Pos(4, 4), { replacedWith: document.createTextNode("M") }); cm.setCursor(1, 0); CodeMirror.commands.goLineDown(cm); eqPos(cm.getCursor(), Pos(2, 0)); }, null); testCM("nestedFold", function(cm) { addDoc(cm, 10, 3); function fold(ll, cl, lr, cr) { return cm.markText(Pos(ll, cl), Pos(lr, cr), {collapsed: true}); } var inner1 = fold(0, 6, 1, 3), inner2 = fold(0, 2, 1, 8), outer = fold(0, 1, 2, 3), inner0 = fold(0, 5, 0, 6); cm.setCursor(0, 1); CodeMirror.commands.goCharRight(cm); 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("wrappingInlineWidget", function(cm) { cm.setSize("11em"); var w = document.createElement("span"); w.style.color = "red"; w.innerHTML = "one two three four"; cm.markText(Pos(0, 6), Pos(0, 9), {replacedWith: w}); var cur0 = cm.cursorCoords(Pos(0, 0)), cur1 = cm.cursorCoords(Pos(0, 10)); is(cur0.top < cur1.top); is(cur0.bottom < cur1.bottom); var curL = cm.cursorCoords(Pos(0, 6)), curR = cm.cursorCoords(Pos(0, 9)); eq(curL.top, cur0.top); eq(curL.bottom, cur0.bottom); eq(curR.top, cur1.top); eq(curR.bottom, cur1.bottom); cm.replaceRange("", Pos(0, 9), Pos(0)); curR = cm.cursorCoords(Pos(0, 9)); eq(curR.top, cur1.top); eq(curR.bottom, cur1.bottom); }, {value: "1 2 3 xxx 4", lineWrapping: true}); testCM("changedInlineWidget", function(cm) { cm.setSize("10em"); var w = document.createElement("span"); w.innerHTML = "x"; var m = cm.markText(Pos(0, 4), Pos(0, 5), {replacedWith: w}); w.innerHTML = "and now the widget is really really long all of a sudden and a scrollbar is needed"; m.changed(); var hScroll = byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0]; is(hScroll.scrollWidth > hScroll.clientWidth); }, {value: "hello there"}); testCM("changedBookmark", function(cm) { cm.setSize("10em"); var w = document.createElement("span"); w.innerHTML = "x"; var m = cm.setBookmark(Pos(0, 4), {widget: w}); w.innerHTML = "and now the widget is really really long all of a sudden and a scrollbar is needed"; m.changed(); var hScroll = byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0]; is(hScroll.scrollWidth > hScroll.clientWidth); }, {value: "abcdefg"}); testCM("inlineWidget", function(cm) { var w = cm.setBookmark(Pos(0, 2), {widget: document.createTextNode("uu")}); cm.setCursor(0, 2); CodeMirror.commands.goLineDown(cm); 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"); if (!phantom) 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(0, 24)); cm.execCommand("goWordRight"); 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("groupMovementCommands", function(cm) { cm.execCommand("goGroupLeft"); eqPos(cm.getCursor(), Pos(0, 0)); cm.execCommand("goGroupRight"); eqPos(cm.getCursor(), Pos(0, 4)); cm.execCommand("goGroupRight"); eqPos(cm.getCursor(), Pos(0, 7)); cm.execCommand("goGroupRight"); eqPos(cm.getCursor(), Pos(0, 10)); cm.execCommand("goGroupLeft"); eqPos(cm.getCursor(), Pos(0, 7)); cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); eqPos(cm.getCursor(), Pos(0, 15)); cm.setCursor(Pos(0, 17)); cm.execCommand("goGroupLeft"); eqPos(cm.getCursor(), Pos(0, 16)); cm.execCommand("goGroupLeft"); eqPos(cm.getCursor(), Pos(0, 14)); cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); eqPos(cm.getCursor(), Pos(0, 20)); cm.execCommand("goGroupRight"); eqPos(cm.getCursor(), Pos(1, 5)); cm.execCommand("goGroupLeft"); cm.execCommand("goGroupLeft"); eqPos(cm.getCursor(), Pos(1, 0)); cm.execCommand("goGroupLeft"); eqPos(cm.getCursor(), Pos(0, 16)); }, {value: "booo ba---quux. ffff\n abc d"}); 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; } }); }); // 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) { if (phantom) return; addDoc(cm, 500, 2); cm.setCursor(Pos(0, 500)); var wrap = cm.getWrapperElement(), cur = byClassName(wrap, "CodeMirror-cursor")[0]; is(wrap.getBoundingClientRect().right > cur.getBoundingClientRect().left); }); testCM("lineWidgets", function(cm) { addDoc(cm, 500, 3); var last = cm.charCoords(Pos(2, 0)); var node = document.createElement("div"); node.innerHTML = "hi"; var widget = cm.addLineWidget(1, node); is(last.top < cm.charCoords(Pos(2, 0)).top, "took up space"); cm.setCursor(Pos(1, 1)); cm.execCommand("goLineDown"); 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(0, 0)); 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, true); 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("beforeChangeUndo", function(cm) { cm.setLine(0, "hi"); cm.setLine(0, "bye"); eq(cm.historySize().undo, 2); cm.on("beforeChange", function(cm, change) { is(!change.update); change.cancel(); }); cm.undo(); eq(cm.historySize().undo, 0); eq(cm.getValue(), "bye\ntwo"); }, {value: "one\ntwo"}); testCM("beforeSelectionChange", function(cm) { function notAtEnd(cm, pos) { var len = cm.getLine(pos.line).length; if (!len || pos.ch == len) return Pos(pos.line, pos.ch - 1); return pos; } cm.on("beforeSelectionChange", function(cm, 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)); }); testCM("change_removedText", function(cm) { cm.setValue("abc\ndef"); var removedText; cm.on("change", function(cm, change) { removedText = [change.removed, change.next && change.next.removed]; }); cm.operation(function() { cm.replaceRange("xyz", Pos(0, 0), Pos(1,1)); cm.replaceRange("123", Pos(0,0)); }); eq(removedText[0].join("\n"), "abc\nd"); eq(removedText[1].join("\n"), ""); cm.undo(); eq(removedText[0].join("\n"), "123"); eq(removedText[1].join("\n"), "xyz"); cm.redo(); eq(removedText[0].join("\n"), "abc\nd"); eq(removedText[1].join("\n"), ""); }); testCM("lineStyleFromMode", function(cm) { CodeMirror.defineMode("test_mode", function() { return {token: function(stream) { if (stream.match(/^\[[^\]]*\]/)) return "line-brackets"; if (stream.match(/^\([^\]]*\)/)) return "line-background-parens"; stream.match(/^\s+|^\S+/); }}; }); cm.setOption("mode", "test_mode"); var bracketElts = byClassName(cm.getWrapperElement(), "brackets"); eq(bracketElts.length, 1); eq(bracketElts[0].nodeName, "PRE"); is(!/brackets.*brackets/.test(bracketElts[0].className)); var parenElts = byClassName(cm.getWrapperElement(), "parens"); eq(parenElts.length, 1); eq(parenElts[0].nodeName, "DIV"); is(!/parens.*parens/.test(parenElts[0].className)); }, {value: "line1: [br] [br]\nline2: (par) (par)\nline3: nothing"}); ================================================ FILE: public/packages/codemirror-3.19/test/vim_test.js ================================================ var code = '' + ' wOrd1 (#%\n' + ' word3] \n' + 'aopop pop 0 1 2 3 4\n' + ' (a) [b] {c} \n' + 'int getchar(void) {\n' + ' static char buf[BUFSIZ];\n' + ' static char *bufp = buf;\n' + ' if (n == 0) { /* buffer is empty */\n' + ' n = read(0, buf, sizeof buf);\n' + ' bufp = buf;\n' + ' }\n' + '\n' + ' return (--n >= 0) ? (unsigned char) *bufp++ : EOF;\n' + ' \n' + '}\n'; var lines = (function() { lineText = code.split('\n'); var ret = []; for (var i = 0; i < lineText.length; i++) { ret[i] = { line: i, length: lineText[i].length, lineText: lineText[i], textStart: /^\s*/.exec(lineText[i])[0].length }; } return ret; })(); var endOfDocument = makeCursor(lines.length - 1, lines[lines.length - 1].length); var wordLine = lines[0]; var bigWordLine = lines[1]; var charLine = lines[2]; var bracesLine = lines[3]; var seekBraceLine = lines[4]; var word1 = { start: { 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 } }; var seekOutside = { start: { line: seekBraceLine.line, ch: 1 }, end: { line: seekBraceLine.line, ch: 16 } }; var seekInside = { start: { line: seekBraceLine.line, ch: 14 }, end: { line: seekBraceLine.line, ch: 11 } }; function copyCursor(cur) { return { ch: cur.ch, line: cur.line }; } function testVim(name, run, opts, expectedFail) { var vimOpts = { lineNumbers: true, vimMode: true, showCursorWhenSelecting: true, value: code }; for (var prop in opts) { if (opts.hasOwnProperty(prop)) { vimOpts[prop] = opts[prop]; } } return test('vim_' + name, function() { var place = document.getElementById("testground"); var cm = CodeMirror(place, vimOpts); var vim = CodeMirror.Vim.maybeInitVimState_(cm); function doKeysFn(cm) { return function(args) { if (args instanceof Array) { arguments = args; } for (var i = 0; i < arguments.length; i++) { CodeMirror.Vim.handleKey(cm, arguments[i]); } } } function doInsertModeKeysFn(cm) { return function(args) { if (args instanceof Array) { arguments = args; } function executeHandler(handler) { if (typeof handler == 'string') { CodeMirror.commands[handler](cm); } else { handler(cm); } return true; } for (var i = 0; i < arguments.length; i++) { var key = arguments[i]; // Find key in keymap and handle. var handled = CodeMirror.lookupKey(key, ['vim-insert'], executeHandler); // Record for insert mode. if (handled === true && cm.state.vim.insertMode && arguments[i] != 'Esc') { var lastChange = CodeMirror.Vim.getVimGlobalState_().macroModeState.lastInsertModeChanges; if (lastChange) { lastChange.changes.push(new CodeMirror.Vim.InsertModeKey(key)); } } } } } function doExFn(cm) { return function(command) { cm.openDialog = helpers.fakeOpenDialog(command); helpers.doKeys(':'); } } function assertCursorAtFn(cm) { return function(line, ch) { var pos; if (ch == null && typeof line.line == 'number') { pos = line; } else { pos = makeCursor(line, ch); } eqPos(pos, cm.getCursor()); } } function fakeOpenDialog(result) { return function(text, callback) { return callback(result); } } var helpers = { doKeys: doKeysFn(cm), // Warning: Only emulates keymap events, not character insertions. Use // replaceRange to simulate character insertions. // Keys are in CodeMirror format, NOT vim format. doInsertModeKeys: doInsertModeKeysFn(cm), doEx: doExFn(cm), assertCursorAt: assertCursorAtFn(cm), fakeOpenDialog: fakeOpenDialog, getRegisterController: function() { return CodeMirror.Vim.getRegisterController(); } } CodeMirror.Vim.resetVimGlobalState_(); 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); }; testVim('qq@q', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('q', 'q', 'l', 'l', 'q'); helpers.assertCursorAt(0,2); helpers.doKeys('@', 'q'); helpers.assertCursorAt(0,4); }, { value: ' '}); testVim('@@', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('q', 'q', 'l', 'l', 'q'); helpers.assertCursorAt(0,2); helpers.doKeys('@', 'q'); helpers.assertCursorAt(0,4); helpers.doKeys('@', '@'); helpers.assertCursorAt(0,6); }, { value: ' '}); var jumplistScene = ''+ 'word\n'+ '(word)\n'+ '{word\n'+ 'word.\n'+ '\n'+ 'word search\n'+ '}word\n'+ 'word\n'+ 'word\n'; function testJumplist(name, keys, endPos, startPos, dialog) { endPos = makeCursor(endPos[0], endPos[1]); startPos = makeCursor(startPos[0], startPos[1]); testVim(name, function(cm, vim, helpers) { CodeMirror.Vim.resetVimGlobalState_(); if(dialog)cm.openDialog = helpers.fakeOpenDialog('word'); cm.setCursor(startPos); helpers.doKeys.apply(null, keys); helpers.assertCursorAt(endPos); }, {value: jumplistScene}); }; testJumplist('jumplist_H', ['H', ''], [5,2], [5,2]); testJumplist('jumplist_M', ['M', ''], [2,2], [2,2]); testJumplist('jumplist_L', ['L', ''], [2,2], [2,2]); testJumplist('jumplist_[[', ['[', '[', ''], [5,2], [5,2]); testJumplist('jumplist_]]', [']', ']', ''], [2,2], [2,2]); testJumplist('jumplist_G', ['G', ''], [5,2], [5,2]); testJumplist('jumplist_gg', ['g', 'g', ''], [5,2], [5,2]); testJumplist('jumplist_%', ['%', ''], [1,5], [1,5]); testJumplist('jumplist_{', ['{', ''], [1,5], [1,5]); testJumplist('jumplist_}', ['}', ''], [1,5], [1,5]); testJumplist('jumplist_\'', ['m', 'a', 'h', '\'', 'a', 'h', ''], [1,5], [1,5]); testJumplist('jumplist_`', ['m', 'a', 'h', '`', 'a', 'h', ''], [1,5], [1,5]); testJumplist('jumplist_*_cachedCursor', ['*', ''], [1,3], [1,3]); testJumplist('jumplist_#_cachedCursor', ['#', ''], [1,3], [1,3]); testJumplist('jumplist_n', ['#', 'n', ''], [1,1], [2,3]); testJumplist('jumplist_N', ['#', 'N', ''], [1,1], [2,3]); testJumplist('jumplist_repeat_', ['*', '*', '*', '3', ''], [2,3], [2,3]); testJumplist('jumplist_repeat_', ['*', '*', '*', '3', '', '2', ''], [5,0], [2,3]); testJumplist('jumplist_repeated_motion', ['3', '*', ''], [2,3], [2,3]); testJumplist('jumplist_/', ['/', ''], [2,3], [2,3], 'dialog'); testJumplist('jumplist_?', ['?', ''], [2,3], [2,3], 'dialog'); testJumplist('jumplist_skip_delted_mark', ['*', 'n', 'n', 'k', 'd', 'k', '', '', ''], [0,2], [0,2]); testJumplist('jumplist_skip_delted_mark', ['*', 'n', 'n', 'k', 'd', 'k', '', '', ''], [1,0], [0,2]); /** * @param name Name of the test * @param keys An array of keys or a string with a single key to simulate. * @param endPos The expected end position of the cursor. * @param startPos The position the cursor should start at, defaults to 0, 0. */ function testMotion(name, keys, endPos, startPos) { testVim(name, function(cm, vim, helpers) { if (!startPos) { startPos = { 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('j_repeat_clip', ['1000', 'j'], endOfDocument); testMotion('k', 'k', offsetCursor(word3.end, -1, 0), word3.end); testMotion('k_repeat', ['2', 'k'], makeCursor(0, 4), makeCursor(2, 4)); testMotion('k_repeat_clip', ['1000', 'k'], makeCursor(0, 4), makeCursor(2, 4)); testMotion('w', 'w', word1.start); testMotion('w_multiple_newlines_no_space', 'w', makeCursor(12, 2), makeCursor(11, 2)); testMotion('w_multiple_newlines_with_space', 'w', makeCursor(14, 0), makeCursor(12, 51)); testMotion('w_repeat', ['2', 'w'], word2.start); testMotion('w_wrap', ['w'], word3.start, word2.start); testMotion('w_endOfDocument', 'w', endOfDocument, endOfDocument); testMotion('w_start_to_end', ['1000', 'w'], endOfDocument, makeCursor(0, 0)); testMotion('W', 'W', bigWord1.start); testMotion('W_repeat', ['2', 'W'], bigWord3.start, bigWord1.start); testMotion('e', 'e', word1.end); testMotion('e_repeat', ['2', 'e'], word2.end); testMotion('e_wrap', 'e', word3.end, word2.end); testMotion('e_endOfDocument', 'e', endOfDocument, endOfDocument); testMotion('e_start_to_end', ['1000', 'e'], endOfDocument, makeCursor(0, 0)); testMotion('b', 'b', word3.start, word3.end); testMotion('b_repeat', ['2', 'b'], word2.start, word3.end); testMotion('b_wrap', 'b', word2.start, word3.start); testMotion('b_startOfDocument', 'b', makeCursor(0, 0), makeCursor(0, 0)); testMotion('b_end_to_start', ['1000', 'b'], makeCursor(0, 0), endOfDocument); testMotion('ge', ['g', 'e'], word2.end, word3.end); testMotion('ge_repeat', ['2', 'g', 'e'], word1.end, word3.start); testMotion('ge_wrap', ['g', 'e'], word2.end, word3.start); testMotion('ge_startOfDocument', ['g', 'e'], makeCursor(0, 0), makeCursor(0, 0)); testMotion('ge_end_to_start', ['1000', 'g', 'e'], makeCursor(0, 0), endOfDocument); testMotion('gg', ['g', 'g'], makeCursor(lines[0].line, lines[0].textStart), makeCursor(3, 1)); testMotion('gg_repeat', ['3', 'g', 'g'], makeCursor(lines[2].line, lines[2].textStart)); testMotion('G', 'G', makeCursor(lines[lines.length - 1].line, lines[lines.length - 1].textStart), makeCursor(3, 1)); testMotion('G_repeat', ['3', 'G'], makeCursor(lines[2].line, lines[2].textStart)); // TODO: Make the test code long enough to test Ctrl-F and Ctrl-B. testMotion('0', '0', makeCursor(0, 0), makeCursor(0, 8)); testMotion('^', '^', makeCursor(0, lines[0].textStart), makeCursor(0, 8)); testMotion('+', '+', makeCursor(1, lines[1].textStart), makeCursor(0, 8)); testMotion('-', '-', makeCursor(0, lines[0].textStart), makeCursor(1, 4)); testMotion('_', ['6','_'], makeCursor(5, lines[5].textStart), makeCursor(0, 8)); testMotion('$', '$', makeCursor(0, lines[0].length - 1), makeCursor(0, 1)); testMotion('$_repeat', ['2', '$'], makeCursor(1, lines[1].length - 1), makeCursor(0, 3)); testMotion('f', ['f', 'p'], pChars[0], makeCursor(charLine.line, 0)); testMotion('f_repeat', ['2', 'f', 'p'], pChars[2], pChars[0]); testMotion('f_num', ['f', '2'], numChars[2], makeCursor(charLine.line, 0)); testMotion('t', ['t','p'], offsetCursor(pChars[0], 0, -1), makeCursor(charLine.line, 0)); testMotion('t_repeat', ['2', 't', 'p'], offsetCursor(pChars[2], 0, -1), pChars[0]); testMotion('F', ['F', 'p'], pChars[0], pChars[1]); testMotion('F_repeat', ['2', 'F', 'p'], pChars[0], pChars[2]); testMotion('T', ['T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[1]); testMotion('T_repeat', ['2', 'T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[2]); testMotion('%_parens', ['%'], parens1.end, parens1.start); testMotion('%_squares', ['%'], squares1.end, squares1.start); testMotion('%_braces', ['%'], curlys1.end, curlys1.start); testMotion('%_seek_outside', ['%'], seekOutside.end, seekOutside.start); testMotion('%_seek_inside', ['%'], seekInside.end, seekInside.start); testVim('%_seek_skip', function(cm, vim, helpers) { cm.setCursor(0,0); helpers.doKeys(['%']); helpers.assertCursorAt(0,9); }, {value:'01234"("()'}); testVim('%_skip_string', function(cm, vim, helpers) { cm.setCursor(0,0); helpers.doKeys(['%']); helpers.assertCursorAt(0,4); cm.setCursor(0,2); helpers.doKeys(['%']); helpers.assertCursorAt(0,0); }, {value:'(")")'}); (')') testVim('%_skip_comment', function(cm, vim, helpers) { cm.setCursor(0,0); helpers.doKeys(['%']); helpers.assertCursorAt(0,6); cm.setCursor(0,3); helpers.doKeys(['%']); helpers.assertCursorAt(0,0); }, {value:'(/*)*/)'}); // Make sure that moving down after going to the end of a line always leaves you // at the end of a line, but preserves the offset in other cases testVim('Changing lines after Eol operation', function(cm, vim, helpers) { cm.setCursor(0,0); helpers.doKeys(['$']); helpers.doKeys(['j']); // After moving to Eol and then down, we should be at Eol of line 2 helpers.assertCursorAt({ 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('gj_gk', function(cm, vim, helpers) { if (phantom) return; cm.setSize(120); // Test top of document edge case. cm.setCursor(0, 4); helpers.doKeys('g', 'j'); helpers.doKeys('10', 'g', 'k'); helpers.assertCursorAt(0, 4); // Test moving down preserves column position. helpers.doKeys('g', 'j'); var pos1 = cm.getCursor(); var expectedPos2 = { line: 0, ch: (pos1.ch - 4) * 2 + 4}; helpers.doKeys('g', 'j'); helpers.assertCursorAt(expectedPos2); // Move to the last character cm.setCursor(0, 0); // Move left to reset HSPos helpers.doKeys('h'); // Test bottom of document edge case. helpers.doKeys('100', 'g', 'j'); var endingPos = cm.getCursor(); is(endingPos != 0, 'gj should not be on wrapped line 0'); var topLeftCharCoords = cm.charCoords(makeCursor(0, 0)); var endingCharCoords = cm.charCoords(endingPos); is(topLeftCharCoords.left == endingCharCoords.left, 'gj should end up on column 0'); },{ lineNumbers: false, lineWrapping:true, value: 'Thislineisintentiallylongtotestmovementofgjandgkoverwrappedlines.' }); 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) { cm.setCursor(0, 6); helpers.doKeys('d', 'l'); eq(' word1', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq(' ', register.text); is(!register.linewise); helpers.assertCursorAt(0, 5); }, { value: ' word1 ' }); testVim('dl_repeat', function(cm, vim, helpers) { var curStart = makeCursor(0, 0); cm.setCursor(curStart); helpers.doKeys('2', 'd', 'l'); eq('ord1 ', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq(' w', register.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. cm.setCursor(0, 1); helpers.doKeys('d', 'w'); eq(' ', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word1 ', register.text); is(!register.linewise); helpers.assertCursorAt(0, 0); }, { value: ' word1 ' }); testVim('dw_eol', function(cm, vim, helpers) { // Assert that dw does not delete the newline if last word to delete is at end // of line. cm.setCursor(0, 1); helpers.doKeys('d', 'w'); eq(' \nword2', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word1', register.text); is(!register.linewise); helpers.assertCursorAt(0, 0); }, { value: ' word1\nword2' }); testVim('dw_eol_with_multiple_newlines', function(cm, vim, helpers) { // Assert that dw does not delete the newline if last word to delete is at end // of line and it is followed by multiple newlines. cm.setCursor(0, 1); helpers.doKeys('d', 'w'); eq(' \n\nword2', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word1', register.text); is(!register.linewise); helpers.assertCursorAt(0, 0); }, { value: ' word1\n\nword2' }); testVim('dw_empty_line_followed_by_whitespace', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'w'); eq(' \nword', cm.getValue()); }, { value: '\n \nword' }); testVim('dw_empty_line_followed_by_word', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'w'); eq('word', cm.getValue()); }, { value: '\nword' }); testVim('dw_empty_line_followed_by_empty_line', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'w'); eq('\n', cm.getValue()); }, { value: '\n\n' }); testVim('dw_whitespace_followed_by_whitespace', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'w'); eq('\n \n', cm.getValue()); }, { value: ' \n \n' }); testVim('dw_whitespace_followed_by_empty_line', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'w'); eq('\n\n', cm.getValue()); }, { value: ' \n\n' }); testVim('dw_word_whitespace_word', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'w'); eq('\n \nword2', cm.getValue()); }, { value: 'word1\n \nword2'}) testVim('dw_end_of_document', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('d', 'w'); eq('\nab', cm.getValue()); }, { value: '\nabc' }); testVim('dw_repeat', function(cm, vim, helpers) { // Assert that dw does delete newline if it should go to the next line, and // that repeat works properly. cm.setCursor(0, 1); helpers.doKeys('d', '2', 'w'); eq(' ', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word1\nword2', register.text); is(!register.linewise); helpers.assertCursorAt(0, 0); }, { value: ' word1\nword2' }); testVim('de_word_start_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'e'); eq('\n\n', cm.getValue()); }, { value: 'word\n\n' }); testVim('de_word_end_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(0, 3); helpers.doKeys('d', 'e'); eq('wor', cm.getValue()); }, { value: 'word\n\n\n' }); testVim('de_whitespace_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'e'); eq('', cm.getValue()); }, { value: ' \n\n\n' }); testVim('de_end_of_document', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('d', 'e'); eq('\nab', cm.getValue()); }, { value: '\nabc' }); testVim('db_empty_lines', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('d', 'b'); eq('\n\n', cm.getValue()); }, { value: '\n\n\n' }); testVim('db_word_start_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('d', 'b'); eq('\nword', cm.getValue()); }, { value: '\n\nword' }); testVim('db_word_end_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(2, 3); helpers.doKeys('d', 'b'); eq('\n\nd', cm.getValue()); }, { value: '\n\nword' }); testVim('db_whitespace_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('d', 'b'); eq('', cm.getValue()); }, { value: '\n \n' }); testVim('db_start_of_document', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'b'); eq('abc\n', cm.getValue()); }, { value: 'abc\n' }); testVim('dge_empty_lines', function(cm, vim, helpers) { cm.setCursor(1, 0); helpers.doKeys('d', 'g', 'e'); // Note: In real VIM the result should be '', but it's not quite consistent, // since 2 newlines are deleted. But in the similar case of word\n\n, only // 1 newline is deleted. We'll diverge from VIM's behavior since it's much // easier this way. eq('\n', cm.getValue()); }, { value: '\n\n' }); testVim('dge_word_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(1, 0); helpers.doKeys('d', 'g', 'e'); eq('wor\n', cm.getValue()); }, { value: 'word\n\n'}); testVim('dge_whitespace_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('d', 'g', 'e'); eq('', cm.getValue()); }, { value: '\n \n' }); testVim('dge_start_of_document', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'g', 'e'); eq('bc\n', cm.getValue()); }, { value: 'abc\n' }); testVim('d_inclusive', function(cm, vim, helpers) { // Assert that when inclusive is set, the character the cursor is on gets // deleted too. var curStart = makeCursor(0, 1); cm.setCursor(curStart); helpers.doKeys('d', 'e'); eq(' ', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word1', register.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); }); testVim('dd_lastline', function(cm, vim, helpers) { cm.setCursor(cm.lineCount(), 0); var expectedLineCount = cm.lineCount() - 1; helpers.doKeys('d', 'd'); eq(expectedLineCount, cm.lineCount()); helpers.assertCursorAt(cm.lineCount() - 1, 0); }); // 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', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('c', '2', 'w'); eq(' word3', cm.getValue()); helpers.assertCursorAt(0, 0); }, { value: 'word1 word2 word3'}); testVim('cw_repeat', function(cm, vim, helpers) { // Assert that cw does delete newline if it should go to the next line, and // that repeat works properly. var curStart = makeCursor(0, 1); cm.setCursor(curStart); helpers.doKeys('c', '2', 'w'); eq(' ', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word1\nword2', register.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); eq('vim-insert', cm.getOption('keyMap')); }); testVim('cc_append', function(cm, vim, helpers) { var expectedLineCount = cm.lineCount(); cm.setCursor(cm.lastLine(), 0); helpers.doKeys('c', 'c'); eq(expectedLineCount, cm.lineCount()); }); // 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 }); // Edit tests function testEdit(name, before, pos, edit, after) { return testVim(name, function(cm, vim, helpers) { cm.setCursor(0, before.search(pos)); helpers.doKeys.apply(this, edit.split('')); eq(after, cm.getValue()); }, {value: before}); } // These Delete tests effectively cover word-wise Change, Visual & Yank. // Tabs are used as differentiated whitespace to catch edge cases. // Normal word: testEdit('diw_mid_spc', 'foo \tbAr\t baz', /A/, 'diw', 'foo \t\t baz'); testEdit('daw_mid_spc', 'foo \tbAr\t baz', /A/, 'daw', 'foo \tbaz'); testEdit('diw_mid_punct', 'foo \tbAr.\t baz', /A/, 'diw', 'foo \t.\t baz'); testEdit('daw_mid_punct', 'foo \tbAr.\t baz', /A/, 'daw', 'foo.\t baz'); testEdit('diw_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'diw', 'foo \t,.\t baz'); testEdit('daw_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'daw', 'foo \t,.\t baz'); testEdit('diw_start_spc', 'bAr \tbaz', /A/, 'diw', ' \tbaz'); testEdit('daw_start_spc', 'bAr \tbaz', /A/, 'daw', 'baz'); testEdit('diw_start_punct', 'bAr. \tbaz', /A/, 'diw', '. \tbaz'); testEdit('daw_start_punct', 'bAr. \tbaz', /A/, 'daw', '. \tbaz'); testEdit('diw_end_spc', 'foo \tbAr', /A/, 'diw', 'foo \t'); testEdit('daw_end_spc', 'foo \tbAr', /A/, 'daw', 'foo'); testEdit('diw_end_punct', 'foo \tbAr.', /A/, 'diw', 'foo \t.'); testEdit('daw_end_punct', 'foo \tbAr.', /A/, 'daw', 'foo.'); // Big word: testEdit('diW_mid_spc', 'foo \tbAr\t baz', /A/, 'diW', 'foo \t\t baz'); testEdit('daW_mid_spc', 'foo \tbAr\t baz', /A/, 'daW', 'foo \tbaz'); testEdit('diW_mid_punct', 'foo \tbAr.\t baz', /A/, 'diW', 'foo \t\t baz'); testEdit('daW_mid_punct', 'foo \tbAr.\t baz', /A/, 'daW', 'foo \tbaz'); testEdit('diW_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'diW', 'foo \t\t baz'); testEdit('daW_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'daW', 'foo \tbaz'); testEdit('diW_start_spc', 'bAr\t baz', /A/, 'diW', '\t baz'); testEdit('daW_start_spc', 'bAr\t baz', /A/, 'daW', 'baz'); testEdit('diW_start_punct', 'bAr.\t baz', /A/, 'diW', '\t baz'); testEdit('daW_start_punct', 'bAr.\t baz', /A/, 'daW', 'baz'); testEdit('diW_end_spc', 'foo \tbAr', /A/, 'diW', 'foo \t'); testEdit('daW_end_spc', 'foo \tbAr', /A/, 'daW', 'foo'); testEdit('diW_end_punct', 'foo \tbAr.', /A/, 'diW', 'foo \t'); testEdit('daW_end_punct', 'foo \tbAr.', /A/, 'daW', 'foo'); // Operator-motion tests testVim('D', function(cm, vim, helpers) { cm.setCursor(0, 3); helpers.doKeys('D'); eq(' wo\nword2\n word3', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('rd1', register.text); is(!register.linewise); helpers.assertCursorAt(0, 2); }, { value: ' word1\nword2\n word3' }); testVim('C', function(cm, vim, helpers) { var curStart = makeCursor(0, 3); cm.setCursor(curStart); helpers.doKeys('C'); eq(' wo\nword2\n word3', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('rd1', register.text); is(!register.linewise); eqPos(curStart, cm.getCursor()); eq('vim-insert', cm.getOption('keyMap')); }, { value: ' word1\nword2\n word3' }); testVim('Y', function(cm, vim, helpers) { var curStart = makeCursor(0, 3); cm.setCursor(curStart); helpers.doKeys('Y'); eq(' word1\nword2\n word3', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('rd1', register.text); is(!register.linewise); helpers.assertCursorAt(0, 3); }, { value: ' word1\nword2\n word3' }); testVim('~', function(cm, vim, helpers) { helpers.doKeys('3', '~'); eq('ABCdefg', cm.getValue()); helpers.assertCursorAt(0, 3); }, { value: 'abcdefg' }); // Action tests testVim('ctrl-a', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys(''); eq('-9', cm.getValue()); helpers.assertCursorAt(0, 1); helpers.doKeys('2',''); eq('-7', cm.getValue()); }, {value: '-10'}); testVim('ctrl-x', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys(''); eq('-1', cm.getValue()); helpers.assertCursorAt(0, 1); helpers.doKeys('2',''); eq('-3', cm.getValue()); }, {value: '0'}); testVim('/ search forward', function(cm, vim, helpers) { ['', ''].forEach(function(key) { cm.setCursor(0, 0); helpers.doKeys(key); helpers.assertCursorAt(0, 5); helpers.doKeys('l'); helpers.doKeys(key); helpers.assertCursorAt(0, 10); cm.setCursor(0, 11); helpers.doKeys(key); helpers.assertCursorAt(0, 11); }); }, {value: '__jmp1 jmp2 jmp'}); testVim('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('i_repeat', function(cm, vim, helpers) { helpers.doKeys('3', 'i'); cm.replaceRange('test', cm.getCursor()); helpers.doInsertModeKeys('Esc'); eq('testtesttest', cm.getValue()); helpers.assertCursorAt(0, 11); }, { value: '' }); testVim('i_repeat_delete', function(cm, vim, helpers) { cm.setCursor(0, 4); helpers.doKeys('2', 'i'); cm.replaceRange('z', cm.getCursor()); helpers.doInsertModeKeys('Backspace', 'Backspace', 'Esc'); eq('abe', cm.getValue()); helpers.assertCursorAt(0, 1); }, { value: 'abcde' }); testVim('A', function(cm, vim, helpers) { 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('I_repeat', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('3', 'I'); cm.replaceRange('test', cm.getCursor()); helpers.doInsertModeKeys('Esc'); eq('testtesttestblah', cm.getValue()); helpers.assertCursorAt(0, 11); }, { value: 'blah' }); testVim('o', function(cm, vim, helpers) { cm.setCursor(0, 4); helpers.doKeys('o'); eq('word1\n\nword2', cm.getValue()); helpers.assertCursorAt(1, 0); eq('vim-insert', cm.getOption('keyMap')); }, { value: 'word1\nword2' }); testVim('o_repeat', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('3', 'o'); cm.replaceRange('test', cm.getCursor()); helpers.doInsertModeKeys('Esc'); eq('\ntest\ntest\ntest', cm.getValue()); helpers.assertCursorAt(3, 3); }, { value: '' }); testVim('O', function(cm, vim, helpers) { cm.setCursor(0, 4); helpers.doKeys('O'); eq('\nword1\nword2', cm.getValue()); helpers.assertCursorAt(0, 0); eq('vim-insert', cm.getOption('keyMap')); }, { value: 'word1\nword2' }); testVim('J', function(cm, vim, helpers) { cm.setCursor(0, 4); helpers.doKeys('J'); var expectedValue = 'word1 word2\nword3\n word4'; eq(expectedValue, cm.getValue()); helpers.assertCursorAt(0, expectedValue.indexOf('word2') - 1); }, { value: 'word1 \n word2\nword3\n word4' }); testVim('J_repeat', function(cm, vim, helpers) { cm.setCursor(0, 4); helpers.doKeys('3', 'J'); var expectedValue = 'word1 word2 word3\n word4'; eq(expectedValue, cm.getValue()); helpers.assertCursorAt(0, expectedValue.indexOf('word3') - 1); }, { value: 'word1 \n word2\nword3\n word4' }); testVim('p', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.getRegisterController().pushText('"', 'yank', 'abc\ndef', false); helpers.doKeys('p'); eq('__abc\ndef_', cm.getValue()); helpers.assertCursorAt(1, 2); }, { value: '___' }); testVim('p_register', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.getRegisterController().getRegister('a').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_lastline', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.getRegisterController().pushText('"', 'yank', ' a\nd', true); helpers.doKeys('2', 'p'); eq('___\n a\nd\n a\nd', cm.getValue()); helpers.assertCursorAt(1, 2); }, { value: '___' }); testVim('P', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.getRegisterController().pushText('"', 'yank', 'abc\ndef', false); helpers.doKeys('P'); eq('_abc\ndef__', cm.getValue()); helpers.assertCursorAt(1, 3); }, { value: '___' }); testVim('P_line', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.getRegisterController().pushText('"', 'yank', ' a\nd\n', true); helpers.doKeys('2', 'P'); eq(' a\nd\n a\nd\n___', cm.getValue()); helpers.assertCursorAt(0, 2); }, { value: '___' }); testVim('r', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('3', 'r', 'u'); eq('wuuuet\nanother', cm.getValue(),'3r failed'); helpers.assertCursorAt(0, 3); cm.setCursor(0, 4); helpers.doKeys('v', 'j', 'h', 'r', ''); eq('wuuu \n her', cm.getValue(),'Replacing selection by space-characters failed'); }, { value: 'wordet\nanother' }); testVim('R', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('R'); helpers.assertCursorAt(0, 1); eq('vim-replace', cm.getOption('keyMap')); is(cm.state.overwrite, 'Setting overwrite state failed'); }); testVim('mark', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 't'); cm.setCursor(0, 0); helpers.doKeys('\'', 't'); helpers.assertCursorAt(2, 2); cm.setCursor(0, 0); helpers.doKeys('`', 't'); helpers.assertCursorAt(2, 2); }); testVim('jumpToMark_next', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 't'); cm.setCursor(0, 0); helpers.doKeys(']', '`'); helpers.assertCursorAt(2, 2); cm.setCursor(0, 0); helpers.doKeys(']', '\''); helpers.assertCursorAt(2, 0); }); testVim('jumpToMark_next_repeat', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 'a'); cm.setCursor(3, 2); helpers.doKeys('m', 'b'); cm.setCursor(4, 2); helpers.doKeys('m', 'c'); cm.setCursor(0, 0); helpers.doKeys('2', ']', '`'); helpers.assertCursorAt(3, 2); cm.setCursor(0, 0); helpers.doKeys('2', ']', '\''); helpers.assertCursorAt(3, 1); }); testVim('jumpToMark_next_sameline', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('m', 'a'); cm.setCursor(2, 4); helpers.doKeys('m', 'b'); cm.setCursor(2, 2); helpers.doKeys(']', '`'); helpers.assertCursorAt(2, 4); }); testVim('jumpToMark_next_onlyprev', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('m', 'a'); cm.setCursor(4, 0); helpers.doKeys(']', '`'); helpers.assertCursorAt(4, 0); }); testVim('jumpToMark_next_nomark', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys(']', '`'); helpers.assertCursorAt(2, 2); helpers.doKeys(']', '\''); helpers.assertCursorAt(2, 0); }); testVim('jumpToMark_next_linewise_over', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 'a'); cm.setCursor(3, 4); helpers.doKeys('m', 'b'); cm.setCursor(2, 1); helpers.doKeys(']', '\''); helpers.assertCursorAt(3, 1); }); testVim('jumpToMark_next_action', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 't'); cm.setCursor(0, 0); helpers.doKeys('d', ']', '`'); helpers.assertCursorAt(0, 0); var actual = cm.getLine(0); var expected = 'pop pop 0 1 2 3 4'; eq(actual, expected, "Deleting while jumping to the next mark failed."); }); testVim('jumpToMark_next_line_action', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 't'); cm.setCursor(0, 0); helpers.doKeys('d', ']', '\''); helpers.assertCursorAt(0, 1); var actual = cm.getLine(0); var expected = ' (a) [b] {c} ' eq(actual, expected, "Deleting while jumping to the next mark line failed."); }); testVim('jumpToMark_prev', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 't'); cm.setCursor(4, 0); helpers.doKeys('[', '`'); helpers.assertCursorAt(2, 2); cm.setCursor(4, 0); helpers.doKeys('[', '\''); helpers.assertCursorAt(2, 0); }); testVim('jumpToMark_prev_repeat', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 'a'); cm.setCursor(3, 2); helpers.doKeys('m', 'b'); cm.setCursor(4, 2); helpers.doKeys('m', 'c'); cm.setCursor(5, 0); helpers.doKeys('2', '[', '`'); helpers.assertCursorAt(3, 2); cm.setCursor(5, 0); helpers.doKeys('2', '[', '\''); helpers.assertCursorAt(3, 1); }); testVim('jumpToMark_prev_sameline', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('m', 'a'); cm.setCursor(2, 4); helpers.doKeys('m', 'b'); cm.setCursor(2, 2); helpers.doKeys('[', '`'); helpers.assertCursorAt(2, 0); }); testVim('jumpToMark_prev_onlynext', function(cm, vim, helpers) { cm.setCursor(4, 4); helpers.doKeys('m', 'a'); cm.setCursor(2, 0); helpers.doKeys('[', '`'); helpers.assertCursorAt(2, 0); }); testVim('jumpToMark_prev_nomark', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('[', '`'); helpers.assertCursorAt(2, 2); helpers.doKeys('[', '\''); helpers.assertCursorAt(2, 0); }); testVim('jumpToMark_prev_linewise_over', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 'a'); cm.setCursor(3, 4); helpers.doKeys('m', 'b'); cm.setCursor(3, 6); helpers.doKeys('[', '\''); helpers.assertCursorAt(2, 0); }); testVim('delmark_single', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('m', 't'); helpers.doEx('delmarks t'); cm.setCursor(0, 0); helpers.doKeys('`', 't'); helpers.assertCursorAt(0, 0); }); testVim('delmark_range', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('m', 'a'); cm.setCursor(2, 2); helpers.doKeys('m', 'b'); cm.setCursor(3, 2); helpers.doKeys('m', 'c'); cm.setCursor(4, 2); helpers.doKeys('m', 'd'); cm.setCursor(5, 2); helpers.doKeys('m', 'e'); helpers.doEx('delmarks b-d'); cm.setCursor(0, 0); helpers.doKeys('`', 'a'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'b'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'c'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'd'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'e'); helpers.assertCursorAt(5, 2); }); testVim('delmark_multi', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('m', 'a'); cm.setCursor(2, 2); helpers.doKeys('m', 'b'); cm.setCursor(3, 2); helpers.doKeys('m', 'c'); cm.setCursor(4, 2); helpers.doKeys('m', 'd'); cm.setCursor(5, 2); helpers.doKeys('m', 'e'); helpers.doEx('delmarks bcd'); cm.setCursor(0, 0); helpers.doKeys('`', 'a'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'b'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'c'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'd'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'e'); helpers.assertCursorAt(5, 2); }); testVim('delmark_multi_space', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('m', 'a'); cm.setCursor(2, 2); helpers.doKeys('m', 'b'); cm.setCursor(3, 2); helpers.doKeys('m', 'c'); cm.setCursor(4, 2); helpers.doKeys('m', 'd'); cm.setCursor(5, 2); helpers.doKeys('m', 'e'); helpers.doEx('delmarks b c d'); cm.setCursor(0, 0); helpers.doKeys('`', 'a'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'b'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'c'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'd'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'e'); helpers.assertCursorAt(5, 2); }); testVim('delmark_all', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('m', 'a'); cm.setCursor(2, 2); helpers.doKeys('m', 'b'); cm.setCursor(3, 2); helpers.doKeys('m', 'c'); cm.setCursor(4, 2); helpers.doKeys('m', 'd'); cm.setCursor(5, 2); helpers.doKeys('m', 'e'); helpers.doEx('delmarks a b-de'); cm.setCursor(0, 0); helpers.doKeys('`', 'a'); helpers.assertCursorAt(0, 0); helpers.doKeys('`', 'b'); helpers.assertCursorAt(0, 0); helpers.doKeys('`', 'c'); helpers.assertCursorAt(0, 0); helpers.doKeys('`', 'd'); helpers.assertCursorAt(0, 0); helpers.doKeys('`', 'e'); helpers.assertCursorAt(0, 0); }); testVim('visual', function(cm, vim, helpers) { helpers.doKeys('l', 'v', 'l', 'l'); helpers.assertCursorAt(0, 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('visual_blank', function(cm, vim, helpers) { helpers.doKeys('v', 'k'); eq(vim.visualMode, true); }, { value: '\n' }); testVim('s_normal', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('s'); helpers.doInsertModeKeys('Esc'); helpers.assertCursorAt(0, 0); eq('ac', cm.getValue()); }, { value: 'abc'}); testVim('s_visual', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('v', 's'); helpers.doInsertModeKeys('Esc'); helpers.assertCursorAt(0, 0); eq('ac', cm.getValue()); }, { value: 'abc'}); testVim('S_normal', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('j', 'S'); helpers.doInsertModeKeys('Esc'); helpers.assertCursorAt(1, 0); eq('aa\n\ncc', cm.getValue()); }, { value: 'aa\nbb\ncc'}); testVim('S_visual', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('v', 'j', 'S'); helpers.doInsertModeKeys('Esc'); helpers.assertCursorAt(0, 0); eq('\ncc', cm.getValue()); }, { value: 'aa\nbb\ncc'}); 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('/_nongreedy', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('aa'); helpers.doKeys('/'); helpers.assertCursorAt(0, 4); helpers.doKeys('n'); helpers.assertCursorAt(1, 3); helpers.doKeys('n'); helpers.assertCursorAt(0, 0); }, { value: 'aaa aa \n a aa'}); testVim('?_nongreedy', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('aa'); helpers.doKeys('?'); helpers.assertCursorAt(1, 3); helpers.doKeys('n'); helpers.assertCursorAt(0, 4); helpers.doKeys('n'); helpers.assertCursorAt(0, 0); }, { value: 'aaa aa \n a aa'}); testVim('/_greedy', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('a+'); helpers.doKeys('/'); helpers.assertCursorAt(0, 4); helpers.doKeys('n'); helpers.assertCursorAt(1, 1); helpers.doKeys('n'); helpers.assertCursorAt(1, 3); helpers.doKeys('n'); helpers.assertCursorAt(0, 0); }, { value: 'aaa aa \n a aa'}); testVim('?_greedy', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('a+'); helpers.doKeys('?'); helpers.assertCursorAt(1, 3); helpers.doKeys('n'); helpers.assertCursorAt(1, 1); helpers.doKeys('n'); helpers.assertCursorAt(0, 4); helpers.doKeys('n'); helpers.assertCursorAt(0, 0); }, { value: 'aaa aa \n a aa'}); testVim('/_greedy_0_or_more', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('a*'); helpers.doKeys('/'); helpers.assertCursorAt(0, 3); helpers.doKeys('n'); helpers.assertCursorAt(0, 4); helpers.doKeys('n'); helpers.assertCursorAt(0, 5); helpers.doKeys('n'); helpers.assertCursorAt(1, 0); helpers.doKeys('n'); helpers.assertCursorAt(1, 1); helpers.doKeys('n'); helpers.assertCursorAt(0, 0); }, { value: 'aaa aa\n aa'}); testVim('?_greedy_0_or_more', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('a*'); helpers.doKeys('?'); helpers.assertCursorAt(1, 1); helpers.doKeys('n'); helpers.assertCursorAt(1, 0); helpers.doKeys('n'); helpers.assertCursorAt(0, 5); helpers.doKeys('n'); helpers.assertCursorAt(0, 4); helpers.doKeys('n'); helpers.assertCursorAt(0, 3); helpers.doKeys('n'); helpers.assertCursorAt(0, 0); }, { value: 'aaa aa\n aa'}); testVim('? and n/N', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('match'); helpers.doKeys('?'); helpers.assertCursorAt(1, 6); helpers.doKeys('n'); helpers.assertCursorAt(0, 11); helpers.doKeys('N'); helpers.assertCursorAt(1, 6); cm.setCursor(0, 0); helpers.doKeys('2', '?'); helpers.assertCursorAt(0, 11); }, { value: 'match nope match \n nope Match' }); testVim('*', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('*'); helpers.assertCursorAt(0, 22); cm.setCursor(0, 9); helpers.doKeys('2', '*'); helpers.assertCursorAt(1, 8); }, { value: 'nomatch match nomatch match \nnomatch Match' }); testVim('*_no_word', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('*'); helpers.assertCursorAt(0, 0); }, { value: ' \n match \n' }); testVim('*_symbol', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('*'); helpers.assertCursorAt(1, 0); }, { value: ' /}\n/} match \n' }); testVim('#', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('#'); helpers.assertCursorAt(1, 8); cm.setCursor(0, 9); helpers.doKeys('2', '#'); helpers.assertCursorAt(0, 22); }, { value: 'nomatch match nomatch match \nnomatch Match' }); testVim('*_seek', function(cm, vim, helpers) { // Should skip over space and symbols. cm.setCursor(0, 3); helpers.doKeys('*'); helpers.assertCursorAt(0, 22); }, { value: ' := match nomatch match \nnomatch Match' }); testVim('#', function(cm, vim, helpers) { // Should skip over space and symbols. cm.setCursor(0, 3); helpers.doKeys('#'); helpers.assertCursorAt(1, 8); }, { value: ' := match nomatch match \nnomatch Match' }); testVim('.', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('2', 'd', 'w'); helpers.doKeys('.'); eq('5 6', cm.getValue()); }, { value: '1 2 3 4 5 6'}); testVim('._repeat', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('2', 'd', 'w'); helpers.doKeys('3', '.'); eq('6', cm.getValue()); }, { value: '1 2 3 4 5 6'}); testVim('._insert', function(cm, vim, helpers) { helpers.doKeys('i'); cm.replaceRange('test', cm.getCursor()); helpers.doInsertModeKeys('Esc'); helpers.doKeys('.'); eq('testestt', cm.getValue()); helpers.assertCursorAt(0, 6); }, { value: ''}); testVim('._insert_repeat', function(cm, vim, helpers) { helpers.doKeys('i'); cm.replaceRange('test', cm.getCursor()); cm.setCursor(0, 4); helpers.doInsertModeKeys('Esc'); helpers.doKeys('2', '.'); eq('testesttestt', cm.getValue()); helpers.assertCursorAt(0, 10); }, { value: ''}); testVim('._repeat_insert', function(cm, vim, helpers) { helpers.doKeys('3', 'i'); cm.replaceRange('te', cm.getCursor()); cm.setCursor(0, 2); helpers.doInsertModeKeys('Esc'); helpers.doKeys('.'); eq('tetettetetee', cm.getValue()); helpers.assertCursorAt(0, 10); }, { value: ''}); testVim('._insert_o', function(cm, vim, helpers) { helpers.doKeys('o'); cm.replaceRange('z', cm.getCursor()); cm.setCursor(1, 1); helpers.doInsertModeKeys('Esc'); helpers.doKeys('.'); eq('\nz\nz', cm.getValue()); helpers.assertCursorAt(2, 0); }, { value: ''}); testVim('._insert_o_repeat', function(cm, vim, helpers) { helpers.doKeys('o'); cm.replaceRange('z', cm.getCursor()); helpers.doInsertModeKeys('Esc'); cm.setCursor(1, 0); helpers.doKeys('2', '.'); eq('\nz\nz\nz', cm.getValue()); helpers.assertCursorAt(3, 0); }, { value: ''}); testVim('._insert_o_indent', function(cm, vim, helpers) { helpers.doKeys('o'); cm.replaceRange('z', cm.getCursor()); helpers.doInsertModeKeys('Esc'); cm.setCursor(1, 2); helpers.doKeys('.'); eq('{\n z\n z', cm.getValue()); helpers.assertCursorAt(2, 2); }, { value: '{'}); testVim('._insert_cw', function(cm, vim, helpers) { helpers.doKeys('c', 'w'); cm.replaceRange('test', cm.getCursor()); helpers.doInsertModeKeys('Esc'); cm.setCursor(0, 3); helpers.doKeys('2', 'l'); helpers.doKeys('.'); eq('test test word3', cm.getValue()); helpers.assertCursorAt(0, 8); }, { value: 'word1 word2 word3' }); testVim('._insert_cw_repeat', function(cm, vim, helpers) { // For some reason, repeat cw in desktop VIM will does not repeat insert mode // changes. Will conform to that behavior. helpers.doKeys('c', 'w'); cm.replaceRange('test', cm.getCursor()); helpers.doInsertModeKeys('Esc'); cm.setCursor(0, 4); helpers.doKeys('l'); helpers.doKeys('2', '.'); eq('test test', cm.getValue()); helpers.assertCursorAt(0, 8); }, { value: 'word1 word2 word3' }); testVim('._delete', function(cm, vim, helpers) { cm.setCursor(0, 5); helpers.doKeys('i'); helpers.doInsertModeKeys('Backspace', 'Esc'); helpers.doKeys('.'); eq('zace', cm.getValue()); helpers.assertCursorAt(0, 1); }, { value: 'zabcde'}); testVim('._delete_repeat', function(cm, vim, helpers) { cm.setCursor(0, 6); helpers.doKeys('i'); helpers.doInsertModeKeys('Backspace', 'Esc'); helpers.doKeys('2', '.'); eq('zzce', cm.getValue()); helpers.assertCursorAt(0, 1); }, { value: 'zzabcde'}); testVim('f;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('f', 'x'); helpers.doKeys(';'); helpers.doKeys('2', ';'); eq(9, cm.getCursor().ch); }, { value: '01x3xx678x'}); testVim('F;', function(cm, vim, helpers) { cm.setCursor(0, 8); helpers.doKeys('F', 'x'); helpers.doKeys(';'); helpers.doKeys('2', ';'); eq(2, cm.getCursor().ch); }, { value: '01x3xx6x8x'}); testVim('t;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('t', 'x'); helpers.doKeys(';'); helpers.doKeys('2', ';'); eq(8, cm.getCursor().ch); }, { value: '01x3xx678x'}); testVim('T;', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('T', 'x'); helpers.doKeys(';'); helpers.doKeys('2', ';'); eq(2, cm.getCursor().ch); }, { value: '0xx3xx678x'}); testVim('f,', function(cm, vim, helpers) { cm.setCursor(0, 6); helpers.doKeys('f', 'x'); helpers.doKeys(','); helpers.doKeys('2', ','); eq(2, cm.getCursor().ch); }, { value: '01x3xx678x'}); testVim('F,', function(cm, vim, helpers) { cm.setCursor(0, 3); helpers.doKeys('F', 'x'); helpers.doKeys(','); helpers.doKeys('2', ','); eq(9, cm.getCursor().ch); }, { value: '01x3xx678x'}); testVim('t,', function(cm, vim, helpers) { cm.setCursor(0, 6); helpers.doKeys('t', 'x'); helpers.doKeys(','); helpers.doKeys('2', ','); eq(3, cm.getCursor().ch); }, { value: '01x3xx678x'}); testVim('T,', function(cm, vim, helpers) { cm.setCursor(0, 4); helpers.doKeys('T', 'x'); helpers.doKeys(','); helpers.doKeys('2', ','); eq(8, cm.getCursor().ch); }, { value: '01x3xx67xx'}); testVim('fd,;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('f', '4'); cm.setCursor(0, 0); helpers.doKeys('d', ';'); eq('56789', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 9); helpers.doKeys('d', ','); eq('01239', cm.getValue()); }, { value: '0123456789'}); testVim('Fd,;', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('F', '4'); cm.setCursor(0, 9); helpers.doKeys('d', ';'); eq('01239', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 0); helpers.doKeys('d', ','); eq('56789', cm.getValue()); }, { value: '0123456789'}); testVim('td,;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('t', '4'); cm.setCursor(0, 0); helpers.doKeys('d', ';'); eq('456789', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 9); helpers.doKeys('d', ','); eq('012349', cm.getValue()); }, { value: '0123456789'}); testVim('Td,;', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('T', '4'); cm.setCursor(0, 9); helpers.doKeys('d', ';'); eq('012349', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 0); helpers.doKeys('d', ','); eq('456789', cm.getValue()); }, { value: '0123456789'}); testVim('fc,;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('f', '4'); cm.setCursor(0, 0); helpers.doKeys('c', ';', 'Esc'); eq('56789', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 9); helpers.doKeys('c', ','); eq('01239', cm.getValue()); }, { value: '0123456789'}); testVim('Fc,;', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('F', '4'); cm.setCursor(0, 9); helpers.doKeys('c', ';', 'Esc'); eq('01239', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 0); helpers.doKeys('c', ','); eq('56789', cm.getValue()); }, { value: '0123456789'}); testVim('tc,;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('t', '4'); cm.setCursor(0, 0); helpers.doKeys('c', ';', 'Esc'); eq('456789', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 9); helpers.doKeys('c', ','); eq('012349', cm.getValue()); }, { value: '0123456789'}); testVim('Tc,;', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('T', '4'); cm.setCursor(0, 9); helpers.doKeys('c', ';', 'Esc'); eq('012349', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 0); helpers.doKeys('c', ','); eq('456789', cm.getValue()); }, { value: '0123456789'}); testVim('fy,;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('f', '4'); cm.setCursor(0, 0); helpers.doKeys('y', ';', 'P'); eq('012340123456789', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 9); helpers.doKeys('y', ',', 'P'); eq('012345678456789', cm.getValue()); }, { value: '0123456789'}); testVim('Fy,;', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('F', '4'); cm.setCursor(0, 9); helpers.doKeys('y', ';', 'p'); eq('012345678945678', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 0); helpers.doKeys('y', ',', 'P'); eq('012340123456789', cm.getValue()); }, { value: '0123456789'}); testVim('ty,;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('t', '4'); cm.setCursor(0, 0); helpers.doKeys('y', ';', 'P'); eq('01230123456789', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 9); helpers.doKeys('y', ',', 'p'); eq('01234567895678', cm.getValue()); }, { value: '0123456789'}); testVim('Ty,;', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('T', '4'); cm.setCursor(0, 9); helpers.doKeys('y', ';', 'p'); eq('01234567895678', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 0); helpers.doKeys('y', ',', 'P'); eq('01230123456789', cm.getValue()); }, { value: '0123456789'}); testVim('HML', function(cm, vim, helpers) { var lines = 35; var textHeight = cm.defaultTextHeight(); cm.setSize(600, lines*textHeight); cm.setCursor(120, 0); helpers.doKeys('H'); helpers.assertCursorAt(86, 2); helpers.doKeys('L'); helpers.assertCursorAt(120, 4); helpers.doKeys('M'); helpers.assertCursorAt(103,4); }, { value: (function(){ var lines = new Array(100); var upper = ' xx\n'; var lower = ' xx\n'; upper = lines.join(upper); lower = lines.join(lower); return upper + lower; })()}); var zVals = ['zb','zz','zt','z-','z.','z'].map(function(e, idx){ var lineNum = 250; var lines = 35; testVim(e, function(cm, vim, helpers) { var k1 = e[0]; var k2 = e.substring(1); var textHeight = cm.defaultTextHeight(); cm.setSize(600, lines*textHeight); cm.setCursor(lineNum, 0); helpers.doKeys(k1, k2); zVals[idx] = cm.getScrollInfo().top; }, { value: (function(){ return new Array(500).join('\n'); })()}); }); testVim('zb', function(cm, vim, helpers){ eq(zVals[2], zVals[5]); }); var squareBracketMotionSandbox = ''+ '({\n'+//0 ' ({\n'+//11 ' /*comment {\n'+//2 ' */(\n'+//3 '#else \n'+//4 ' /* )\n'+//5 '#if }\n'+//6 ' )}*/\n'+//7 ')}\n'+//8 '{}\n'+//9 '#else {{\n'+//10 '{}\n'+//11 '}\n'+//12 '{\n'+//13 '#endif\n'+//14 '}\n'+//15 '}\n'+//16 '#else';//17 testVim('[[, ]]', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys(']', ']'); helpers.assertCursorAt(9,0); helpers.doKeys('2', ']', ']'); helpers.assertCursorAt(13,0); helpers.doKeys(']', ']'); helpers.assertCursorAt(17,0); helpers.doKeys('[', '['); helpers.assertCursorAt(13,0); helpers.doKeys('2', '[', '['); helpers.assertCursorAt(9,0); helpers.doKeys('[', '['); helpers.assertCursorAt(0,0); }, { value: squareBracketMotionSandbox}); testVim('[], ][', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys(']', '['); helpers.assertCursorAt(12,0); helpers.doKeys('2', ']', '['); helpers.assertCursorAt(16,0); helpers.doKeys(']', '['); helpers.assertCursorAt(17,0); helpers.doKeys('[', ']'); helpers.assertCursorAt(16,0); helpers.doKeys('2', '[', ']'); helpers.assertCursorAt(12,0); helpers.doKeys('[', ']'); helpers.assertCursorAt(0,0); }, { value: squareBracketMotionSandbox}); testVim('[{, ]}', function(cm, vim, helpers) { cm.setCursor(4, 10); helpers.doKeys('[', '{'); helpers.assertCursorAt(2,12); helpers.doKeys('2', '[', '{'); helpers.assertCursorAt(0,1); cm.setCursor(4, 10); helpers.doKeys(']', '}'); helpers.assertCursorAt(6,11); helpers.doKeys('2', ']', '}'); helpers.assertCursorAt(8,1); cm.setCursor(0,1); helpers.doKeys(']', '}'); helpers.assertCursorAt(8,1); helpers.doKeys('[', '{'); helpers.assertCursorAt(0,1); }, { value: squareBracketMotionSandbox}); testVim('[(, ])', function(cm, vim, helpers) { cm.setCursor(4, 10); helpers.doKeys('[', '('); helpers.assertCursorAt(3,14); helpers.doKeys('2', '[', '('); helpers.assertCursorAt(0,0); cm.setCursor(4, 10); helpers.doKeys(']', ')'); helpers.assertCursorAt(5,11); helpers.doKeys('2', ']', ')'); helpers.assertCursorAt(8,0); helpers.doKeys('[', '('); helpers.assertCursorAt(0,0); helpers.doKeys(']', ')'); helpers.assertCursorAt(8,0); }, { value: squareBracketMotionSandbox}); testVim('[*, ]*, [/, ]/', function(cm, vim, helpers) { ['*', '/'].forEach(function(key){ cm.setCursor(7, 0); helpers.doKeys('2', '[', key); helpers.assertCursorAt(2,2); helpers.doKeys('2', ']', key); helpers.assertCursorAt(7,5); }); }, { value: squareBracketMotionSandbox}); testVim('[#, ]#', function(cm, vim, helpers) { cm.setCursor(10, 3); helpers.doKeys('2', '[', '#'); helpers.assertCursorAt(4,0); helpers.doKeys('5', ']', '#'); helpers.assertCursorAt(17,0); cm.setCursor(10, 3); helpers.doKeys(']', '#'); helpers.assertCursorAt(14,0); }, { value: squareBracketMotionSandbox}); testVim('[m, ]m, [M, ]M', function(cm, vim, helpers) { cm.setCursor(11, 0); helpers.doKeys('[', 'm'); helpers.assertCursorAt(10,7); helpers.doKeys('4', '[', 'm'); helpers.assertCursorAt(1,3); helpers.doKeys('5', ']', 'm'); helpers.assertCursorAt(11,0); helpers.doKeys('[', 'M'); helpers.assertCursorAt(9,1); helpers.doKeys('3', ']', 'M'); helpers.assertCursorAt(15,0); helpers.doKeys('5', '[', 'M'); helpers.assertCursorAt(7,3); }, { value: squareBracketMotionSandbox}); // Ex mode tests testVim('ex_go_to_line', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doEx('4'); helpers.assertCursorAt(3, 0); }, { value: 'a\nb\nc\nd\ne\n'}); testVim('ex_write', function(cm, vim, helpers) { var tmp = CodeMirror.commands.save; var written; var actualCm; CodeMirror.commands.save = function(cm) { written = true; actualCm = cm; }; // Test that w, wr, wri ... write all trigger :write. var command = 'write'; for (var i = 1; i < command.length; i++) { written = false; actualCm = null; helpers.doEx(command.substring(0, i)); eq(written, true); eq(actualCm, cm); } CodeMirror.commands.save = tmp; }); testVim('ex_sort', function(cm, vim, helpers) { helpers.doEx('sort'); eq('Z\na\nb\nc\nd', cm.getValue()); }, { value: 'b\nZ\nd\nc\na'}); testVim('ex_sort_reverse', function(cm, vim, helpers) { helpers.doEx('sort!'); eq('d\nc\nb\na', cm.getValue()); }, { value: 'b\nd\nc\na'}); testVim('ex_sort_range', function(cm, vim, helpers) { helpers.doEx('2,3sort'); eq('b\nc\nd\na', cm.getValue()); }, { value: 'b\nd\nc\na'}); testVim('ex_sort_oneline', function(cm, vim, helpers) { helpers.doEx('2sort'); // Expect no change. eq('b\nd\nc\na', cm.getValue()); }, { value: 'b\nd\nc\na'}); testVim('ex_sort_ignoreCase', function(cm, vim, helpers) { helpers.doEx('sort i'); eq('a\nb\nc\nd\nZ', cm.getValue()); }, { value: 'b\nZ\nd\nc\na'}); testVim('ex_sort_unique', function(cm, vim, helpers) { helpers.doEx('sort u'); eq('Z\na\nb\nc\nd', cm.getValue()); }, { value: 'b\nZ\na\na\nd\na\nc\na'}); testVim('ex_sort_decimal', function(cm, vim, helpers) { helpers.doEx('sort d'); eq('d3\n s5\n6\n.9', cm.getValue()); }, { value: '6\nd3\n s5\n.9'}); testVim('ex_sort_decimal_negative', function(cm, vim, helpers) { helpers.doEx('sort d'); eq('z-9\nd3\n s5\n6\n.9', cm.getValue()); }, { value: '6\nd3\n s5\n.9\nz-9'}); testVim('ex_sort_decimal_reverse', function(cm, vim, helpers) { helpers.doEx('sort! d'); eq('.9\n6\n s5\nd3', cm.getValue()); }, { value: '6\nd3\n s5\n.9'}); testVim('ex_sort_hex', function(cm, vim, helpers) { helpers.doEx('sort x'); eq(' s5\n6\n.9\n&0xB\nd3', cm.getValue()); }, { value: '6\nd3\n s5\n&0xB\n.9'}); testVim('ex_sort_octal', function(cm, vim, helpers) { helpers.doEx('sort o'); eq('.8\n.9\nd3\n s5\n6', cm.getValue()); }, { value: '6\nd3\n s5\n.9\n.8'}); testVim('ex_sort_decimal_mixed', function(cm, vim, helpers) { helpers.doEx('sort d'); eq('y\nz\nc1\nb2\na3', cm.getValue()); }, { value: 'a3\nz\nc1\ny\nb2'}); testVim('ex_sort_decimal_mixed_reverse', function(cm, vim, helpers) { helpers.doEx('sort! d'); eq('a3\nb2\nc1\nz\ny', cm.getValue()); }, { value: 'a3\nz\nc1\ny\nb2'}); testVim('ex_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' }); function testSubstituteConfirm(name, command, initialValue, expectedValue, keys, finalPos) { testVim(name, function(cm, vim, helpers) { var savedOpenDialog = cm.openDialog; var savedKeyName = CodeMirror.keyName; var onKeyDown; var recordedCallback; var closed = true; // Start out closed, set false on second openDialog. function close() { closed = true; } // First openDialog should save callback. cm.openDialog = function(template, callback, options) { recordedCallback = callback; } // Do first openDialog. helpers.doKeys(':'); // Second openDialog should save keyDown handler. cm.openDialog = function(template, callback, options) { onKeyDown = options.onKeyDown; closed = false; }; // Return the command to Vim and trigger second openDialog. recordedCallback(command); // The event should really use keyCode, but here just mock it out and use // key and replace keyName to just return key. CodeMirror.keyName = function (e) { return e.key; } keys = keys.toUpperCase(); for (var i = 0; i < keys.length; i++) { is(!closed); onKeyDown({ key: keys.charAt(i) }, '', close); } try { eq(expectedValue, cm.getValue()); helpers.assertCursorAt(finalPos); is(closed); } catch(e) { throw e } finally { // Restore overriden functions. CodeMirror.keyName = savedKeyName; cm.openDialog = savedOpenDialog; } }, { value: initialValue }); }; testSubstituteConfirm('ex_substitute_confirm_emptydoc', '%s/x/b/c', '', '', '', makeCursor(0, 0)); testSubstituteConfirm('ex_substitute_confirm_nomatch', '%s/x/b/c', 'ba a\nbab', 'ba a\nbab', '', makeCursor(0, 0)); testSubstituteConfirm('ex_substitute_confirm_accept', '%s/a/b/c', 'ba a\nbab', 'bb b\nbbb', 'yyy', makeCursor(1, 1)); testSubstituteConfirm('ex_substitute_confirm_random_keys', '%s/a/b/c', 'ba a\nbab', 'bb b\nbbb', 'ysdkywerty', makeCursor(1, 1)); testSubstituteConfirm('ex_substitute_confirm_some', '%s/a/b/c', 'ba a\nbab', 'bb a\nbbb', 'yny', makeCursor(1, 1)); testSubstituteConfirm('ex_substitute_confirm_all', '%s/a/b/c', 'ba a\nbab', 'bb b\nbbb', 'a', makeCursor(1, 1)); testSubstituteConfirm('ex_substitute_confirm_accept_then_all', '%s/a/b/c', 'ba a\nbab', 'bb b\nbbb', 'ya', makeCursor(1, 1)); testSubstituteConfirm('ex_substitute_confirm_quit', '%s/a/b/c', 'ba a\nbab', 'bb a\nbab', 'yq', makeCursor(0, 3)); testSubstituteConfirm('ex_substitute_confirm_last', '%s/a/b/c', 'ba a\nbab', 'bb b\nbab', 'yl', makeCursor(0, 3)); testSubstituteConfirm('ex_substitute_confirm_oneline', '1s/a/b/c', 'ba a\nbab', 'bb b\nbab', 'yl', makeCursor(0, 3)); testSubstituteConfirm('ex_substitute_confirm_range_accept', '1,2s/a/b/c', 'aa\na \na\na', 'bb\nb \na\na', 'yyy', makeCursor(1, 0)); testSubstituteConfirm('ex_substitute_confirm_range_some', '1,3s/a/b/c', 'aa\na \na\na', 'ba\nb \nb\na', 'ynyy', makeCursor(2, 0)); testSubstituteConfirm('ex_substitute_confirm_range_all', '1,3s/a/b/c', 'aa\na \na\na', 'bb\nb \nb\na', 'a', makeCursor(2, 0)); testSubstituteConfirm('ex_substitute_confirm_range_last', '1,3s/a/b/c', 'aa\na \na\na', 'bb\nb \na\na', 'yyl', makeCursor(1, 0)); //:noh should clear highlighting of search-results but allow to resume search through n testVim('ex_noh_clearSearchHighlight', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('match'); helpers.doKeys('?'); helpers.doEx('noh'); eq(vim.searchState_.getOverlay(),null,'match-highlighting wasn\'t cleared'); helpers.doKeys('n'); helpers.assertCursorAt(0, 11,'can\'t resume search after clearing highlighting'); }, { value: 'match nope match \n nope Match' }); // 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('',''); 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' }); ================================================ FILE: public/packages/codemirror-3.19/theme/3024-day.css ================================================ /* Name: 3024 day Author: Jan T. Sott (http://github.com/idleberg) CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ .cm-s-3024-day.CodeMirror {background: #f7f7f7; color: #3a3432;} .cm-s-3024-day div.CodeMirror-selected {background: #d6d5d4 !important;} .cm-s-3024-day .CodeMirror-gutters {background: #f7f7f7; border-right: 0px;} .cm-s-3024-day .CodeMirror-linenumber {color: #807d7c;} .cm-s-3024-day .CodeMirror-cursor {border-left: 1px solid #5c5855 !important;} .cm-s-3024-day span.cm-comment {color: #cdab53;} .cm-s-3024-day span.cm-atom {color: #a16a94;} .cm-s-3024-day span.cm-number {color: #a16a94;} .cm-s-3024-day span.cm-property, .cm-s-3024-day span.cm-attribute {color: #01a252;} .cm-s-3024-day span.cm-keyword {color: #db2d20;} .cm-s-3024-day span.cm-string {color: #fded02;} .cm-s-3024-day span.cm-variable {color: #01a252;} .cm-s-3024-day span.cm-variable-2 {color: #01a0e4;} .cm-s-3024-day span.cm-def {color: #e8bbd0;} .cm-s-3024-day span.cm-bracket {color: #3a3432;} .cm-s-3024-day span.cm-tag {color: #db2d20;} .cm-s-3024-day span.cm-link {color: #a16a94;} .cm-s-3024-day span.cm-error {background: #db2d20; color: #5c5855;} .cm-s-3024-day .CodeMirror-activeline-background {background: #e8f2ff !important;} .cm-s-3024-day .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/3024-night.css ================================================ /* Name: 3024 night Author: Jan T. Sott (http://github.com/idleberg) CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ .cm-s-3024-night.CodeMirror {background: #090300; color: #d6d5d4;} .cm-s-3024-night div.CodeMirror-selected {background: #3a3432 !important;} .cm-s-3024-night .CodeMirror-gutters {background: #090300; border-right: 0px;} .cm-s-3024-night .CodeMirror-linenumber {color: #5c5855;} .cm-s-3024-night .CodeMirror-cursor {border-left: 1px solid #807d7c !important;} .cm-s-3024-night span.cm-comment {color: #cdab53;} .cm-s-3024-night span.cm-atom {color: #a16a94;} .cm-s-3024-night span.cm-number {color: #a16a94;} .cm-s-3024-night span.cm-property, .cm-s-3024-night span.cm-attribute {color: #01a252;} .cm-s-3024-night span.cm-keyword {color: #db2d20;} .cm-s-3024-night span.cm-string {color: #fded02;} .cm-s-3024-night span.cm-variable {color: #01a252;} .cm-s-3024-night span.cm-variable-2 {color: #01a0e4;} .cm-s-3024-night span.cm-def {color: #e8bbd0;} .cm-s-3024-night span.cm-bracket {color: #d6d5d4;} .cm-s-3024-night span.cm-tag {color: #db2d20;} .cm-s-3024-night span.cm-link {color: #a16a94;} .cm-s-3024-night span.cm-error {background: #db2d20; color: #807d7c;} .cm-s-3024-night .CodeMirror-activeline-background {background: #2F2F2F !important;} .cm-s-3024-night .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/ambiance-mobile.css ================================================ .cm-s-ambiance.CodeMirror { -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } ================================================ FILE: public/packages/codemirror-3.19/theme/ambiance.css ================================================ /* 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-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 .cm-error { color: #AF2018; } .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; 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 .CodeMirror-activeline-background { background: none repeat scroll 0% 0% rgba(255, 255, 255, 0.031); } .cm-s-ambiance.CodeMirror, .cm-s-ambiance .CodeMirror-gutters { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAQAAAAHUWYVAABFFUlEQVQYGbzBCeDVU/74/6fj9HIcx/FRHx9JCFmzMyGRURhLZIkUsoeRfUjS2FNDtr6WkMhO9sm+S8maJfu+Jcsg+/o/c+Z4z/t97/vezy3z+z8ekGlnYICG/o7gdk+wmSHZ1z4pJItqapjoKXWahm8NmV6eOTbWUOp6/6a/XIg6GQqmenJ2lDHyvCFZ2cBDbmtHA043VFhHwXxClWmeYAdLhV00Bd85go8VmaFCkbVkzlQENzfBDZ5gtN7HwF0KDrTwJ0dypSOzpaKCMwQHKTIreYIxlmhXTzTWkVm+LTynZhiSBT3RZQ7aGfjGEd3qyXQ1FDymqbKxpspERQN2MiRjNZlFFQXfCNFm9nM1zpAsoYjmtRTc5ajwuaXc5xrWskT97RaKzAGe5ARHhVUsDbjKklziiX5WROcJwSNCNI+9w1Jwv4Zb2r7lCMZ4oq5C0EdTx+2GzNuKpJ+iFf38JEWkHJn9DNF7mmBDITrWEg0VWL3pHU20tSZnuqWu+R3BtYa8XxV1HO7GyD32UkOpL/yDloINFTmvtId+nmAjxRw40VMwVKiwrKLE4bK5UOVntYwhOcSSXKrJHKPJedocpGjVz/ZMIbnYUPB10/eKCrs5apqpgVmWzBYWpmtKHecJPjaUuEgRDDaU0oZghCJ6zNMQ5ZhDYx05r5v2muQdM0EILtXUsaKiQX9WMEUotagQzFbUNN6NUPC2nm5pxEWGCjMc3GdJHjSU2kORLK/JGSrkfGEIjncU/CYUnOipoYemwj8tST9NsJmB7TUVXtbUtXATJVZXBMvYeTXJfobgJUPmGMP/yFaWonaa6BcFO3nqcIqCozSZoZoSr1g4zJOzuyGnxTEX3lUEJ7WcZgme8ddaWvWJo2AJR9DZU3CUIbhCSG6ybSwN6qtJVnCU2svDTP2ZInOw2cBTrqtQahtNZn9NcJ4l2NaSmSkkP1noZWnVwkLmdUPOwLZEwy2Z3S3R+4rIG9hcbpPXHFVWcQdZkn2FOta3cKWQnNRC5g1LsJah4GCzSVsKnCOY5OAFRTBekyyryeyilhFKva75r4Mc0aWanGEaThcy31s439KKxTzJYY5WTHPU1FtIHjQU3Oip4xlNzj/lBw23dYZVliQa7WAXf4shetcQfatI+jWRDBPmyNeW6A1P5kdDgyYJlba0BIM8BZu1JfrFwItyjcAMR3K0BWOIrtMEXyhyrlVEx3ui5dUBjmB/Q3CXW85R4mBD0s7B+4q5tKUjOlb9qqmhi5AZ6GFIC5HXtOobdYGlVdMVbNJ8toNTFcHxnoL+muBagcctjWnbNMuR00uI7nQESwg5q2qqrKWIfrNUmeQocY6HuyxJV02wj36w00yhpmUFenv4p6fUkZYqLyuinx2RGOjhCXYyJF84oiU00YMOOhhquNdfbOB7gU88pY4xJO8LVdp6/q2voeB4R04vIdhSE40xZObx1HGGJ/ja0LBthFInKaLPPFzuCaYaoj8JjPME8yoyxo6zlBqkiUZYgq00OYMswbWO5NGmq+xhipxHLRW29ARjNKXO0wRnear8XSg4XFPLKEPUS1GqvyLwiuBUoa7zpZ0l5xxFwWmWZC1H5h5FwU8eQ7K+g8UcVY6TMQreVQT/8uQ8Z+ALIXnSEa2pYZQneE9RZbSBNYXfWYJzW/h/4j4Dp1tYVcFIC5019Vyi4ThPqSFCzjGWaHQTBU8q6vrVwgxP9Lkm840imWKpcLCjYTtrKuwvsKSnrvHCXGkSMk9p6lhckfRpIeis+N2PiszT+mFLspyGleUhDwcLrZqmyeylxwjBcKHEapqkmyangyLZRVOijwOtCY5SsG5zL0OwlCJ4y5KznF3EUNDDrinwiyLZRzOXtlBbK5ITHFGLp8Q0R6ab6mS7enI2cFrxOyHvOCFaT1HThS1krjCwqWeurCkk+willhCC+RSZnRXBiZaC5RXRIZYKp2lyfrHwiKPKR0JDzrdU2EFgpidawlFDR6FgXUMNa+g1FY3bUQh2cLCwosRdnuQTS/S+JVrGLeWIvtQUvONJxlqSQYYKpwoN2kaocLjdVsis4Mk80ESF2YpSkzwldjHkjFCUutI/r+EHDU8oCs6yzL3PhWiEooZdFMkymlas4AcI3KmoMMNSQ3tHzjGWCrcJJdYyZC7QFGwjRL9p+MrRkAGWzIaWCn9W0F3TsK01c2ZvQw0byvxuQU0r1lM0qJO7wW0kRIMdDTtXEdzi4VIh+EoIHm0mWtAtpCixlabgn83fKTI7anJe9ST7WIK1DMGpQmYeA58ImV6ezOGOzK2Kgq01pd60cKWiUi9Lievb/0vIDPHQ05Kzt4ddPckQBQtoaurjyHnek/nKzpQLrVgKPjIkh2v4uyezpv+Xoo7fPFXaGFp1vaLKxQ4uUpQQS5VuQs7BCq4xRJv7fwpVvvFEB3j+620haOuocqMhWd6TTPAEx+mdFNGHdranFe95WrWmIvlY4F1Dle2ECgc6cto7SryuqGGGha0tFQ5V53migUKmg6XKAo4qS3mik+0OZpAhOLeZKicacgaYcyx5hypYQE02ZA4xi/pNhOQxR4klNKyqacj+mpxnLTnnGSo85++3ZCZq6lrZkXlGEX3o+C9FieccJbZWVFjC0Yo1FZnJhoYMFoI1hEZ9r6hwg75HwzBNhbZCdJEfJwTPGzJvaKImw1yYX1HDAmpXR+ZJQ/SmgqMNVQb5vgamGwLtt7VwvP7Qk1xpiM5x5Cyv93E06MZmgs0Nya2azIKOYKCGBQQW97RmhKNKF02JZqHEJ4o58qp7X5EcZmc56trXEqzjCBZ1MFGR87Ql2tSTs6CGxS05PTzRQorkbw7aKoKXFDXsYW42VJih/q+FP2BdTzDTwVqOYB13liM50vG7wy28qagyuIXMeQI/Oqq8bcn5wJI50xH00CRntyfpL1T4hydYpoXgNiFzoIUTDZnLNRzh4TBHwbYGDvZkxmlyJloyr6tRihpeUG94GnKtIznREF0tzJG/OOr73JBcrSh1k6WuTprgLU+mnSGnv6Zge0NNz+kTDdH8nuAuTdJDCNb21LCiIuqlYbqGzT3RAoZofQfjFazkqeNWdYaGvYTM001EW2oKPvVk1ldUGSgUtHFwjKM1h9jnFcmy5lChoLNaQMGGDsYbKixlaMBmmsx1QjCfflwTfO/gckW0ruZ3jugKR3R5W9hGUWqCgxuFgsuaCHorotGKzGaeZB9DMsaTnKCpMtwTvOzhYk0rdrArKCqcaWmVk1+F372ur1YkKxgatI8Qfe1gIX9wE9FgS8ESmuABIXnRUbCapcKe+nO7slClSZFzpV/LkLncEb1qiO42fS3R855Su2mCLh62t1SYZZYVmKwIHjREF2uihTzB20JOkz7dkxzYQnK0UOU494wh+VWRc6Un2kpTaVgLDFEkJ/uhzRcI0YKGgpGWOlocBU/a4fKoJ/pEaNV6jip3+Es9VXY078rGnmAdf7t9ylPXS34RBSuYPs1UecZTU78WanhBCHpZ5sAoTz0LGZKjPf9TRypqWEiTvOFglL1fCEY3wY/++rbk7C8bWebA6p6om6PgOL2kp44TFJlVNBXae2rqqdZztOJpT87GQsE9jqCPIe9VReZuQ/CIgacsyZdCpIScSYqcZk8r+nsyCzhyfhOqHGOIvrLknC8wTpFcaYiGC/RU1NRbUeUpocQOnkRpGOrIOcNRx+1uA0UrzhSSt+VyS3SJpnFWkzNDqOFGIWcfR86DnmARTQ1HKIL33ExPiemeOhYSSjzlSUZZuE4TveoJLnBUOFof6KiysCbnAEcZgcUNTDOwkqWu3RWtmGpZwlHhJENdZ3miGz0lJlsKnjbwqSHQjpxnFDlTLLwqJPMZMjd7KrzkSG7VsxXBZE+F8YZkb01Oe00yyRK9psh5SYh29ySPKBo2ylNht7ZkZnsKenjKNJu9PNEyZpaCHv4Kt6RQsLvAVp7M9kIimmCUwGeWqLMmGuIotYMmWNpSahkhZw9FqZsVnKJhsjAHvtHMsTM9fCI06Dx/u3vfUXCqfsKRc4oFY2jMsoo/7DJDwZ1CsIKnJu+J9ldkpmiCxQx1rWjI+T9FwcWWzOuaYH0Hj7klNRVWEQpmaqosakiGNTFHdjS/qnUdmf0NJW5xsL0HhimCCZZSRzmSPTXJQ4aaztAwtZnoabebJ+htCaZ7Cm535ByoqXKbX1WRc4Eh2MkRXWzImVc96Cj4VdOKVxR84VdQsIUM8Psoou2byVHyZFuq7O8otbSQ2UAoeEWTudATLGSpZzVLlXVkPU2Jc+27lsw2jmg5T5VhbeE3BT083K9WsTTkFU/Osi0rC5lRlpwRHUiesNS0sOvmqGML1aRbPAxTJD9ZKtxuob+hhl8cwYGWpJ8nub7t5p6coYbMovZ1BTdaKn1jYD6h4GFDNFyT/Kqe1XCXphXHOKLZmuRSRdBPEfVUXQzJm5YGPGGJdvAEr7hHNdGZnuBvrpciGmopOLf5N0uVMy0FfYToJk90uUCbJupaVpO53UJXR2bVpoU00V2KOo4zMFrBd0Jtz2pa0clT5Q5L8IpQ177mWQejPMEJhuQjS10ref6HHjdEhy1P1EYR7GtO0uSsKJQYLiTnG1rVScj5lyazpqWGl5uBbRWl7m6ixGOOnEsMJR7z8J0n6KMnCdxhiNYQCoZ6CmYLnO8omC3MkW3bktlPmEt/VQQHejL3+dOE5FlPdK/Mq8hZxxJtLyRrepLThYKbLZxkSb5W52vYxNOaOxUF0yxMUPwBTYqCzy01XayYK0sJyWBLqX0MwU5CzoymRzV0EjjeUeLgDpTo6ij42ZAzvD01dHUUTPLU96MdLbBME8nFBn7zJCMtJcZokn8YoqU0FS5WFKyniHobguMcmW8N0XkWZjkyN3hqOMtS08r+/xTBwpZSZ3qiVRX8SzMHHjfUNFjgHEPmY9PL3ykEzxkSre/1ZD6z/NuznuB0RcE1TWTm9zRgfUWVJiG6yrzgmWPXC8EAR4Wxhlad0ZbgQyEz3pG5RVEwwDJH2mgKpjcTiCOzn1lfUWANFbZ2BA8balnEweJC9J0iuaeZoI+ippFCztEKVvckR2iice1JvhVytrQwUAZpgsubCPaU7xUe9vWnaOpaSBEspalykhC9bUlOMpT42ZHca6hyrqKmw/wMR8H5ZmdFoBVJb03O4UL0tSNnvIeRmkrLWqrs78gcrEn2tpcboh0UPOW3UUR9PMk4T4nnNKWmCjlrefhCwxRNztfmIQVdDElvS4m1/WuOujoZCs5XVOjtKPGokJzsYCtFYoWonSPT21DheU/wWhM19FcElwqNGOsp9Q8N/cwXaiND1MmeL1Q5XROtYYgGeFq1aTMsoMmcrKjQrOFQTQ1fmBYhmW6o8Jkjc7iDJRTBIo5kgJD5yMEYA3srCg7VFKwiVJkmRCc5ohGOKhsYMn/XBLdo5taZjlb9YAlGWRimqbCsoY7HFAXLa5I1HPRxMMsQDHFkWtRNniqT9UEeNjcE7RUlrCJ4R2CSJuqlKHWvJXjAUNcITYkenuBRB84TbeepcqTj3zZyFJzgYQdHnqfgI0ddUwS6GqWpsKWhjq9cV0vBAEMN2znq+EBfIWT+pClYw5xsTlJU6GeIBsjGmmANTzJZiIYpgrM0Oa8ZMjd7NP87jxhqGOhJlnQtjuQpB+8aEE00wZFznSJPyHxgH3HkPOsJFvYk8zqCHzTs1BYOa4J3PFU+UVRZxlHDM4YavlNUuMoRveiZA2d7grMNc2g+RbSCEKzmgYsUmWmazFJyoiOZ4KnyhKOGRzWJa0+moyV4TVHDzn51Awtqaphfk/lRQ08FX1iiqxTB/kLwd0VynKfEvI6cd4XMV5bMhZ7gZUWVzYQ6Nm2BYzxJbw3bGthEUUMfgbGeorae6DxHtJoZ6alhZ0+ytiVoK1R4z5PTrOECT/SugseEOlb1MMNR4VRNcJy+V1Hg9ONClSZFZjdHlc6W6FBLdJja2MC5hhpu0DBYEY1TFGwiFAxRRCsYkiM9JRb0JNMVkW6CZYT/2EiTGWmo8k+h4FhDNE7BvppoTSFnmCV5xZKzvcCdDo7VVPnIU+I+Rc68juApC90MwcFCsJ5hDqxgScYKreruyQwTqrzoqDCmhWi4IbhB0Yrt3RGa6GfDv52rKXWhh28dyZaWUvcZeMTBaZoSGyiCtRU5J8iviioHaErs7Jkj61syVzTTgOcUOQ8buFBTYWdL5g3T4qlpe0+wvD63heAXRfCCIed9RbCsp2CiI7raUOYOTU13N8PNHvpaGvayo4a3LLT1lDrVEPT2zLUlheB1R+ZTRfKWJ+dcocLJfi11vyJ51lLqJ0WD7tRwryezjiV5W28uJO9qykzX8JDe2lHl/9oyBwa2UMfOngpXCixvKdXTk3wrsKmiVYdZIqsoWEERjbcUNDuiaQomGoIbFdEHmsyWnuR+IeriKDVLnlawlyNHKwKlSU631PKep8J4Q+ayjkSLKYLhalNHlYvttb6fHm0p6OApsZ4l2VfdqZkjuysy6ysKLlckf1KUutCTs39bmCgEyyoasIWlVaMF7mgmWtBT8Kol5xpH9IGllo8cJdopcvZ2sImlDmMIbtDk3KIpeNiS08lQw11NFPTwVFlPP6pJ2gvRfI7gQUfmNAtf6Gs0wQxDsKGlVBdF8rCa3jzdwMaGHOsItrZk7hAyOzpK9VS06j5F49b0VNGOOfKs3lDToMsMBe9ZWtHFEgxTJLs7qrygKZjUnmCYoeAqeU6jqWuLJup4WghOdvCYJnrSkSzoyRkm5M2StQwVltPkfCAk58tET/CSg+8MUecmotMEnhBKfWBIZsg2ihruMJQaoIm+tkTLKEqspMh00w95gvFCQRtDwTT1gVDDSEVdlwqZfxoQRbK0g+tbiBZxzKlpnpypejdDwTaeOvorMk/IJE10h9CqRe28hhLbe0pMsdSwv4ZbhKivo2BjDWfL8UKJgeavwlwb5KlwhyE4u4XkGE2ytZCznKLCDZZq42VzT8HLCrpruFbIfOIINmh/qCdZ1ZBc65kLHR1Bkyf5zn6pN3SvGKIlFNGplhrO9QSXanLOMQTLCa0YJCRrCZm/CZmrLTm7WzCK4GJDiWUdFeYx1LCFg3NMd0XmCuF3Y5rITLDUsYS9zoHVzwnJoYpSTQoObyEzr4cFBNqYTopoaU/wkyLZ2lPhX/5Y95ulxGTV7KjhWrOZgl8MyUUafjYraNjNU1N3IWcjT5WzWqjwtoarHSUObGYO3GCJZpsBlnJGPd6ZYLyl1GdCA2625IwwJDP8GUKymbzuyPlZlvTUsaUh5zFDhRWFzPKKZLAlWdcQbObgF9tOqOsmB1dqcqYJmWstFbZRRI9poolmqiLnU0POvxScpah2iSL5UJNzgScY5+AuIbpO0YD3NCW+dLMszFSdFCWGqG6eVq2uYVNDdICGD6W7EPRWZEY5gpsE9rUkS3mijzzJnm6UpUFXG1hCUeVoS5WfNcFpblELL2qqrCvMvRfd45oalvKU2tiQ6ePJOVMRXase9iTtLJztPxJKLWpo2CRDcJwn2sWSLKIO1WQWNTCvpVUvOZhgSC40JD0dOctaSqzkCRbXsKlb11Oip6PCJ0IwSJM31j3akRxlP7Rwn6aGaUL0qiLnJkvB3xWZ2+Q1TfCwpQH3G0o92UzmX4o/oJNQMMSQc547wVHhdk+VCw01DFYEnTxzZKAm74QmeNNR1w6WzEhNK15VJzuCdxQ53dRUDws5KvwgBMOEgpcVNe0hZI6RXT1Jd0cyj5nsaEAHgVmGaJIlWdsc5Ui2ElrRR6jrRAttNMEAIWrTDFubkZaok7/AkzfIwfuWVq0jHzuCK4QabtLUMVPB3kJ0oyHTSVFlqMALilJf2Rf8k5aaHtMfayocLBS8L89oKoxpJvnAkDPa0qp5DAUTHKWmCcnthlou8iCKaFFLHWcINd1nyIwXqrSxMNmSs6KmoL2QrKuWtlQ5V0120xQ5vRyZS1rgFkWwhiOwiuQbR0OOVhQM9iS3tiXp4RawRPMp5tDletOOBL95MpM01dZTBM9pkn5qF010rIeHFcFZhmSGpYpTsI6nwhqe5C9ynhlpp5ophuRb6WcJFldkVnVEwwxVfrVkvnWUuNLCg5bgboFHPDlDPDmnK7hUrWiIbjadDclujlZcaokOFup4Ri1kacV6jmrrK1hN9bGwpKEBQ4Q6DvIUXOmo6U5LqQM6EPyiKNjVkPnJkDPNEaxhiFay5ExW1NXVUGqcpYYdPcGiCq7z/TSlbhL4pplWXKd7NZO5QQFrefhRQW/NHOsqcIglc4UhWklR8K0QzbAw08CBDnpbgqXdeD/QUsM4RZXDFBW6WJKe/mFPdH0LtBgiq57wFLzlyQzz82qYx5D5WJP5yVJDW01BfyHnS6HKO/reZqId1WGa4Hkh2kWodJ8i6KoIPlAj2hPt76CzXsVR6koPRzWTfKqIentatYpQw2me4AA3y1Kind3SwoOKZDcFXTwl9tWU6mfgRk9d71sKtlNwrjnYw5tC5n5LdKiGry3JKNlHEd3oaMCFHrazBPMp/uNJ+V7IudcSbeOIdjUEdwl0VHCOZo5t6YluEuaC9mQeMgSfOyKnYGFHcIeQ84yQWbuJYJpZw5CzglDH7gKnWqqM9ZTaXcN0TeYhR84eQtJT76JJ1lREe7WnnvsMmRc9FQ7SBBM9mV3lCUdmHk/S2RAMt0QjFNFqQpWjDPQ01DXWUdDBkXziKPjGEP3VP+zIWU2t7im41FOloyWzn/L6dkUy3VLDaZ6appgDLHPjJEsyvJngWEPUyVBiAaHCTEXwrLvSEbV1e1gKJniicWorC1MUrVjB3uDhJE/wgSOzk1DXpk0k73qCM8xw2UvD5kJmDUfOomqMpWCkJRlvKXGmoeBm18USjVIk04SClxTB6YrgLAPLWYK9HLUt5cmc0vYES8GnTeRc6skZbQkWdxRsIcyBRzx1DbTk9FbU0caTPOgJHhJKnOGIVhQqvKmo0llRw9sabrZkDtdg3PqaKi9oatjY8B+G371paMg6+mZFNNtQ04mWBq3rYLOmtWWQp8KJnpy9DdFensyjdqZ+yY40VJlH8wcdLzC8PZnvHMFUTZUrDTkLyQaGus5X5LzpYAf3i+e/ZlhqGqWhh6Ou6xTR9Z6oi5AZZtp7Mj2EEm8oSpxiYZCHU/1fbGdNNNRRoZMhmilEb2gqHOEJDtXkHK/JnG6IrvbPCwV3NhONVdS1thBMs1T4QOBcTWa2IzhMk2nW5Kyn9tXUtpv9RsG2msxk+ZsQzRQacJncpgke0+T8y5Fzj8BiGo7XlJjaTIlpQs7KFjpqGnKuoyEPeIKnFMkZHvopgh81ySxNFWvJWcKRs70j2FOT012IllEEO1n4pD1513Yg2ssQPOThOkvyrqHUdEXOSEsihmBbTbKX1kLBPWqWkLOqJbjB3GBIZmoa8qWl4CG/iZ7oiA72ZL7TJNeZUY7kFQftDcHHluBzRbCegzMtrRjVQpX2lgoPKKLJAkcbMl01XK2p7yhL8pCBbQ3BN2avJgKvttcrWDK3CiUOVxQ8ZP+pqXKyIxnmBymCg5vJjNfkPK4+c8cIfK8ocVt7kmfd/I5SR1hKvCzUtb+lhgc00ZaO6CyhIQP1Uv4yIZjload72PXX0OIJvnFU+0Zf6MhsJwTfW0r0UwQfW4LNLZl5HK261JCZ4qnBaAreVAS3WrjV0LBnNDUNNDToCEeFfwgcb4gOEqLRhirWkexrCEYKVV711DLYEE1XBEsp5tpTGjorkomKYF9FDXv7fR3BGwbettSxnyL53MBPjsxDZjMh+VUW9NRxq1DhVk+FSxQcaGjV9Pawv6eGByw5qzoy7xk4RsOShqjJwWKe/1pEEfzkobeD/dQJmpqedcyBTy2sr4nGNRH0c0SPWTLrqAc0OQcb/gemKgqucQT7ySWKCn2EUotoCvpZct7RO2sy/QW0IWcXd7pQRQyZVwT2USRO87uhjioTLKV2brpMUcMQRbKH/N2T+UlTpaMls6cmc6CCNy3JdYYSUzzJQ4oSD3oKLncULOiJvjBEC2oqnCJkJluCYy2ZQ5so9YYlZ1VLlQU1mXEW1jZERwj/MUSRc24TdexlqLKfQBtDTScJUV8FszXBEY5ktpD5Ur9hYB4Nb1iikw3JoYpkKX+RodRKFt53MMuRnKSpY31PwYaGaILh3wxJGz9TkTPEETxoCWZrgvOlmyMzxFEwVJE5xZKzvyJ4WxEc16Gd4Xe3Weq4XH2jKRikqOkGQ87hQnC7wBmGYLAnesX3M+S87eFATauuN+Qcrh7xIxXJbUIdMw3JGE3ylCWzrieaqCn4zhGM19TQ3z1oH1AX+pWEqIc7wNGAkULBo/ZxRaV9NNyh4Br3rCHZzbzmSfawBL0dNRwpW1kK9mxPXR9povcdrGSZK9c2k0xwFGzjuniCtRSZCZ6ccZ7gaktmgAOtKbG/JnOkJrjcQTdFMsxRQ2cLY3WTIrlCw1eWKn8R6pvt4GFDso3QoL4a3nLk3G6JrtME3dSenpx7PNFTmga0EaJTLQ061sEeQoWXhSo9LTXsaSjoJQRXeZLtDclbCrYzfzHHeaKjHCVOUkQHO3JeEepr56mhiyaYYKjjNU+Fed1wS5VlhWSqI/hYUdDOkaxiKehoyOnrCV5yBHtbWFqTHCCwtpDcYolesVR5yUzTZBb3RNMd0d6WP+SvhuBmRcGxnuQzT95IC285cr41cLGQ6aJJhmi4TMGempxeimBRQw1tFKV+8jd6KuzoSTqqDxzRtpZkurvKEHxlqXKRIjjfUNNXQsNOsRScoWFLT+YeRZVD3GRN0MdQcKqQjHDMrdGGVu3iYJpQx3WGUvfbmxwFfR20WBq0oYY7LMFhhgYtr8jpaEnaOzjawWWaTP8mMr0t/EPDPoqcnxTBI5o58L7uoWnMrpoqPwgVrlAUWE+V+TQl9rawoyP6QGAlQw2TPRX+YSkxyBC8Z6jhHkXBgQL7WII3DVFnRfCrBfxewv9D6xsyjys4VkhWb9pUU627JllV0YDNHMku/ldNMMXDEo4aFnAkk4U6frNEU4XgZUPmEKHUl44KrzmYamjAbh0JFvGnaTLPu1s9jPCwjFpYiN7z1DTOk/nc07CfDFzmCf7i+bfNHXhDtLeBXzTBT5rkMvWOIxpl4EMh2LGJBu2syDnAEx2naEhHDWMMzPZEhygyS1mS5RTJr5ZkoKbEUoYqr2kqdDUE8ztK7OaIntJkFrIECwv8LJTaVx5XJE86go8dFeZ3FN3rjabCAYpoYEeC9zzJVULBbmZhDyd7ko09ydpNZ3nm2Kee4FPPXHnYEF1nqOFEC08LUVcDvYXkJHW8gTaKCk9YGOeIJhqiE4ToPEepdp7IWFjdwnWaufGMwJJCMtUTTBBK9BGCOy2tGGrJTHIwyEOzp6aPzNMOtlZkDvcEWpP5SVNhfkvDxhmSazTJXYrM9U1E0xwFVwqZQwzJxw6+kGGGUj2FglGGmnb1/G51udRSMNlTw6GGnCcUwVcOpmsqTHa06o72sw1RL02p9z0VbnMLOaIX3QKaYKSCFQzBKEUNHTSc48k53RH9wxGMtpQa5KjjW0W0n6XCCCG4yxNNdhQ4R4l1Ff+2sSd6UFHiIEOyqqFgT01mEUMD+joy75jPhOA+oVVLm309FR4yVOlp4RhLiScNmSmaYF5Pw0STrOIoWMSR2UkRXOMp+M4SHW8o8Zoi6OZgjKOaFar8zZDzkWzvKOjkKBjmCXby8JahhjXULY4KlzgKLvAwxVGhvyd4zxB1d9T0piazmKLCVZY5sKiD0y2ZSYrkUEPUbIk+dlQ4SJHTR50k1DPaUWIdTZW9NJwnJMOECgd7ou/MnppMJ02O1VT4Wsh85MnZzcFTngpXGKo84qmwgKbCL/orR/SzJ2crA+t6Mp94KvxJUeIbT3CQu1uIdlQEOzlKfS3UMcrTiFmOuroocrZrT2AcmamOKg8YomeEKm/rlT2sociMaybaUlFhuqHCM2qIJ+rg4EcDFymiDSxzaHdPcpE62pD5kyM5SBMoA1PaUtfIthS85ig1VPiPPYXgYEMNk4Qq7TXBgo7oT57gPUdwgCHzhIVFPFU6OYJzHAX9m5oNrVjeE61miDrqQ4VSa1oiURTsKHC0IfjNwU2WzK6eqK8jWln4g15TVBnqmDteCJ501PGAocJhhqjZdtBEB6lnhLreFJKxmlKbeGrqLiSThVIbCdGzloasa6lpMQXHCME2boLpJgT7yWaemu6wBONbqGNVRS0PKIL7LckbjmQtR7K8I5qtqel+T/ChJTNIKLjdUMNIRyvOEko9YYl2cwQveBikCNawJKcLBbc7+JM92mysNvd/Fqp8a0k6CNEe7cnZrxlW0wQXaXjaktnRwNOGZKYiONwS7a1JVheq3WgJHlQUGKHKmp4KAxXR/ULURcNgoa4zhKSLpZR3kxRRb0NmD0OFn+UCS7CzI1nbP6+o4x47QZE5xRCt3ZagnYcvmpYQktXdk5YKXTzBC57kKEe0VVuiSYqapssMS3C9p2CKkHOg8B8Pa8p5atrIw3qezIWanMGa5HRDNF6RM9wcacl0N+Q8Z8hsIkSnaIIdHRUOEebAPy1zbCkhM062FCJtif7PU+UtoVXzWKqM1PxXO8cfdruhFQ/a6x3JKYagvVDhQEtNiyiiSQ7OsuRsZUku0CRNDs4Sog6KKjsZgk2bYJqijgsEenoKeniinRXBn/U3lgpPdyDZynQx8IiioMnCep5Ky8mjGs6Wty0l1hUQTcNWswS3WRp2kCNZwJG8omG8JphPUaFbC8lEfabwP7VtM9yoaNCAjpR41VNhrD9LkbN722v0CoZMByFzhaW+MyzRYEWFDQwN2M4/JiT76PuljT3VU/A36eaIThb+R9oZGOAJ9tewkgGvqOMNRWYjT/Cwu99Q8LqDE4TgbLWxJ1jaDDAERsFOFrobgjUsBScaguXU8kKm2RL19tRypSHnHNlHiIZqgufs4opgQdVdwxBNNFBR6kVFqb8ogimOzB6a6HTzrlDHEpYaxjiiA4TMQobkDg2vejjfwJGWmnbVFAw3H3hq2NyQfG7hz4aC+w3BbwbesG0swYayvpAs6++Ri1Vfzx93mFChvyN5xVHTS+0p9aqCAxyZ6ZacZyw5+7uuQkFPR9DDk9NOiE7X1PCYJVjVUqq7JlrHwWALF5nfHNGjApdpqgzx5OwilDhCiDYTgnc9waGW4BdLNNUQvOtpzDOWHDH8D7TR/A/85KljEQu3NREc4Pl/6B1Hhc8Umb5CsKMmGC9EPcxoT2amwHNCmeOEnOPbklnMkbOgIvO5UMOpQrS9UGVdt6iH/fURjhI/WOpaW9OKLYRod6HCUEdOX000wpDZQ6hwg6LgZfOqo1RfT/CrJzjekXOGhpc1VW71ZLbXyyp+93ILbC1kPtIEYx0FIx1VDrLoVzXRKRYWk809yYlC9ImcrinxtabKnzRJk3lAU1OLEN1j2zrYzr2myHRXJFf4h4QKT1qSTzTB5+ZNTzTRkAxX8FcLV2uS8eoQQ2aAkFzvCM72sJIcJET3WPjRk5wi32uSS9rfZajpWEvj9hW42F4o5NytSXYy8IKHay10VYdrcl4SkqscrXpMwyGOgtkajheSxdQqmpxP1L3t4R5PqasFnrQEjytq6qgp9Y09Qx9o4S1FzhUCn1kyHSzBWLemoSGvOqLNhZyBjmCaAUYpMgt4Ck7wBBMMwWKWgjsUwTaGVsxWC1mYoKiyqqeGKYqonSIRQ3KIkHO0pmAxTdBHkbOvfllfr+AA+7gnc50huVKYK393FOyg7rbPO/izI7hE4CnHHHnJ0ogNPRUGeUpsrZZTBJcrovUcJe51BPsr6GkJdhCCsZ6aTtMEb2pqWkqeVtDXE/QVggsU/Nl86d9RMF3DxvZTA58agu810RWawCiSzzXBeU3MMW9oyJUedvNEvQyNu1f10BSMddR1vaLCYpYa/mGocLSiYDcLbQz8aMn5iyF4xBNMs1P0QEOV7o5gaWGuzSeLue4tt3ro7y4Tgm4G/mopdZgl6q0o6KzJWE3mMksNr3r+a6CbT8g5wZNzT9O7fi/zpaOmnz3BRoqos+tv9zMbdpxsqDBOEewtJLt7cg5wtKKbvldpSzRRCD43VFheCI7yZLppggMVBS/KMAdHODJvOwq2NQSbKKKPLdFWQs7Fqo+mpl01JXYRgq8dnGLhTiFzqmWsUMdpllZdbKlyvSdYxhI9YghOtxR8LgSLWHK62mGGVoxzBE8LNWzqH9CUesQzFy5RQzTc56mhi6fgXEWwpKfE5Z7M05ZgZUPmo6auiv8YKzDYwWBLMErIbKHJvOwIrvEdhOBcQ9JdU1NHQ7CXn2XIDFBKU2WAgcX9UAUzDXWd5alwuyJ41Z9rjKLCL4aCp4WarhPm2rH+SaHUYE001JDZ2ZAzXPjdMpZWvC9wmqIB2lLhQ01D5jO06hghWMndbM7yRJMsoCj1vYbnFQVrW9jak3OlEJ3s/96+p33dEPRV5GxiqaGjIthUU6FFEZyqCa5qJrpBdzSw95IUnOPIrCUUjRZQFrbw5PR0R1qiYx3cb6nrWUMrBmmiBQxVHtTew5ICP/ip6g4hed/Akob/32wvBHsIOX83cI8hGeNeNPCIkPmXe8fPKx84OMSRM1MTdXSwjCZ4S30jVGhvqTRak/OVhgGazHuOCud5onEO1lJr6ecVyaOK6H7zqlBlIaHE0oroCgfvGJIdPcmfLNGLjpz7hZwZQpUbFME0A1cIJa7VNORkgfsMBatbKgwwJM9bSvQXeNOvbIjelg6WWvo5kvbKaJJNHexkKNHL9xRyFlH8Ti2riB5wVPhUk7nGkJnoCe428LR/wRGdYIlmWebCyxou1rCk4g/ShugBDX0V0ZQWkh0dOVsagkM0yV6OoLd5ye+pRlsCr0n+KiQrGuq5yJDzrTAXHtLUMduTDBVKrSm3eHL+6ijxhFDX9Z5gVU/wliHYTMiMFpKLNMEywu80wd3meoFmt6VbRMPenhrOc6DVe4pgXU8DnnHakLOIIrlF4FZPIw6R+zxBP0dyq6OOZ4Q5sLKCcz084ok+VsMMyQhNZmmBgX5xIXOEJTmi7VsGTvMTNdHHhpzdbE8Du2oKxgvBqQKdDDnTFOylCFaxR1syz2iqrOI/FEpNc3C6f11/7+ASS6l2inq2ciTrCCzgyemrCL5SVPjQkdPZUmGy2c9Sw9FtR1sS30RmsKPCS4rkIC/2U0MduwucYolGaPjKEyhzmiPYXagyWbYz8LWBDdzRimAXzxx4z8K9hpzlhLq+NiQ97HuKorMUfK/OVvC2JfiHUPCQI/q7J2gjK+tTDNxkCc4TMssqCs4TGtLVwQihyoAWgj9bosU80XGW6Ac9TJGziaUh5+hnFcHOnlaM1iRn29NaqGENTTTSUHCH2tWTeV0osUhH6psuVLjRUmGWhm6OZEshGeNowABHcJ2Bpy2ZszRcKkRXd2QuKVEeXnbfaEq825FguqfgfE2whlChSRMdron+LATTPQ2Z369t4B9C5gs/ylzv+CMmepIDPclFQl13W0rspPd1JOcbghGOEutqCv5qacURQl3dDKyvyJlqKXGPgcM9FfawJAMVmdcspcYKOZc4GjDYkFlK05olNMHyHn4zFNykyOxt99RkHlfwmiHo60l2EKI+mhreEKp080Tbug08BVPcgoqC5zWt+NLDTZ7oNSF51N1qie7Va3uCCwyZbkINf/NED6jzOsBdZjFN8oqG3wxVunqCSYYKf3EdhJyf9YWGf7tRU2oH3VHgPr1fe5J9hOgHd7xQ0y7qBwXr23aGErP0cm64JVjZwsOGqL+mhNgZmhJLW2oY4UhedsyBgzrCKrq7BmcpNVhR6jBPq64Vgi+kn6XE68pp8J5/+0wRHGOpsKenQn9DZntPzjRLZpDAdD2fnSgkG9tmIXnUwQ6WVighs7Yi2MxQ0N3CqYaCXkJ0oyOztMDJjmSSpcpvlrk0RMMOjmArQ04PRV1DO1FwhCVaUVPpKUM03JK5SxPsIWRu8/CGHi8UHChiqGFDTbSRJWeYUDDcH6vJWUxR4k1FXbMUwV6e4AJFXS8oMqsZKqzvYQ9DDQdZckY4aGsIhtlubbd2r3j4QBMoTamdPZk7O/Bf62lacZwneNjQoGcdVU7zJOd7ghsUHOkosagic6cnWc8+4gg285R6zZP5s1/LUbCKIznTwK36PkdwlOrl4U1LwfdCCa+IrvFkmgw1PCAUXKWo0sURXWcI2muKJlgyFzhynCY4RBOsqCjoI1R5zREco0n2Vt09BQtYSizgKNHfUmUrQ5UOCh51BFcLmY7umhYqXKQomOop8bUnWNNQcIiBcYaC6xzMNOS8JQQfeqKBmmglB+97ok/lfk3ygaHSyZaCRTzRxQo6GzLfa2jWBPepw+UmT7SQEJyiyRkhBLMVOfcoMjcK0eZChfUNzFAUzCsEN5vP/X1uP/n/aoMX+K+nw/Hjr/9xOo7j7Pju61tLcgvJpTWXNbfN5jLpi6VfCOviTktKlFusQixdEKWmEBUKNaIpjZRSSOXSgzaaKLdabrm1/9nZ+/f+vd/vz/v9+Xy+zZ7PRorYoZqyLrCwQdEAixxVOEXNNnjX2nUSRlkqGmWowk8lxR50JPy9Bo6qJXaXwNvREBvnThPEPrewryLhcAnj5WE15Fqi8W7R1sAuEu86S4ENikItFN4xkv9Af4nXSnUVcLiA9xzesFpivRRVeFKtsMRaKBhuSbjOELnAUtlSQUpXgdfB4Z1oSbnFEetbQ0IrAe+Y+pqnDcEJFj6S8LDZzZHwY4e3XONNlARraomNEt2bkvGsosA3ioyHm+6jCMbI59wqt4eeara28IzEmyPgoRaUOEDhTVdEJhmCoTWfC0p8aNkCp0oYqih2iqGi4yXeMkOsn4LdLLnmKfh/YogjNsPebeFGR4m9BJHLzB61XQ3BtpISfS2FugsK9FAtLWX1dCRcrCnUp44CNzuCowUZmxSRgYaE6Za0W2u/E7CVXCiI/UOR8aAm1+OSyE3mOUcwyc1zBBeoX1kiKy0Zfxck1Gsyulti11i83QTBF5Kg3pDQThFMVHiPSlK+0cSedng/VaS8bOZbtsBcTcZAR8JP5KeqQ1OYKAi20njdNNRpgnsU//K+JnaXJaGTomr7aYIphoRn9aeShJWKEq9LcozSF7QleEfDI5LYm5bgVkFkRwVDBCVu0DDIkGupo8TZBq+/pMQURYErJQmPKGKjNDkWOLx7Jd5QizdUweIaKrlP7SwJDhZvONjLkOsBBX9UpGxnydhXkfBLQ8IxgojQbLFnJf81JytSljclYYyEFyx0kVBvKWOFJmONpshGAcsduQY5giVNCV51eOdJYo/pLhbvM0uDHSevNKRcrKZIqnCtJeEsO95RoqcgGK4ocZcho1tTYtcZvH41pNQ7vA0WrhIfOSraIIntIAi+NXWCErdbkvrWwjRLrt0NKUdL6KSOscTOdMSOUtBHwL6OLA0vNSdynaWQEnCpIvKaIrJJEbvHkmuNhn6OjM8VkSGSqn1uYJCGHnq9I3aLhNME3t6GjIkO7xrNFumpyTNX/NrwX7CrIRiqqWijI9JO4d1iieykyfiposQIQ8YjjsjlBh6oHWbwRjgYJQn2NgSnNycmJAk3NiXhx44Sxykihxm8ybUwT1OVKySc7vi3OXVkdBJ4AyXBeksDXG0IhgtYY0lY5ahCD0ehborIk5aUWRJviMA7Xt5kyRjonrXENkm8yYqgs8VzgrJmClK20uMM3jRJ0FiQICQF9hdETlLQWRIb5ki6WDfWRPobvO6a4GP5mcOrNzDFELtTkONLh9dXE8xypEg7z8A9jkhrQ6Fhjlg/QVktJXxt4WXzT/03Q8IaQWSqIuEvloQ2mqC9Jfi7wRul4RX3pSPlzpoVlmCtI2jvKHCFhjcM3sN6lqF6HxnKelLjXWbwrpR4xzuCrTUZx2qq9oAh8p6ixCUGr78g8oyjRAtB5CZFwi80VerVpI0h+IeBxa6Zg6kWvpDHaioYYuEsRbDC3eOmC2JvGYLeioxGknL2UATNJN6hmtj1DlpLvDVmocYbrGCVJKOrg4X6DgddLA203BKMFngdJJFtFd7vJLm6KEpc5yjQrkk7M80SGe34X24nSex1Ra5Omgb71JKyg8SrU3i/kARKwWpH0kOGhKkObyfd0ZGjvyXlAkVZ4xRbYJ2irFMkFY1SwyWxr2oo4zlNiV+7zmaweFpT4kR3kaDAFW6xpSqzJay05FtYR4HmZhc9UxKbbfF2V8RG1MBmSaE+kmC6JnaRXK9gsiXhJHl/U0qM0WTcbyhwkYIvFGwjSbjfwhiJt8ZSQU+Bd5+marPMOkVkD0muxYLIfEuhh60x/J92itguihJSEMySVPQnTewnEm+620rTQEMsOfo4/kP/0ARvWjitlpSX7GxBgcMEsd3EEeYWvdytd+Saawi6aCIj1CkGb6Aj9rwhx16Cf3vAwFy5pyLhVonXzy51FDpdEblbkdJbUcEPDEFzQ8qNmhzzLTmmKWKbFCXeEuRabp6rxbvAtLF442QjQ+wEA9eL1xSR7Q0JXzlSHjJ4exq89yR0laScJ/FW6z4a73pFMEfDiRZvuvijIt86RaSFOl01riV2mD1UEvxGk/Geg5aWwGki1zgKPG9J2U8PEg8qYvMsZeytiTRXBMslCU8JSlxi8EabjwUldlDNLfzTUmCgxWsjqWCOHavYAqsknKFIO0yQ61VL5AVFxk6WhEaCAkdJgt9aSkzXlKNX2jEa79waYuc7gq0N3GDJGCBhoiTXUEPsdknCUE1CK0fwsiaylSF2uiDyO4XX3pFhNd7R4itFGc0k/ElBZwWvq+GC6szVeEoS/MZ+qylwpKNKv9Z469UOjqCjwlusicyTxG6VpNxcQ8IncoR4RhLbR+NdpGGmJWOcIzJGUuKPGpQg8rrG21dOMqQssJQ4RxH5jaUqnZuQ0F4Q+cjxLwPtpZbIAk3QTJHQWBE5S1BokoVtDd6lhqr9UpHSUxMcIYl9pojsb8h4SBOsMQcqvOWC2E8EVehqiJ1hrrAEbQxeK0NGZ0Gkq+guSRgniM23bIHVkqwx4hiHd7smaOyglyIyQuM978j4VS08J/A2G1KeMBRo4fBaSNhKUEZfQewVQ/C1I+MgfbEleEzCUw7mKXI0M3hd1EESVji8x5uQ41nxs1q4RMJCCXs7Iq9acpxn22oSDnQ/sJTxsCbHIYZiLyhY05TY0ZLIOQrGaSJDDN4t8pVaIrsqqFdEegtizc1iTew5Q4ayBDMUsQMkXocaYkc0hZua412siZ1rSXlR460zRJ5SlHGe5j801RLMlJTxtaOM3Q1pvxJ45zUlWFD7rsAbpfEm1JHxG0eh8w2R7QQVzBUw28FhFp5QZzq8t2rx2joqulYTWSuJdTYfWwqMFMcovFmSyJPNyLhE4E10pHzYjOC3huArRa571ZsGajQpQx38SBP5pyZB6lMU3khDnp0MBV51BE9o2E+TY5Ml2E8S7C0o6w1xvCZjf0HkVEHCzFoyNmqC+9wdcqN+Tp7jSDheE9ws8Y5V0NJCn2bk2tqSY4okdrEhx1iDN8cSudwepWmAGXKcJXK65H9to8jYQRH7SBF01ESUJdd0TayVInaWhLkOjlXE5irKGOnI6GSWGCJa482zBI9rCr0jyTVcEuzriC1vcr6mwFGSiqy5zMwxBH/TJHwjSPhL8+01kaaSUuMFKTcLEvaUePcrSmwn8DZrgikWb7CGPxkSjhQwrRk57tctmxLsb9sZvL9LSlyuSLlWkqOjwduo8b6Uv1DkmudIeFF2dHCgxVtk8dpIvHpBxhEOdhKk7OLIUSdJ+cSRY57B+0DgGUUlNfpthTfGkauzxrvTsUUaCVhlKeteTXCoJDCa2NOKhOmC4G1H8JBd4OBZReSRGkqcb/CO1PyLJTLB4j1q8JYaIutEjSLX8YKM+a6phdMsdLFUoV5RTm9JSkuDN8WcIon0NZMNZWh1q8C7SJEwV5HxrmnnTrf3KoJBlmCYI2ilSLlfEvlE4011NNgjgthzEua0oKK7JLE7HZHlEl60BLMVFewg4EWNt0ThrVNEVkkiTwpKXSWJzdRENgvKGq4IhjsiezgSFtsfCUq8qki5S1LRQeYQQ4nemmCkImWMw3tFUoUBZk4NOeZYEp4XRKTGa6wJjrWNHBVJR4m3FCnbuD6aak2WsMTh3SZImGCIPKNgsDpVwnsa70K31lCFJZYcwwSMFcQulGTsZuEaSdBXkPGZhu0FsdUO73RHjq8MPGGIfaGIbVTk6iuI3GFgucHrIQkmWSJdBd7BBu+uOryWAhY7+Lki9rK5wtEQzWwvtbqGhIMFwWRJsElsY4m9IIg9L6lCX0VklaPAYkfkZEGDnOWowlBJjtMUkcGK4Lg6EtoZInMUBVYLgn0UsdmCyCz7gIGHFfk+k1QwTh5We7A9x+IdJ6CvIkEagms0hR50eH9UnTQJ+2oiKyVlLFUE+8gBGu8MQ3CppUHesnjTHN4QB/UGPhCTHLFPHMFrCqa73gqObUJGa03wgbhHkrCfpEpzNLE7JDS25FMKhlhKKWKfCgqstLCPu1zBXy0J2ztwjtixBu8UTRn9LVtkmCN2iyFhtME70JHRQ1KVZXqKI/KNIKYMCYs1GUMEKbM1bKOI9LDXC7zbHS+bt+1MTWS9odA9DtrYtpbImQJ2VHh/lisEwaHqUk1kjKTAKknkBEXkbkdMGwq0dnhzLJF3NJH3JVwrqOB4Sca2hti75nmJN0WzxS6UxDYoEpxpa4htVlRjkYE7DZGzJVU72uC9IyhQL4i8YfGWSYLLNcHXloyz7QhNifmKSE9JgfGmuyLhc403Xm9vqcp6gXe3xuuv8F6VJNxkyTHEkHG2g0aKXL0MsXc1bGfgas2//dCONXiNLCX+5mB7eZIl1kHh7ajwpikyzlUUWOVOsjSQlsS+M0R+pPje/dzBXRZGO0rMtgQrLLG9VSu9n6CMXS3BhwYmSoIBhsjNBmZbgusE9BCPCP5triU4VhNbJfE+swSP27aayE8tuTpYYjtrYjMVGZdp2NpS1s6aBnKSHDsbKuplKbHM4a0wMFd/5/DmGyKrJSUaW4IBrqUhx0vyfzTBBLPIUcnZdrAkNsKR0sWRspumSns6Ch0v/qqIbBYUWKvPU/CFoyrDJGwSNFhbA/MlzKqjrO80hRbpKx0Jewsi/STftwGSlKc1JZyAzx05dhLEdnfQvhZOqiHWWEAHC7+30FuRcZUgaO5gpaIK+xsiHRUsqaPElTV40xQZQ107Q9BZE1nryDVGU9ZSQ47bmhBpLcYpUt7S+xuK/FiT8qKjwXYw5ypS2iuCv7q1gtgjhuBuB8LCFY5cUuCNtsQOFcT+4Ih9JX+k8Ea6v0iCIRZOtCT0Et00JW5UeC85Cg0ScK0k411HcG1zKtre3SeITBRk7WfwDhEvaYLTHP9le0m8By0JDwn4TlLW/aJOvGHxdjYUes+ScZigCkYQdNdEOhkiezgShqkx8ueKjI8lDfK2oNiOFvrZH1hS+tk7NV7nOmLHicGWEgubkXKdwdtZknCLJXaCpkrjZBtLZFsDP9CdxWsSr05Sxl6CMmoFbCOgryX40uDtamB7SVmXW4Ihlgpmq+00tBKUUa83WbjLUNkzDmY7cow1JDygyPGlhgGKYKz4vcV7QBNbJIgM11TUqZaMdwTeSguH6rOaw1JRKzaaGyxVm2EJ/uCIrVWUcZUkcp2grMsEjK+DMwS59jQk3Kd6SEq1d0S6uVmO4Bc1lDXTUcHjluCXEq+1OlBDj1pi9zgiXxnKuE0SqTXwhqbETW6RggMEnGl/q49UT2iCzgJvRwVXS2K/d6+ZkyUl7jawSVLit46EwxVljDZwoSQ20sDBihztHfk2yA8NVZghiXwrYHQdfKAOtzsayjhY9bY0yE2CWEeJ9xfzO423xhL5syS2TFJofO2pboHob0nY4GiAgRrvGQEDa/FWSsoaaYl0syRsEt3kWoH3B01shCXhTUWe9w3Bt44SC9QCh3eShQctwbaK2ApLroGCMlZrYqvlY3qYhM0aXpFkPOuoqJ3Dm6fxXrGwVF9gCWZagjPqznfkuMKQ8DPTQRO8ZqG1hPGKEm9IgpGW4DZDgTNriTxvFiq+Lz+0cKfp4wj6OCK9JSnzNSn9LFU7UhKZZMnYwcJ8s8yRsECScK4j5UOB95HFO0CzhY4xJxuCix0lDlEUeMdS6EZBkTsUkZ4K74dugyTXS7aNgL8aqjDfkCE0ZbwkCXpaWCKhl8P7VD5jxykivSyxyZrYERbe168LYu9ZYh86IkscgVLE7tWPKmJv11CgoyJltMEbrohtVAQfO4ImltiHEroYEs7RxAarVpY8AwXMcMReFOTYWe5iiLRQxJ5Q8DtJ8LQhWOhIeFESPGsILhbNDRljNbHzNRlTFbk2S3L0NOS6V1KFJYKUbSTcIIhM0wQ/s2TM0SRMNcQmSap3jCH4yhJZKSkwyRHpYYgsFeQ4U7xoCB7VVOExhXepo9ABBsYbvGWKXPME3lyH95YioZ0gssQRWWbI+FaSMkXijZXwgiTlYdPdkNLaETxlyDVIwqeaEus0aTcYcg0RVOkpR3CSJqIddK+90JCxzsDVloyrFd5ZAr4TBKfaWa6boEA7C7s6EpYaeFPjveooY72mjIccLHJ9HUwVlDhKkmutJDJBwnp1rvulJZggKDRfbXAkvC/4l3ozQOG9a8lxjx0i7nV4jSXc7vhe3OwIxjgSHjdEhhsif9YkPGlus3iLFDnWOFhtCZbJg0UbQcIaR67JjthoCyMEZRwhiXWyxO5QxI6w5NhT4U1WsJvDO60J34fW9hwzwlKij6ZAW9ne4L0s8C6XeBMEkd/LQy1VucBRot6QMlbivaBhoBgjqGiCJNhsqVp/S2SsG6DIONCR0dXhvWbJ+MRRZJkkuEjgDXJjFQW6SSL7GXK8Z2CZg7cVsbWGoKmEpzQ5elpiy8Ryg7dMkLLUEauzeO86CuwlSOlgYLojZWeJ9xM3S1PWfEfKl5ISLQ0MEKR8YOB2QfCxJBjrKPCN4f9MkaSsqoVXJBmP7EpFZ9UQfOoOFwSzBN4MQ8LsGrymlipcJQhmy0GaQjPqCHaXRwuCZwRbqK2Fg9wlClZqYicrIgMdZfxTQ0c7TBIbrChxmuzoKG8XRaSrIhhiyNFJkrC7oIAWMEOQa5aBekPCRknCo4IKPrYkvCDI8aYmY7WFtprgekcJZ3oLIqssCSMtFbQTJKwXYy3BY5oCh2iKPCpJOE+zRdpYgi6O2KmOAgvVCYaU4ySRek1sgyFhJ403QFHiVEmJHwtybO1gs8Hr5+BETQX3War0qZngYGgtVZtoqd6vFSk/UwdZElYqyjrF4HXUeFspIi9IGKf4j92pKGAdCYMVsbcV3kRF0N+R8LUd5PCsIGWoxDtBkCI0nKofdJQxT+LtZflvuc8Q3CjwWkq8KwUpHzkK/NmSsclCL0nseQdj5FRH5CNHSgtLiW80Of5HU9Hhlsga9bnBq3fEVltKfO5IaSTmGjjc4J0otcP7QsJUSQM8pEj5/wCuUuC2DWz8AAAAAElFTkSuQmCC"); } ================================================ FILE: public/packages/codemirror-3.19/theme/base16-dark.css ================================================ /* Name: Base16 Default Dark Author: Chris Kempson (http://chriskempson.com) CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-chrome-devtools) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ .cm-s-base16-dark.CodeMirror {background: #151515; color: #e0e0e0;} .cm-s-base16-dark div.CodeMirror-selected {background: #202020 !important;} .cm-s-base16-dark .CodeMirror-gutters {background: #151515; border-right: 0px;} .cm-s-base16-dark .CodeMirror-linenumber {color: #505050;} .cm-s-base16-dark .CodeMirror-cursor {border-left: 1px solid #b0b0b0 !important;} .cm-s-base16-dark span.cm-comment {color: #8f5536;} .cm-s-base16-dark span.cm-atom {color: #aa759f;} .cm-s-base16-dark span.cm-number {color: #aa759f;} .cm-s-base16-dark span.cm-property, .cm-s-base16-dark span.cm-attribute {color: #90a959;} .cm-s-base16-dark span.cm-keyword {color: #ac4142;} .cm-s-base16-dark span.cm-string {color: #f4bf75;} .cm-s-base16-dark span.cm-variable {color: #90a959;} .cm-s-base16-dark span.cm-variable-2 {color: #6a9fb5;} .cm-s-base16-dark span.cm-def {color: #d28445;} .cm-s-base16-dark span.cm-bracket {color: #e0e0e0;} .cm-s-base16-dark span.cm-tag {color: #ac4142;} .cm-s-base16-dark span.cm-link {color: #aa759f;} .cm-s-base16-dark span.cm-error {background: #ac4142; color: #b0b0b0;} .cm-s-base16-dark .CodeMirror-activeline-background {background: #2F2F2F !important;} .cm-s-base16-dark .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/base16-light.css ================================================ /* Name: Base16 Default Light Author: Chris Kempson (http://chriskempson.com) CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-chrome-devtools) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ .cm-s-base16-light.CodeMirror {background: #f5f5f5; color: #202020;} .cm-s-base16-light div.CodeMirror-selected {background: #e0e0e0 !important;} .cm-s-base16-light .CodeMirror-gutters {background: #f5f5f5; border-right: 0px;} .cm-s-base16-light .CodeMirror-linenumber {color: #b0b0b0;} .cm-s-base16-light .CodeMirror-cursor {border-left: 1px solid #505050 !important;} .cm-s-base16-light span.cm-comment {color: #8f5536;} .cm-s-base16-light span.cm-atom {color: #aa759f;} .cm-s-base16-light span.cm-number {color: #aa759f;} .cm-s-base16-light span.cm-property, .cm-s-base16-light span.cm-attribute {color: #90a959;} .cm-s-base16-light span.cm-keyword {color: #ac4142;} .cm-s-base16-light span.cm-string {color: #f4bf75;} .cm-s-base16-light span.cm-variable {color: #90a959;} .cm-s-base16-light span.cm-variable-2 {color: #6a9fb5;} .cm-s-base16-light span.cm-def {color: #d28445;} .cm-s-base16-light span.cm-bracket {color: #202020;} .cm-s-base16-light span.cm-tag {color: #ac4142;} .cm-s-base16-light span.cm-link {color: #aa759f;} .cm-s-base16-light span.cm-error {background: #ac4142; color: #505050;} .cm-s-base16-light .CodeMirror-activeline-background {background: #DDDCDC !important;} .cm-s-base16-light .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/blackboard.css ================================================ /* 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-builtin { color: #8DA6CE; } .cm-s-blackboard .cm-tag { color: #8DA6CE; } .cm-s-blackboard .cm-attribute { color: #8DA6CE; } .cm-s-blackboard .cm-header { color: #FF6400; } .cm-s-blackboard .cm-hr { color: #AEAEAE; } .cm-s-blackboard .cm-link { color: #8DA6CE; } .cm-s-blackboard .cm-error { background: #9D1E15; color: #F8F8F8; } .cm-s-blackboard .CodeMirror-activeline-background {background: #3C3636 !important;} .cm-s-blackboard .CodeMirror-matchingbracket {outline:1px solid grey;color:white !important} ================================================ FILE: public/packages/codemirror-3.19/theme/cobalt.css ================================================ .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-bracket { color: #d8d8d8; } .cm-s-cobalt span.cm-builtin, .cm-s-cobalt span.cm-special { color: #ff9e59; } .cm-s-cobalt span.cm-link { color: #845dc4; } .cm-s-cobalt span.cm-error { color: #9d1e15; } .cm-s-cobalt .CodeMirror-activeline-background {background: #002D57 !important;} .cm-s-cobalt .CodeMirror-matchingbracket {outline:1px solid grey;color:white !important} ================================================ FILE: public/packages/codemirror-3.19/theme/eclipse.css ================================================ .cm-s-eclipse span.cm-meta {color: #FF1717;} .cm-s-eclipse span.cm-keyword { line-height: 1em; font-weight: bold; color: #7F0055; } .cm-s-eclipse span.cm-atom {color: #219;} .cm-s-eclipse span.cm-number {color: #164;} .cm-s-eclipse span.cm-def {color: #00f;} .cm-s-eclipse span.cm-variable {color: black;} .cm-s-eclipse span.cm-variable-2 {color: #0000C0;} .cm-s-eclipse span.cm-variable-3 {color: #0000C0;} .cm-s-eclipse span.cm-property {color: black;} .cm-s-eclipse span.cm-operator {color: black;} .cm-s-eclipse span.cm-comment {color: #3F7F5F;} .cm-s-eclipse span.cm-string {color: #2A00FF;} .cm-s-eclipse span.cm-string-2 {color: #f50;} .cm-s-eclipse span.cm-qualifier {color: #555;} .cm-s-eclipse span.cm-builtin {color: #30a;} .cm-s-eclipse span.cm-bracket {color: #cc7;} .cm-s-eclipse span.cm-tag {color: #170;} .cm-s-eclipse span.cm-attribute {color: #00c;} .cm-s-eclipse span.cm-link {color: #219;} .cm-s-eclipse span.cm-error {color: #f00;} .cm-s-eclipse .CodeMirror-activeline-background {background: #e8f2ff !important;} .cm-s-eclipse .CodeMirror-matchingbracket {outline:1px solid grey; color:black !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/elegant.css ================================================ .cm-s-elegant span.cm-number, .cm-s-elegant span.cm-string, .cm-s-elegant span.cm-atom {color: #762;} .cm-s-elegant span.cm-comment {color: #262; font-style: italic; line-height: 1em;} .cm-s-elegant span.cm-meta {color: #555; font-style: italic; line-height: 1em;} .cm-s-elegant span.cm-variable {color: black;} .cm-s-elegant span.cm-variable-2 {color: #b11;} .cm-s-elegant span.cm-qualifier {color: #555;} .cm-s-elegant span.cm-keyword {color: #730;} .cm-s-elegant span.cm-builtin {color: #30a;} .cm-s-elegant span.cm-link {color: #762;} .cm-s-elegant span.cm-error {background-color: #fdd;} .cm-s-elegant .CodeMirror-activeline-background {background: #e8f2ff !important;} .cm-s-elegant .CodeMirror-matchingbracket {outline:1px solid grey; color:black !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/erlang-dark.css ================================================ .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: #f133f1; } .cm-s-erlang-dark span.cm-attribute { color: #ff80e1; } .cm-s-erlang-dark span.cm-bracket { color: #ff9d00; } .cm-s-erlang-dark span.cm-builtin { color: #eaa; } .cm-s-erlang-dark span.cm-comment { color: #77f; } .cm-s-erlang-dark span.cm-def { color: #e7a; } .cm-s-erlang-dark span.cm-keyword { color: #ffee80; } .cm-s-erlang-dark span.cm-meta { color: #50fefe; } .cm-s-erlang-dark span.cm-number { color: #ffd0d0; } .cm-s-erlang-dark span.cm-operator { color: #d55; } .cm-s-erlang-dark span.cm-property { color: #ccc; } .cm-s-erlang-dark span.cm-qualifier { color: #ccc; } .cm-s-erlang-dark span.cm-quote { color: #ccc; } .cm-s-erlang-dark span.cm-special { color: #ffbbbb; } .cm-s-erlang-dark span.cm-string { color: #3ad900; } .cm-s-erlang-dark span.cm-string-2 { color: #ccc; } .cm-s-erlang-dark span.cm-tag { color: #9effff; } .cm-s-erlang-dark span.cm-variable { color: #50fe50; } .cm-s-erlang-dark span.cm-variable-2 { color: #e0e; } .cm-s-erlang-dark span.cm-variable-3 { color: #ccc; } .cm-s-erlang-dark span.cm-error { color: #9d1e15; } .cm-s-erlang-dark .CodeMirror-activeline-background {background: #013461 !important;} .cm-s-erlang-dark .CodeMirror-matchingbracket {outline:1px solid grey; color:white !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/lesser-dark.css ================================================ /* http://lesscss.org/ dark theme Ported to CodeMirror by Peter Kroon */ .cm-s-lesser-dark { line-height: 1.3em; } .cm-s-lesser-dark { 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*/ .cm-s-lesser-dark.CodeMirror span.CodeMirror-matchingbracket { color: #7EFC7E; }/*65FC65*/ .cm-s-lesser-dark .CodeMirror-gutters { background: #262626; border-right:1px solid #aaa; } .cm-s-lesser-dark .CodeMirror-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-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;} .cm-s-lesser-dark span.cm-error { color: #9d1e15; } .cm-s-lesser-dark .CodeMirror-activeline-background {background: #3C3A3A !important;} .cm-s-lesser-dark .CodeMirror-matchingbracket {outline:1px solid grey; color:white !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/mbo.css ================================================ /* Based on mbonaci's Brackets mbo theme */ .cm-s-mbo.CodeMirror {background: #2c2c2c; color: #ffffe9;} .cm-s-mbo div.CodeMirror-selected {background: #716C62 !important;} .cm-s-mbo .CodeMirror-gutters {background: #4e4e4e; border-right: 0px;} .cm-s-mbo .CodeMirror-linenumber {color: #dadada;} .cm-s-mbo .CodeMirror-cursor {border-left: 1px solid #ffffec !important;} .cm-s-mbo span.cm-comment {color: #95958a;} .cm-s-mbo span.cm-atom {color: #00a8c6;} .cm-s-mbo span.cm-number {color: #00a8c6;} .cm-s-mbo span.cm-property, .cm-s-mbo span.cm-attribute {color: #9ddfe9;} .cm-s-mbo span.cm-keyword {color: #ffb928;} .cm-s-mbo span.cm-string {color: #ffcf6c;} .cm-s-mbo span.cm-variable {color: #ffffec;} .cm-s-mbo span.cm-variable-2 {color: #00a8c6;} .cm-s-mbo span.cm-def {color: #ffffec;} .cm-s-mbo span.cm-bracket {color: #fffffc; font-weight: bold;} .cm-s-mbo span.cm-tag {color: #9ddfe9;} .cm-s-mbo span.cm-link {color: #f54b07;} .cm-s-mbo span.cm-error {background: #636363; color: #ffffec;} .cm-s-mbo .CodeMirror-activeline-background {background: #494b41 !important;} .cm-s-mbo .CodeMirror-matchingbracket { text-decoration: underline; color: #f5e107 !important; } div.CodeMirror span.CodeMirror-searching { background-color: none; background: none; box-shadow: 0 0 0 1px #ffffec; } ================================================ FILE: public/packages/codemirror-3.19/theme/midnight.css ================================================ /* Based on the theme at http://bonsaiden.github.com/JavaScript-Garden */ /**/ .cm-s-midnight span.CodeMirror-matchhighlight { background: #494949 } .cm-s-midnight.CodeMirror-focused span.CodeMirror-matchhighlight { background: #314D67 !important; } /**/ .cm-s-midnight .CodeMirror-activeline-background {background: #253540 !important;} .cm-s-midnight.CodeMirror { background: #0F192A; color: #D1EDFF; } .cm-s-midnight.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;} .cm-s-midnight div.CodeMirror-selected {background: #314D67 !important;} .cm-s-midnight .CodeMirror-gutters {background: #0F192A; border-right: 1px solid;} .cm-s-midnight .CodeMirror-linenumber {color: #D0D0D0;} .cm-s-midnight .CodeMirror-cursor { border-left: 1px solid #F8F8F0 !important; } .cm-s-midnight span.cm-comment {color: #428BDD;} .cm-s-midnight span.cm-atom {color: #AE81FF;} .cm-s-midnight span.cm-number {color: #D1EDFF;} .cm-s-midnight span.cm-property, .cm-s-midnight span.cm-attribute {color: #A6E22E;} .cm-s-midnight span.cm-keyword {color: #E83737;} .cm-s-midnight span.cm-string {color: #1DC116;} .cm-s-midnight span.cm-variable {color: #FFAA3E;} .cm-s-midnight span.cm-variable-2 {color: #FFAA3E;} .cm-s-midnight span.cm-def {color: #4DD;} .cm-s-midnight span.cm-bracket {color: #D1EDFF;} .cm-s-midnight span.cm-tag {color: #449;} .cm-s-midnight span.cm-link {color: #AE81FF;} .cm-s-midnight span.cm-error {background: #F92672; color: #F8F8F0;} .cm-s-midnight .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: public/packages/codemirror-3.19/theme/monokai.css ================================================ /* Based on Sublime Text's Monokai theme */ .cm-s-monokai.CodeMirror {background: #272822; color: #f8f8f2;} .cm-s-monokai div.CodeMirror-selected {background: #49483E !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-bracket {color: #f8f8f2;} .cm-s-monokai span.cm-tag {color: #f92672;} .cm-s-monokai span.cm-link {color: #ae81ff;} .cm-s-monokai span.cm-error {background: #f92672; color: #f8f8f0;} .cm-s-monokai .CodeMirror-activeline-background {background: #373831 !important;} .cm-s-monokai .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: public/packages/codemirror-3.19/theme/neat.css ================================================ .cm-s-neat span.cm-comment { color: #a86; } .cm-s-neat span.cm-keyword { line-height: 1em; font-weight: bold; color: blue; } .cm-s-neat span.cm-string { color: #a22; } .cm-s-neat span.cm-builtin { line-height: 1em; font-weight: bold; color: #077; } .cm-s-neat span.cm-special { line-height: 1em; font-weight: bold; color: #0aa; } .cm-s-neat span.cm-variable { color: black; } .cm-s-neat span.cm-number, .cm-s-neat span.cm-atom { color: #3a3; } .cm-s-neat span.cm-meta {color: #555;} .cm-s-neat span.cm-link { color: #3a3; } .cm-s-neat .CodeMirror-activeline-background {background: #e8f2ff !important;} .cm-s-neat .CodeMirror-matchingbracket {outline:1px solid grey; color:black !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/night.css ================================================ /* Loosely based on the Midnight Textmate theme */ .cm-s-night.CodeMirror { background: #0a001f; color: #f8f8f8; } .cm-s-night div.CodeMirror-selected { background: #447 !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-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; } .cm-s-night span.cm-error { color: #9d1e15; } .cm-s-night .CodeMirror-activeline-background {background: #1C005A !important;} .cm-s-night .CodeMirror-matchingbracket {outline:1px solid grey; color:white !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/paraiso-dark.css ================================================ /* Name: Paraíso (Dark) Author: Jan T. Sott Color scheme by Jan T. Sott (https://github.com/idleberg/Paraiso-CodeMirror) Inspired by the art of Rubens LP (http://www.rubenslp.com.br) */ .cm-s-paraiso-dark.CodeMirror {background: #2f1e2e; color: #b9b6b0;} .cm-s-paraiso-dark div.CodeMirror-selected {background: #41323f !important;} .cm-s-paraiso-dark .CodeMirror-gutters {background: #2f1e2e; border-right: 0px;} .cm-s-paraiso-dark .CodeMirror-linenumber {color: #776e71;} .cm-s-paraiso-dark .CodeMirror-cursor {border-left: 1px solid #8d8687 !important;} .cm-s-paraiso-dark span.cm-comment {color: #e96ba8;} .cm-s-paraiso-dark span.cm-atom {color: #815ba4;} .cm-s-paraiso-dark span.cm-number {color: #815ba4;} .cm-s-paraiso-dark span.cm-property, .cm-s-paraiso-dark span.cm-attribute {color: #48b685;} .cm-s-paraiso-dark span.cm-keyword {color: #ef6155;} .cm-s-paraiso-dark span.cm-string {color: #fec418;} .cm-s-paraiso-dark span.cm-variable {color: #48b685;} .cm-s-paraiso-dark span.cm-variable-2 {color: #06b6ef;} .cm-s-paraiso-dark span.cm-def {color: #f99b15;} .cm-s-paraiso-dark span.cm-bracket {color: #b9b6b0;} .cm-s-paraiso-dark span.cm-tag {color: #ef6155;} .cm-s-paraiso-dark span.cm-link {color: #815ba4;} .cm-s-paraiso-dark span.cm-error {background: #ef6155; color: #8d8687;} .cm-s-paraiso-dark .CodeMirror-activeline-background {background: #4D344A !important;} .cm-s-paraiso-dark .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/paraiso-light.css ================================================ /* Name: Paraíso (Light) Author: Jan T. Sott Color scheme by Jan T. Sott (https://github.com/idleberg/Paraiso-CodeMirror) Inspired by the art of Rubens LP (http://www.rubenslp.com.br) */ .cm-s-paraiso-light.CodeMirror {background: #e7e9db; color: #41323f;} .cm-s-paraiso-light div.CodeMirror-selected {background: #b9b6b0 !important;} .cm-s-paraiso-light .CodeMirror-gutters {background: #e7e9db; border-right: 0px;} .cm-s-paraiso-light .CodeMirror-linenumber {color: #8d8687;} .cm-s-paraiso-light .CodeMirror-cursor {border-left: 1px solid #776e71 !important;} .cm-s-paraiso-light span.cm-comment {color: #e96ba8;} .cm-s-paraiso-light span.cm-atom {color: #815ba4;} .cm-s-paraiso-light span.cm-number {color: #815ba4;} .cm-s-paraiso-light span.cm-property, .cm-s-paraiso-light span.cm-attribute {color: #48b685;} .cm-s-paraiso-light span.cm-keyword {color: #ef6155;} .cm-s-paraiso-light span.cm-string {color: #fec418;} .cm-s-paraiso-light span.cm-variable {color: #48b685;} .cm-s-paraiso-light span.cm-variable-2 {color: #06b6ef;} .cm-s-paraiso-light span.cm-def {color: #f99b15;} .cm-s-paraiso-light span.cm-bracket {color: #41323f;} .cm-s-paraiso-light span.cm-tag {color: #ef6155;} .cm-s-paraiso-light span.cm-link {color: #815ba4;} .cm-s-paraiso-light span.cm-error {background: #ef6155; color: #776e71;} .cm-s-paraiso-light .CodeMirror-activeline-background {background: #CFD1C4 !important;} .cm-s-paraiso-light .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/rubyblue.css ================================================ .cm-s-rubyblue { font-family: 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-bracket { color: #F0F; } .cm-s-rubyblue span.cm-link { color: #F4C20B; } .cm-s-rubyblue span.CodeMirror-matchingbracket { color:#F0F !important; } .cm-s-rubyblue span.cm-builtin, .cm-s-rubyblue span.cm-special { color: #FF9D00; } .cm-s-rubyblue span.cm-error { color: #AF2018; } .cm-s-rubyblue .CodeMirror-activeline-background {background: #173047 !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/solarized.css ================================================ /* 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-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-error, .cm-s-solarized .cm-invalidchar { color: #586e75; border-bottom: 1px dotted #dc322f; } .cm-s-solarized.cm-s-dark .CodeMirror-selected { background: #073642; } .cm-s-solarized.cm-s-light .CodeMirror-selected { background: #eee8d5; } /* Editor styling */ /* Little shadow on the view-port of the buffer view */ .cm-s-solarized.CodeMirror { -moz-box-shadow: inset 7px 0 12px -6px #000; -webkit-box-shadow: inset 7px 0 12px -6px #000; box-shadow: inset 7px 0 12px -6px #000; } /* 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.cm-s-dark .CodeMirror-activeline-background { background: rgba(255, 255, 255, 0.10); } .cm-s-solarized.cm-s-light .CodeMirror-activeline-background { background: rgba(0, 0, 0, 0.10); } /* 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"); } ================================================ FILE: public/packages/codemirror-3.19/theme/the-matrix.css ================================================ .cm-s-the-matrix.CodeMirror { background: #000000; color: #00FF00; } .cm-s-the-matrix span.CodeMirror-selected { background: #a8f !important; } .cm-s-the-matrix .CodeMirror-gutters { background: #060; border-right: 2px solid #00FF00; } .cm-s-the-matrix .CodeMirror-linenumber { color: #FFFFFF; } .cm-s-the-matrix .CodeMirror-cursor { border-left: 1px solid #00FF00 !important; } .cm-s-the-matrix span.cm-keyword {color: #008803; font-weight: bold;} .cm-s-the-matrix span.cm-atom {color: #3FF;} .cm-s-the-matrix span.cm-number {color: #FFB94F;} .cm-s-the-matrix span.cm-def {color: #99C;} .cm-s-the-matrix span.cm-variable {color: #F6C;} .cm-s-the-matrix span.cm-variable-2 {color: #C6F;} .cm-s-the-matrix span.cm-variable-3 {color: #96F;} .cm-s-the-matrix span.cm-property {color: #62FFA0;} .cm-s-the-matrix span.cm-operator {color: #999} .cm-s-the-matrix span.cm-comment {color: #CCCCCC;} .cm-s-the-matrix span.cm-string {color: #39C;} .cm-s-the-matrix span.cm-meta {color: #C9F;} .cm-s-the-matrix span.cm-qualifier {color: #FFF700;} .cm-s-the-matrix span.cm-builtin {color: #30a;} .cm-s-the-matrix span.cm-bracket {color: #cc7;} .cm-s-the-matrix span.cm-tag {color: #FFBD40;} .cm-s-the-matrix span.cm-attribute {color: #FFF700;} .cm-s-the-matrix span.cm-error {color: #FF0000;} .cm-s-the-matrix .CodeMirror-activeline-background {background: #040;} ================================================ FILE: public/packages/codemirror-3.19/theme/tomorrow-night-eighties.css ================================================ /* Name: Tomorrow Night - Eighties Author: Chris Kempson CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ .cm-s-tomorrow-night-eighties.CodeMirror {background: #000000; color: #CCCCCC;} .cm-s-tomorrow-night-eighties div.CodeMirror-selected {background: #2D2D2D !important;} .cm-s-tomorrow-night-eighties .CodeMirror-gutters {background: #000000; border-right: 0px;} .cm-s-tomorrow-night-eighties .CodeMirror-linenumber {color: #515151;} .cm-s-tomorrow-night-eighties .CodeMirror-cursor {border-left: 1px solid #6A6A6A !important;} .cm-s-tomorrow-night-eighties span.cm-comment {color: #d27b53;} .cm-s-tomorrow-night-eighties span.cm-atom {color: #a16a94;} .cm-s-tomorrow-night-eighties span.cm-number {color: #a16a94;} .cm-s-tomorrow-night-eighties span.cm-property, .cm-s-tomorrow-night-eighties span.cm-attribute {color: #99cc99;} .cm-s-tomorrow-night-eighties span.cm-keyword {color: #f2777a;} .cm-s-tomorrow-night-eighties span.cm-string {color: #ffcc66;} .cm-s-tomorrow-night-eighties span.cm-variable {color: #99cc99;} .cm-s-tomorrow-night-eighties span.cm-variable-2 {color: #6699cc;} .cm-s-tomorrow-night-eighties span.cm-def {color: #f99157;} .cm-s-tomorrow-night-eighties span.cm-bracket {color: #CCCCCC;} .cm-s-tomorrow-night-eighties span.cm-tag {color: #f2777a;} .cm-s-tomorrow-night-eighties span.cm-link {color: #a16a94;} .cm-s-tomorrow-night-eighties span.cm-error {background: #f2777a; color: #6A6A6A;} .cm-s-tomorrow-night-eighties .CodeMirror-activeline-background {background: #343600 !important;} .cm-s-tomorrow-night-eighties .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/twilight.css ================================================ .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-builtin { color: #cda869; } /*?*/ .cm-s-twilight .cm-tag { color: #997643; } /**/ .cm-s-twilight .cm-attribute { color: #d6bb6d; } /*?*/ .cm-s-twilight .cm-header { color: #FF6400; } .cm-s-twilight .cm-hr { color: #AEAEAE; } .cm-s-twilight .cm-link { color:#ad9361; font-style:italic; text-decoration:none; } /**/ .cm-s-twilight .cm-error { border-bottom: 1px solid red; } .cm-s-twilight .CodeMirror-activeline-background {background: #27282E !important;} .cm-s-twilight .CodeMirror-matchingbracket {outline:1px solid grey; color:white !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/vibrant-ink.css ================================================ /* Taken from the popular Visual Studio Vibrant Ink Schema */ .cm-s-vibrant-ink.CodeMirror { background: black; color: white; } .cm-s-vibrant-ink .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-vibrant span.cm-tag { color: #FFC66D } .cm-s-vibrant-ink span.cm-variable-3, .cm-s-vibrant 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-builtin { color: #8DA6CE; } .cm-s-vibrant-ink .cm-tag { color: #8DA6CE; } .cm-s-vibrant-ink .cm-attribute { color: #8DA6CE; } .cm-s-vibrant-ink .cm-header { color: #FF6400; } .cm-s-vibrant-ink .cm-hr { color: #AEAEAE; } .cm-s-vibrant-ink .cm-link { color: blue; } .cm-s-vibrant-ink .cm-error { border-bottom: 1px solid red; } .cm-s-vibrant-ink .CodeMirror-activeline-background {background: #27282E !important;} .cm-s-vibrant-ink .CodeMirror-matchingbracket {outline:1px solid grey; color:white !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/xq-dark.css ================================================ /* Copyright (C) 2011 by MarkLogic Corporation Author: Mike Brevoort Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ .cm-s-xq-dark.CodeMirror { background: #0a001f; color: #f8f8f8; } .cm-s-xq-dark .CodeMirror-selected { background: #27007A !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-qualifier {color: #FFF700;} .cm-s-xq-dark span.cm-builtin {color: #30a;} .cm-s-xq-dark span.cm-bracket {color: #cc7;} .cm-s-xq-dark span.cm-tag {color: #FFBD40;} .cm-s-xq-dark span.cm-attribute {color: #FFF700;} .cm-s-xq-dark span.cm-error {color: #f00;} .cm-s-xq-dark .CodeMirror-activeline-background {background: #27282E !important;} .cm-s-xq-dark .CodeMirror-matchingbracket {outline:1px solid grey; color:white !important;} ================================================ FILE: public/packages/codemirror-3.19/theme/xq-light.css ================================================ /* Copyright (C) 2011 by MarkLogic Corporation Author: Mike Brevoort Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ .cm-s-xq-light span.cm-keyword {line-height: 1em; font-weight: bold; color: #5A5CAD; } .cm-s-xq-light span.cm-atom {color: #6C8CD5;} .cm-s-xq-light span.cm-number {color: #164;} .cm-s-xq-light span.cm-def {text-decoration:underline;} .cm-s-xq-light span.cm-variable {color: black; } .cm-s-xq-light span.cm-variable-2 {color:black;} .cm-s-xq-light span.cm-variable-3 {color: black; } .cm-s-xq-light span.cm-property {} .cm-s-xq-light span.cm-operator {} .cm-s-xq-light span.cm-comment {color: #0080FF; font-style: italic;} .cm-s-xq-light span.cm-string {color: red;} .cm-s-xq-light span.cm-meta {color: yellow;} .cm-s-xq-light span.cm-qualifier {color: grey} .cm-s-xq-light span.cm-builtin {color: #7EA656;} .cm-s-xq-light span.cm-bracket {color: #cc7;} .cm-s-xq-light span.cm-tag {color: #3F7F7F;} .cm-s-xq-light span.cm-attribute {color: #7F007F;} .cm-s-xq-light span.cm-error {color: #f00;} .cm-s-xq-light .CodeMirror-activeline-background {background: #e8f2ff !important;} .cm-s-xq-light .CodeMirror-matchingbracket {outline:1px solid grey;color:black !important;background:yellow;} ================================================ FILE: public/packages/google-code-prettify/lang-apollo.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["com",/^#[^\n\r]*/,null,"#"],["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r \u00a0"],["str",/^"(?:[^"\\]|\\[\S\s])*(?:"|$)/,null,'"']],[["kwd",/^(?:ADS|AD|AUG|BZF|BZMF|CAE|CAF|CA|CCS|COM|CS|DAS|DCA|DCOM|DCS|DDOUBL|DIM|DOUBLE|DTCB|DTCF|DV|DXCH|EDRUPT|EXTEND|INCR|INDEX|NDX|INHINT|LXCH|MASK|MSK|MP|MSU|NOOP|OVSK|QXCH|RAND|READ|RELINT|RESUME|RETURN|ROR|RXOR|SQUARE|SU|TCR|TCAA|OVSK|TCF|TC|TS|WAND|WOR|WRITE|XCH|XLQ|XXALQ|ZL|ZQ|ADD|ADZ|SUB|SUZ|MPY|MPR|MPZ|DVP|COM|ABS|CLA|CLZ|LDQ|STO|STQ|ALS|LLS|LRS|TRA|TSQ|TMI|TOV|AXT|TIX|DLY|INP|OUT)\s/, null],["typ",/^(?:-?GENADR|=MINUS|2BCADR|VN|BOF|MM|-?2CADR|-?[1-6]DNADR|ADRES|BBCON|[ES]?BANK=?|BLOCK|BNKSUM|E?CADR|COUNT\*?|2?DEC\*?|-?DNCHAN|-?DNPTR|EQUALS|ERASE|MEMORY|2?OCT|REMADR|SETLOC|SUBRO|ORG|BSS|BES|SYN|EQU|DEFINE|END)\s/,null],["lit",/^'(?:-*(?:\w|\\[!-~])(?:[\w-]*|\\[!-~])[!=?]?)?/],["pln",/^-*(?:[!-z]|\\[!-~])(?:[\w-]*|\\[!-~])[!=?]?/],["pun",/^[^\w\t\n\r "'-);\\\xa0]+/]]),["apollo","agc","aea"]); ================================================ FILE: public/packages/google-code-prettify/lang-basic.js ================================================ var a=null; PR.registerLangHandler(PR.createSimpleLexer([["str",/^"(?:[^\n\r"\\]|\\.)*(?:"|$)/,a,'"'],["pln",/^\s+/,a," \r\n\t\u00a0"]],[["com",/^REM[^\n\r]*/,a],["kwd",/^\b(?:AND|CLOSE|CLR|CMD|CONT|DATA|DEF ?FN|DIM|END|FOR|GET|GOSUB|GOTO|IF|INPUT|LET|LIST|LOAD|NEW|NEXT|NOT|ON|OPEN|OR|POKE|PRINT|READ|RESTORE|RETURN|RUN|SAVE|STEP|STOP|SYS|THEN|TO|VERIFY|WAIT)\b/,a],["pln",/^[a-z][^\W_]?(?:\$|%)?/i,a],["lit",/^(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?/i,a,"0123456789"],["pun", /^.[^\s\w"$%.]*/,a]]),["basic","cbm"]); ================================================ FILE: public/packages/google-code-prettify/lang-clj.js ================================================ /* Copyright (C) 2011 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var a=null; PR.registerLangHandler(PR.createSimpleLexer([["opn",/^[([{]+/,a,"([{"],["clo",/^[)\]}]+/,a,")]}"],["com",/^;[^\n\r]*/,a,";"],["pln",/^[\t\n\r \xa0]+/,a,"\t\n\r \u00a0"],["str",/^"(?:[^"\\]|\\[\S\s])*(?:"|$)/,a,'"']],[["kwd",/^(?:def|if|do|let|quote|var|fn|loop|recur|throw|try|monitor-enter|monitor-exit|defmacro|defn|defn-|macroexpand|macroexpand-1|for|doseq|dosync|dotimes|and|or|when|not|assert|doto|proxy|defstruct|first|rest|cons|defprotocol|deftype|defrecord|reify|defmulti|defmethod|meta|with-meta|ns|in-ns|create-ns|import|intern|refer|alias|namespace|resolve|ref|deref|refset|new|set!|memfn|to-array|into-array|aset|gen-class|reduce|map|filter|find|nil?|empty?|hash-map|hash-set|vec|vector|seq|flatten|reverse|assoc|dissoc|list|list?|disj|get|union|difference|intersection|extend|extend-type|extend-protocol|prn)\b/,a], ["typ",/^:[\dA-Za-z-]+/]]),["clj"]); ================================================ FILE: public/packages/google-code-prettify/lang-css.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\f\r ]+/,null," \t\r\n\u000c"]],[["str",/^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/,null],["str",/^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/,null],["lang-css-str",/^url\(([^"')]+)\)/i],["kwd",/^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//], ["com",/^(?:<\!--|--\>)/],["lit",/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],["lit",/^#[\da-f]{3,6}\b/i],["pln",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],["pun",/^[^\s\w"']+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[["kwd",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[["str",/^[^"')]+/]]),["css-str"]); ================================================ FILE: public/packages/google-code-prettify/lang-dart.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r \u00a0"]],[["com",/^#!.*/],["kwd",/^\b(?:import|library|part of|part|as|show|hide)\b/i],["com",/^\/\/.*/],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],["kwd",/^\b(?:class|interface)\b/i],["kwd",/^\b(?:assert|break|case|catch|continue|default|do|else|finally|for|if|in|is|new|return|super|switch|this|throw|try|while)\b/i],["kwd",/^\b(?:abstract|const|extends|factory|final|get|implements|native|operator|set|static|typedef|var)\b/i], ["typ",/^\b(?:bool|double|dynamic|int|num|object|string|void)\b/i],["kwd",/^\b(?:false|null|true)\b/i],["str",/^r?'''[\S\s]*?[^\\]'''/],["str",/^r?"""[\S\s]*?[^\\]"""/],["str",/^r?'('|[^\n\f\r]*?[^\\]')/],["str",/^r?"("|[^\n\f\r]*?[^\\]")/],["pln",/^[$_a-z]\w*/i],["pun",/^[!%&*+/:<-?^|~-]/],["lit",/^\b0x[\da-f]+/i],["lit",/^\b\d+(?:\.\d*)?(?:e[+-]?\d+)?/i],["lit",/^\b\.\d+(?:e[+-]?\d+)?/i],["pun",/^[(),.;[\]{}]/]]), ["dart"]); ================================================ FILE: public/packages/google-code-prettify/lang-erlang.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t-\r ]+/,null,"\t\n\u000b\u000c\r "],["str",/^"(?:[^\n\f\r"\\]|\\[\S\s])*(?:"|$)/,null,'"'],["lit",/^[a-z]\w*/],["lit",/^'(?:[^\n\f\r'\\]|\\[^&])+'?/,null,"'"],["lit",/^\?[^\t\n ({]+/,null,"?"],["lit",/^(?:0o[0-7]+|0x[\da-f]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)/i,null,"0123456789"]],[["com",/^%[^\n]*/],["kwd",/^(?:module|attributes|do|let|in|letrec|apply|call|primop|case|of|end|when|fun|try|catch|receive|after|char|integer|float,atom,string,var)\b/], ["kwd",/^-[_a-z]+/],["typ",/^[A-Z_]\w*/],["pun",/^[,.;]/]]),["erlang","erl"]); ================================================ FILE: public/packages/google-code-prettify/lang-go.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r \u00a0"],["pln",/^(?:"(?:[^"\\]|\\[\S\s])*(?:"|$)|'(?:[^'\\]|\\[\S\s])+(?:'|$)|`[^`]*(?:`|$))/,null,"\"'"]],[["com",/^(?:\/\/[^\n\r]*|\/\*[\S\s]*?\*\/)/],["pln",/^(?:[^"'/`]|\/(?![*/]))+/]]),["go"]); ================================================ FILE: public/packages/google-code-prettify/lang-hs.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t-\r ]+/,null,"\t\n\u000b\u000c\r "],["str",/^"(?:[^\n\f\r"\\]|\\[\S\s])*(?:"|$)/,null,'"'],["str",/^'(?:[^\n\f\r'\\]|\\[^&])'?/,null,"'"],["lit",/^(?:0o[0-7]+|0x[\da-f]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)/i,null,"0123456789"]],[["com",/^(?:--+[^\n\f\r]*|{-(?:[^-]|-+[^}-])*-})/],["kwd",/^(?:case|class|data|default|deriving|do|else|if|import|in|infix|infixl|infixr|instance|let|module|newtype|of|then|type|where|_)(?=[^\d'A-Za-z]|$)/, null],["pln",/^(?:[A-Z][\w']*\.)*[A-Za-z][\w']*/],["pun",/^[^\d\t-\r "'A-Za-z]+/]]),["hs"]); ================================================ FILE: public/packages/google-code-prettify/lang-lisp.js ================================================ var a=null; PR.registerLangHandler(PR.createSimpleLexer([["opn",/^\(+/,a,"("],["clo",/^\)+/,a,")"],["com",/^;[^\n\r]*/,a,";"],["pln",/^[\t\n\r \xa0]+/,a,"\t\n\r \u00a0"],["str",/^"(?:[^"\\]|\\[\S\s])*(?:"|$)/,a,'"']],[["kwd",/^(?:block|c[ad]+r|catch|con[ds]|def(?:ine|un)|do|eq|eql|equal|equalp|eval-when|flet|format|go|if|labels|lambda|let|load-time-value|locally|macrolet|multiple-value-call|nil|progn|progv|quote|require|return-from|setq|symbol-macrolet|t|tagbody|the|throw|unwind)\b/,a], ["lit",/^[+-]?(?:[#0]x[\da-f]+|\d+\/\d+|(?:\.\d+|\d+(?:\.\d*)?)(?:[de][+-]?\d+)?)/i],["lit",/^'(?:-*(?:\w|\\[!-~])(?:[\w-]*|\\[!-~])[!=?]?)?/],["pln",/^-*(?:[_a-z]|\\[!-~])(?:[\w-]*|\\[!-~])[!=?]?/i],["pun",/^[^\w\t\n\r "'-);\\\xa0]+/]]),["cl","el","lisp","lsp","scm","ss","rkt"]); ================================================ FILE: public/packages/google-code-prettify/lang-llvm.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r \u00a0"],["str",/^!?"(?:[^"\\]|\\[\S\s])*(?:"|$)/,null,'"'],["com",/^;[^\n\r]*/,null,";"]],[["pln",/^[!%@](?:[$\-.A-Z_a-z][\w$\-.]*|\d+)/],["kwd",/^[^\W\d]\w*/,null],["lit",/^\d+\.\d+/],["lit",/^(?:\d+|0[Xx][\dA-Fa-f]+)/],["pun",/^[(-*,:<->[\]{}]|\.\.\.$/]]),["llvm","ll"]); ================================================ FILE: public/packages/google-code-prettify/lang-lua.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r \u00a0"],["str",/^(?:"(?:[^"\\]|\\[\S\s])*(?:"|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$))/,null,"\"'"]],[["com",/^--(?:\[(=*)\[[\S\s]*?(?:]\1]|$)|[^\n\r]*)/],["str",/^\[(=*)\[[\S\s]*?(?:]\1]|$)/],["kwd",/^(?:and|break|do|else|elseif|end|false|for|function|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/,null],["lit",/^[+-]?(?:0x[\da-f]+|(?:\.\d+|\d+(?:\.\d*)?)(?:e[+-]?\d+)?)/i], ["pln",/^[_a-z]\w*/i],["pun",/^[^\w\t\n\r \xa0][^\w\t\n\r "'+=\xa0-]*/]]),["lua"]); ================================================ FILE: public/packages/google-code-prettify/lang-matlab.js ================================================ var a=null,b=window.PR,c=[[b.PR_PLAIN,/^[\t-\r \xa0]+/,a," \t\r\n\u000b\u000c\u00a0"],[b.PR_COMMENT,/^%{[^%]*%+(?:[^%}][^%]*%+)*}/,a],[b.PR_COMMENT,/^%[^\n\r]*/,a,"%"],["syscmd",/^![^\n\r]*/,a,"!"]],d=[["linecont",/^\.\.\.\s*[\n\r]/,a],["err",/^\?\?\? [^\n\r]*/,a],["wrn",/^Warning: [^\n\r]*/,a],["codeoutput",/^>>\s+/,a],["codeoutput",/^octave:\d+>\s+/,a],["lang-matlab-operators",/^((?:[A-Za-z]\w*(?:\.[A-Za-z]\w*)*|[).\]}])')/,a],["lang-matlab-identifiers",/^([A-Za-z]\w*(?:\.[A-Za-z]\w*)*)(?!')/,a], [b.PR_STRING,/^'(?:[^']|'')*'/,a],[b.PR_LITERAL,/^[+-]?\.?\d+(?:\.\d*)?(?:[Ee][+-]?\d+)?[ij]?/,a],[b.PR_TAG,/^[()[\]{}]/,a],[b.PR_PUNCTUATION,/^[!&*-/:->@\\^|~]/,a]],e=[["lang-matlab-identifiers",/^([A-Za-z]\w*(?:\.[A-Za-z]\w*)*)/,a],[b.PR_TAG,/^[()[\]{}]/,a],[b.PR_PUNCTUATION,/^[!&*-/:->@\\^|~]/,a],["transpose",/^'/,a]]; b.registerLangHandler(b.createSimpleLexer([],[[b.PR_KEYWORD,/^\b(?:break|case|catch|classdef|continue|else|elseif|end|for|function|global|if|otherwise|parfor|persistent|return|spmd|switch|try|while)\b/,a],["const",/^\b(?:true|false|inf|Inf|nan|NaN|eps|pi|ans|nargin|nargout|varargin|varargout)\b/,a],[b.PR_TYPE,/^\b(?:cell|struct|char|double|single|logical|u?int(?:8|16|32|64)|sparse)\b/,a],["fun",/^\b(?:abs|accumarray|acos(?:d|h)?|acot(?:d|h)?|acsc(?:d|h)?|actxcontrol(?:list|select)?|actxGetRunningServer|actxserver|addlistener|addpath|addpref|addtodate|airy|align|alim|all|allchild|alpha|alphamap|amd|ancestor|and|angle|annotation|any|area|arrayfun|asec(?:d|h)?|asin(?:d|h)?|assert|assignin|atan[2dh]?|audiodevinfo|audioplayer|audiorecorder|aufinfo|auread|autumn|auwrite|avifile|aviinfo|aviread|axes|axis|balance|bar(?:3|3h|h)?|base2dec|beep|BeginInvoke|bench|bessel[h-ky]|beta|betainc|betaincinv|betaln|bicg|bicgstab|bicgstabl|bin2dec|bitand|bitcmp|bitget|bitmax|bitnot|bitor|bitset|bitshift|bitxor|blanks|blkdiag|bone|box|brighten|brush|bsxfun|builddocsearchdb|builtin|bvp4c|bvp5c|bvpget|bvpinit|bvpset|bvpxtend|calendar|calllib|callSoapService|camdolly|cameratoolbar|camlight|camlookat|camorbit|campan|campos|camproj|camroll|camtarget|camup|camva|camzoom|cart2pol|cart2sph|cast|cat|caxis|cd|cdf2rdf|cdfepoch|cdfinfo|cdflib(?:.(?:close|closeVar|computeEpoch|computeEpoch16|create|createAttr|createVar|delete|deleteAttr|deleteAttrEntry|deleteAttrgEntry|deleteVar|deleteVarRecords|epoch16Breakdown|epochBreakdown|getAttrEntry|getAttrgEntry|getAttrMaxEntry|getAttrMaxgEntry|getAttrName|getAttrNum|getAttrScope|getCacheSize|getChecksum|getCompression|getCompressionCacheSize|getConstantNames|getConstantValue|getCopyright|getFileBackward|getFormat|getLibraryCopyright|getLibraryVersion|getMajority|getName|getNumAttrEntries|getNumAttrgEntries|getNumAttributes|getNumgAttributes|getReadOnlyMode|getStageCacheSize|getValidate|getVarAllocRecords|getVarBlockingFactor|getVarCacheSize|getVarCompression|getVarData|getVarMaxAllocRecNum|getVarMaxWrittenRecNum|getVarName|getVarNum|getVarNumRecsWritten|getVarPadValue|getVarRecordData|getVarReservePercent|getVarsMaxWrittenRecNum|getVarSparseRecords|getVersion|hyperGetVarData|hyperPutVarData|inquire|inquireAttr|inquireAttrEntry|inquireAttrgEntry|inquireVar|open|putAttrEntry|putAttrgEntry|putVarData|putVarRecordData|renameAttr|renameVar|setCacheSize|setChecksum|setCompression|setCompressionCacheSize|setFileBackward|setFormat|setMajority|setReadOnlyMode|setStageCacheSize|setValidate|setVarAllocBlockRecords|setVarBlockingFactor|setVarCacheSize|setVarCompression|setVarInitialRecs|setVarPadValue|SetVarReservePercent|setVarsCacheSize|setVarSparseRecords))?|cdfread|cdfwrite|ceil|cell2mat|cell2struct|celldisp|cellfun|cellplot|cellstr|cgs|checkcode|checkin|checkout|chol|cholinc|cholupdate|circshift|cla|clabel|class|clc|clear|clearvars|clf|clipboard|clock|close|closereq|cmopts|cmpermute|cmunique|colamd|colon|colorbar|colordef|colormap|colormapeditor|colperm|Combine|comet|comet3|commandhistory|commandwindow|compan|compass|complex|computer|cond|condeig|condest|coneplot|conj|containers.Map|contour(?:[3cf]|slice)?|contrast|conv|conv2|convhull|convhulln|convn|cool|copper|copyfile|copyobj|corrcoef|cos(?:d|h)?|cot(?:d|h)?|cov|cplxpair|cputime|createClassFromWsdl|createSoapMessage|cross|csc(?:d|h)?|csvread|csvwrite|ctranspose|cumprod|cumsum|cumtrapz|curl|customverctrl|cylinder|daqread|daspect|datacursormode|datatipinfo|date|datenum|datestr|datetick|datevec|dbclear|dbcont|dbdown|dblquad|dbmex|dbquit|dbstack|dbstatus|dbstep|dbstop|dbtype|dbup|dde23|ddeget|ddesd|ddeset|deal|deblank|dec2base|dec2bin|dec2hex|decic|deconv|del2|delaunay|delaunay3|delaunayn|DelaunayTri|delete|demo|depdir|depfun|det|detrend|deval|diag|dialog|diary|diff|diffuse|dir|disp|display|dither|divergence|dlmread|dlmwrite|dmperm|doc|docsearch|dos|dot|dragrect|drawnow|dsearch|dsearchn|dynamicprops|echo|echodemo|edit|eig|eigs|ellipj|ellipke|ellipsoid|empty|enableNETfromNetworkDrive|enableservice|EndInvoke|enumeration|eomday|eq|erf|erfc|erfcinv|erfcx|erfinv|error|errorbar|errordlg|etime|etree|etreeplot|eval|evalc|evalin|event.(?:EventData|listener|PropertyEvent|proplistener)|exifread|exist|exit|exp|expint|expm|expm1|export2wsdlg|eye|ezcontour|ezcontourf|ezmesh|ezmeshc|ezplot|ezplot3|ezpolar|ezsurf|ezsurfc|factor|factorial|fclose|feather|feature|feof|ferror|feval|fft|fft2|fftn|fftshift|fftw|fgetl|fgets|fieldnames|figure|figurepalette|fileattrib|filebrowser|filemarker|fileparts|fileread|filesep|fill|fill3|filter|filter2|find|findall|findfigs|findobj|findstr|finish|fitsdisp|fitsinfo|fitsread|fitswrite|fix|flag|flipdim|fliplr|flipud|floor|flow|fminbnd|fminsearch|fopen|format|fplot|fprintf|frame2im|fread|freqspace|frewind|fscanf|fseek|ftell|FTP|full|fullfile|func2str|functions|funm|fwrite|fzero|gallery|gamma|gammainc|gammaincinv|gammaln|gca|gcbf|gcbo|gcd|gcf|gco|ge|genpath|genvarname|get|getappdata|getenv|getfield|getframe|getpixelposition|getpref|ginput|gmres|gplot|grabcode|gradient|gray|graymon|grid|griddata(?:3|n)?|griddedInterpolant|gsvd|gt|gtext|guidata|guide|guihandles|gunzip|gzip|h5create|h5disp|h5info|h5read|h5readatt|h5write|h5writeatt|hadamard|handle|hankel|hdf|hdf5|hdf5info|hdf5read|hdf5write|hdfinfo|hdfread|hdftool|help|helpbrowser|helpdesk|helpdlg|helpwin|hess|hex2dec|hex2num|hgexport|hggroup|hgload|hgsave|hgsetget|hgtransform|hidden|hilb|hist|histc|hold|home|horzcat|hostid|hot|hsv|hsv2rgb|hypot|ichol|idivide|ifft|ifft2|ifftn|ifftshift|ilu|im2frame|im2java|imag|image|imagesc|imapprox|imfinfo|imformats|import|importdata|imread|imwrite|ind2rgb|ind2sub|inferiorto|info|inline|inmem|inpolygon|input|inputdlg|inputname|inputParser|inspect|instrcallback|instrfind|instrfindall|int2str|integral(?:2|3)?|interp(?:1|1q|2|3|ft|n)|interpstreamspeed|intersect|intmax|intmin|inv|invhilb|ipermute|isa|isappdata|iscell|iscellstr|ischar|iscolumn|isdir|isempty|isequal|isequaln|isequalwithequalnans|isfield|isfinite|isfloat|isglobal|ishandle|ishghandle|ishold|isinf|isinteger|isjava|iskeyword|isletter|islogical|ismac|ismatrix|ismember|ismethod|isnan|isnumeric|isobject|isocaps|isocolors|isonormals|isosurface|ispc|ispref|isprime|isprop|isreal|isrow|isscalar|issorted|isspace|issparse|isstr|isstrprop|isstruct|isstudent|isunix|isvarname|isvector|javaaddpath|javaArray|javachk|javaclasspath|javacomponent|javaMethod|javaMethodEDT|javaObject|javaObjectEDT|javarmpath|jet|keyboard|kron|lasterr|lasterror|lastwarn|lcm|ldivide|ldl|le|legend|legendre|length|libfunctions|libfunctionsview|libisloaded|libpointer|libstruct|license|light|lightangle|lighting|lin2mu|line|lines|linkaxes|linkdata|linkprop|linsolve|linspace|listdlg|listfonts|load|loadlibrary|loadobj|log|log10|log1p|log2|loglog|logm|logspace|lookfor|lower|ls|lscov|lsqnonneg|lsqr|lt|lu|luinc|magic|makehgtform|mat2cell|mat2str|material|matfile|matlab.io.MatFile|matlab.mixin.(?:Copyable|Heterogeneous(?:.getDefaultScalarElement)?)|matlabrc|matlabroot|max|maxNumCompThreads|mean|median|membrane|memmapfile|memory|menu|mesh|meshc|meshgrid|meshz|meta.(?:class(?:.fromName)?|DynamicProperty|EnumeratedValue|event|MetaData|method|package(?:.(?:fromName|getAllPackages))?|property)|metaclass|methods|methodsview|mex(?:.getCompilerConfigurations)?|MException|mexext|mfilename|min|minres|minus|mislocked|mkdir|mkpp|mldivide|mlint|mlintrpt|mlock|mmfileinfo|mmreader|mod|mode|more|move|movefile|movegui|movie|movie2avi|mpower|mrdivide|msgbox|mtimes|mu2lin|multibandread|multibandwrite|munlock|namelengthmax|nargchk|narginchk|nargoutchk|native2unicode|nccreate|ncdisp|nchoosek|ncinfo|ncread|ncreadatt|ncwrite|ncwriteatt|ncwriteschema|ndgrid|ndims|ne|NET(?:.(?:addAssembly|Assembly|convertArray|createArray|createGeneric|disableAutoRelease|enableAutoRelease|GenericClass|invokeGenericMethod|NetException|setStaticProperty))?|netcdf.(?:abort|close|copyAtt|create|defDim|defGrp|defVar|defVarChunking|defVarDeflate|defVarFill|defVarFletcher32|delAtt|endDef|getAtt|getChunkCache|getConstant|getConstantNames|getVar|inq|inqAtt|inqAttID|inqAttName|inqDim|inqDimID|inqDimIDs|inqFormat|inqGrpName|inqGrpNameFull|inqGrpParent|inqGrps|inqLibVers|inqNcid|inqUnlimDims|inqVar|inqVarChunking|inqVarDeflate|inqVarFill|inqVarFletcher32|inqVarID|inqVarIDs|open|putAtt|putVar|reDef|renameAtt|renameDim|renameVar|setChunkCache|setDefaultFormat|setFill|sync)|newplot|nextpow2|nnz|noanimate|nonzeros|norm|normest|not|notebook|now|nthroot|null|num2cell|num2hex|num2str|numel|nzmax|ode(?:113|15i|15s|23|23s|23t|23tb|45)|odeget|odeset|odextend|onCleanup|ones|open|openfig|opengl|openvar|optimget|optimset|or|ordeig|orderfields|ordqz|ordschur|orient|orth|pack|padecoef|pagesetupdlg|pan|pareto|parseSoapResponse|pascal|patch|path|path2rc|pathsep|pathtool|pause|pbaspect|pcg|pchip|pcode|pcolor|pdepe|pdeval|peaks|perl|perms|permute|pie|pink|pinv|planerot|playshow|plot|plot3|plotbrowser|plotedit|plotmatrix|plottools|plotyy|plus|pol2cart|polar|poly|polyarea|polyder|polyeig|polyfit|polyint|polyval|polyvalm|pow2|power|ppval|prefdir|preferences|primes|print|printdlg|printopt|printpreview|prod|profile|profsave|propedit|propertyeditor|psi|publish|PutCharArray|PutFullMatrix|PutWorkspaceData|pwd|qhull|qmr|qr|qrdelete|qrinsert|qrupdate|quad|quad2d|quadgk|quadl|quadv|questdlg|quit|quiver|quiver3|qz|rand|randi|randn|randperm|RandStream(?:.(?:create|getDefaultStream|getGlobalStream|list|setDefaultStream|setGlobalStream))?|rank|rat|rats|rbbox|rcond|rdivide|readasync|real|reallog|realmax|realmin|realpow|realsqrt|record|rectangle|rectint|recycle|reducepatch|reducevolume|refresh|refreshdata|regexp|regexpi|regexprep|regexptranslate|rehash|rem|Remove|RemoveAll|repmat|reset|reshape|residue|restoredefaultpath|rethrow|rgb2hsv|rgb2ind|rgbplot|ribbon|rmappdata|rmdir|rmfield|rmpath|rmpref|rng|roots|rose|rosser|rot90|rotate|rotate3d|round|rref|rsf2csf|run|save|saveas|saveobj|savepath|scatter|scatter3|schur|sec|secd|sech|selectmoveresize|semilogx|semilogy|sendmail|serial|set|setappdata|setdiff|setenv|setfield|setpixelposition|setpref|setstr|setxor|shading|shg|shiftdim|showplottool|shrinkfaces|sign|sin(?:d|h)?|size|slice|smooth3|snapnow|sort|sortrows|sound|soundsc|spalloc|spaugment|spconvert|spdiags|specular|speye|spfun|sph2cart|sphere|spinmap|spline|spones|spparms|sprand|sprandn|sprandsym|sprank|spring|sprintf|spy|sqrt|sqrtm|squeeze|ss2tf|sscanf|stairs|startup|std|stem|stem3|stopasync|str2double|str2func|str2mat|str2num|strcat|strcmp|strcmpi|stream2|stream3|streamline|streamparticles|streamribbon|streamslice|streamtube|strfind|strjust|strmatch|strncmp|strncmpi|strread|strrep|strtok|strtrim|struct2cell|structfun|strvcat|sub2ind|subplot|subsasgn|subsindex|subspace|subsref|substruct|subvolume|sum|summer|superclasses|superiorto|support|surf|surf2patch|surface|surfc|surfl|surfnorm|svd|svds|swapbytes|symamd|symbfact|symmlq|symrcm|symvar|system|tan(?:d|h)?|tar|tempdir|tempname|tetramesh|texlabel|text|textread|textscan|textwrap|tfqmr|throw|tic|Tiff(?:.(?:getTagNames|getVersion))?|timer|timerfind|timerfindall|times|timeseries|title|toc|todatenum|toeplitz|toolboxdir|trace|transpose|trapz|treelayout|treeplot|tril|trimesh|triplequad|triplot|TriRep|TriScatteredInterp|trisurf|triu|tscollection|tsearch|tsearchn|tstool|type|typecast|uibuttongroup|uicontextmenu|uicontrol|uigetdir|uigetfile|uigetpref|uiimport|uimenu|uiopen|uipanel|uipushtool|uiputfile|uiresume|uisave|uisetcolor|uisetfont|uisetpref|uistack|uitable|uitoggletool|uitoolbar|uiwait|uminus|undocheckout|unicode2native|union|unique|unix|unloadlibrary|unmesh|unmkpp|untar|unwrap|unzip|uplus|upper|urlread|urlwrite|usejava|userpath|validateattributes|validatestring|vander|var|vectorize|ver|verctrl|verLessThan|version|vertcat|VideoReader(?:.isPlatformSupported)?|VideoWriter(?:.getProfiles)?|view|viewmtx|visdiff|volumebounds|voronoi|voronoin|wait|waitbar|waitfor|waitforbuttonpress|warndlg|warning|waterfall|wavfinfo|wavplay|wavread|wavrecord|wavwrite|web|weekday|what|whatsnew|which|whitebg|who|whos|wilkinson|winopen|winqueryreg|winter|wk1finfo|wk1read|wk1write|workspace|xlabel|xlim|xlsfinfo|xlsread|xlswrite|xmlread|xmlwrite|xor|xslt|ylabel|ylim|zeros|zip|zlabel|zlim|zoom)\b/, a],["fun_tbx",/^\b(?:addedvarplot|andrewsplot|anova[12n]|ansaribradley|aoctool|barttest|bbdesign|beta(?:cdf|fit|inv|like|pdf|rnd|stat)|bino(?:cdf|fit|inv|pdf|rnd|stat)|biplot|bootci|bootstrp|boxplot|candexch|candgen|canoncorr|capability|capaplot|caseread|casewrite|categorical|ccdesign|cdfplot|chi2(?:cdf|gof|inv|pdf|rnd|stat)|cholcov|Classification(?:BaggedEnsemble|Discriminant(?:.(?:fit|make|template))?|Ensemble|KNN(?:.(?:fit|template))?|PartitionedEnsemble|PartitionedModel|Tree(?:.(?:fit|template))?)|classify|classregtree|cluster|clusterdata|cmdscale|combnk|Compact(?:Classification(?:Discriminant|Ensemble|Tree)|Regression(?:Ensemble|Tree)|TreeBagger)|confusionmat|controlchart|controlrules|cophenet|copula(?:cdf|fit|param|pdf|rnd|stat)|cordexch|corr|corrcov|coxphfit|createns|crosstab|crossval|cvpartition|datasample|dataset|daugment|dcovary|dendrogram|dfittool|disttool|dummyvar|dwtest|ecdf|ecdfhist|ev(?:cdf|fit|inv|like|pdf|rnd|stat)|ExhaustiveSearcher|exp(?:cdf|fit|inv|like|pdf|rnd|stat)|factoran|fcdf|ff2n|finv|fitdist|fitensemble|fpdf|fracfact|fracfactgen|friedman|frnd|fstat|fsurfht|fullfact|gagerr|gam(?:cdf|fit|inv|like|pdf|rnd|stat)|GeneralizedLinearModel(?:.fit)?|geo(?:cdf|inv|mean|pdf|rnd|stat)|gev(?:cdf|fit|inv|like|pdf|rnd|stat)|gline|glmfit|glmval|glyphplot|gmdistribution(?:.fit)?|gname|gp(?:cdf|fit|inv|like|pdf|rnd|stat)|gplotmatrix|grp2idx|grpstats|gscatter|haltonset|harmmean|hist3|histfit|hmm(?:decode|estimate|generate|train|viterbi)|hougen|hyge(?:cdf|inv|pdf|rnd|stat)|icdf|inconsistent|interactionplot|invpred|iqr|iwishrnd|jackknife|jbtest|johnsrnd|KDTreeSearcher|kmeans|knnsearch|kruskalwallis|ksdensity|kstest|kstest2|kurtosis|lasso|lassoglm|lassoPlot|leverage|lhsdesign|lhsnorm|lillietest|LinearModel(?:.fit)?|linhyptest|linkage|logn(?:cdf|fit|inv|like|pdf|rnd|stat)|lsline|mad|mahal|maineffectsplot|manova1|manovacluster|mdscale|mhsample|mle|mlecov|mnpdf|mnrfit|mnrnd|mnrval|moment|multcompare|multivarichart|mvn(?:cdf|pdf|rnd)|mvregress|mvregresslike|mvt(?:cdf|pdf|rnd)|NaiveBayes(?:.fit)?|nan(?:cov|max|mean|median|min|std|sum|var)|nbin(?:cdf|fit|inv|pdf|rnd|stat)|ncf(?:cdf|inv|pdf|rnd|stat)|nct(?:cdf|inv|pdf|rnd|stat)|ncx2(?:cdf|inv|pdf|rnd|stat)|NeighborSearcher|nlinfit|nlintool|nlmefit|nlmefitsa|nlparci|nlpredci|nnmf|nominal|NonLinearModel(?:.fit)?|norm(?:cdf|fit|inv|like|pdf|rnd|stat)|normplot|normspec|ordinal|outlierMeasure|parallelcoords|paretotails|partialcorr|pcacov|pcares|pdf|pdist|pdist2|pearsrnd|perfcurve|perms|piecewisedistribution|plsregress|poiss(?:cdf|fit|inv|pdf|rnd|tat)|polyconf|polytool|prctile|princomp|ProbDist(?:Kernel|Parametric|UnivKernel|UnivParam)?|probplot|procrustes|qqplot|qrandset|qrandstream|quantile|randg|random|randsample|randtool|range|rangesearch|ranksum|rayl(?:cdf|fit|inv|pdf|rnd|stat)|rcoplot|refcurve|refline|regress|Regression(?:BaggedEnsemble|Ensemble|PartitionedEnsemble|PartitionedModel|Tree(?:.(?:fit|template))?)|regstats|relieff|ridge|robustdemo|robustfit|rotatefactors|rowexch|rsmdemo|rstool|runstest|sampsizepwr|scatterhist|sequentialfs|signrank|signtest|silhouette|skewness|slicesample|sobolset|squareform|statget|statset|stepwise|stepwisefit|surfht|tabulate|tblread|tblwrite|tcdf|tdfread|tiedrank|tinv|tpdf|TreeBagger|treedisp|treefit|treeprune|treetest|treeval|trimmean|trnd|tstat|ttest|ttest2|unid(?:cdf|inv|pdf|rnd|stat)|unif(?:cdf|inv|it|pdf|rnd|stat)|vartest(?:2|n)?|wbl(?:cdf|fit|inv|like|pdf|rnd|stat)|wblplot|wishrnd|x2fx|xptread|zscore|ztest)\b/, a],["fun_tbx",/^\b(?:adapthisteq|analyze75info|analyze75read|applycform|applylut|axes2pix|bestblk|blockproc|bwarea|bwareaopen|bwboundaries|bwconncomp|bwconvhull|bwdist|bwdistgeodesic|bweuler|bwhitmiss|bwlabel|bwlabeln|bwmorph|bwpack|bwperim|bwselect|bwtraceboundary|bwulterode|bwunpack|checkerboard|col2im|colfilt|conndef|convmtx2|corner|cornermetric|corr2|cp2tform|cpcorr|cpselect|cpstruct2pairs|dct2|dctmtx|deconvblind|deconvlucy|deconvreg|deconvwnr|decorrstretch|demosaic|dicom(?:anon|dict|info|lookup|read|uid|write)|edge|edgetaper|entropy|entropyfilt|fan2para|fanbeam|findbounds|fliptform|freqz2|fsamp2|fspecial|ftrans2|fwind1|fwind2|getheight|getimage|getimagemodel|getline|getneighbors|getnhood|getpts|getrangefromclass|getrect|getsequence|gray2ind|graycomatrix|graycoprops|graydist|grayslice|graythresh|hdrread|hdrwrite|histeq|hough|houghlines|houghpeaks|iccfind|iccread|iccroot|iccwrite|idct2|ifanbeam|im2bw|im2col|im2double|im2int16|im2java2d|im2single|im2uint16|im2uint8|imabsdiff|imadd|imadjust|ImageAdapter|imageinfo|imagemodel|imapplymatrix|imattributes|imbothat|imclearborder|imclose|imcolormaptool|imcomplement|imcontour|imcontrast|imcrop|imdilate|imdisplayrange|imdistline|imdivide|imellipse|imerode|imextendedmax|imextendedmin|imfill|imfilter|imfindcircles|imfreehand|imfuse|imgca|imgcf|imgetfile|imhandles|imhist|imhmax|imhmin|imimposemin|imlincomb|imline|immagbox|immovie|immultiply|imnoise|imopen|imoverview|imoverviewpanel|impixel|impixelinfo|impixelinfoval|impixelregion|impixelregionpanel|implay|impoint|impoly|impositionrect|improfile|imputfile|impyramid|imreconstruct|imrect|imregconfig|imregionalmax|imregionalmin|imregister|imresize|imroi|imrotate|imsave|imscrollpanel|imshow|imshowpair|imsubtract|imtool|imtophat|imtransform|imview|ind2gray|ind2rgb|interfileinfo|interfileread|intlut|ippl|iptaddcallback|iptcheckconn|iptcheckhandle|iptcheckinput|iptcheckmap|iptchecknargin|iptcheckstrs|iptdemos|iptgetapi|iptGetPointerBehavior|iptgetpref|ipticondir|iptnum2ordinal|iptPointerManager|iptprefs|iptremovecallback|iptSetPointerBehavior|iptsetpref|iptwindowalign|iradon|isbw|isflat|isgray|isicc|isind|isnitf|isrgb|isrset|lab2double|lab2uint16|lab2uint8|label2rgb|labelmatrix|makecform|makeConstrainToRectFcn|makehdr|makelut|makeresampler|maketform|mat2gray|mean2|medfilt2|montage|nitfinfo|nitfread|nlfilter|normxcorr2|ntsc2rgb|openrset|ordfilt2|otf2psf|padarray|para2fan|phantom|poly2mask|psf2otf|qtdecomp|qtgetblk|qtsetblk|radon|rangefilt|reflect|regionprops|registration.metric.(?:MattesMutualInformation|MeanSquares)|registration.optimizer.(?:OnePlusOneEvolutionary|RegularStepGradientDescent)|rgb2gray|rgb2ntsc|rgb2ycbcr|roicolor|roifill|roifilt2|roipoly|rsetwrite|std2|stdfilt|strel|stretchlim|subimage|tformarray|tformfwd|tforminv|tonemap|translate|truesize|uintlut|viscircles|warp|watershed|whitepoint|wiener2|xyz2double|xyz2uint16|ycbcr2rgb)\b/, a],["fun_tbx",/^\b(?:bintprog|color|fgoalattain|fminbnd|fmincon|fminimax|fminsearch|fminunc|fseminf|fsolve|fzero|fzmult|gangstr|ktrlink|linprog|lsqcurvefit|lsqlin|lsqnonlin|lsqnonneg|optimget|optimset|optimtool|quadprog)\b/,a],["ident",/^[A-Za-z]\w*(?:\.[A-Za-z]\w*)*/,a]]),["matlab-identifiers"]);b.registerLangHandler(b.createSimpleLexer([],e),["matlab-operators"]);b.registerLangHandler(b.createSimpleLexer(c,d),["matlab"]); ================================================ FILE: public/packages/google-code-prettify/lang-ml.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r \u00a0"],["com",/^#(?:if[\t\n\r \xa0]+(?:[$_a-z][\w']*|``[^\t\n\r`]*(?:``|$))|else|endif|light)/i,null,"#"],["str",/^(?:"(?:[^"\\]|\\[\S\s])*(?:"|$)|'(?:[^'\\]|\\[\S\s])(?:'|$))/,null,"\"'"]],[["com",/^(?:\/\/[^\n\r]*|\(\*[\S\s]*?\*\))/],["kwd",/^(?:abstract|and|as|assert|begin|class|default|delegate|do|done|downcast|downto|elif|else|end|exception|extern|false|finally|for|fun|function|if|in|inherit|inline|interface|internal|lazy|let|match|member|module|mutable|namespace|new|null|of|open|or|override|private|public|rec|return|static|struct|then|to|true|try|type|upcast|use|val|void|when|while|with|yield|asr|land|lor|lsl|lsr|lxor|mod|sig|atomic|break|checked|component|const|constraint|constructor|continue|eager|event|external|fixed|functor|global|include|method|mixin|object|parallel|process|protected|pure|sealed|trait|virtual|volatile)\b/], ["lit",/^[+-]?(?:0x[\da-f]+|(?:\.\d+|\d+(?:\.\d*)?)(?:e[+-]?\d+)?)/i],["pln",/^(?:[_a-z][\w']*[!#?]?|``[^\t\n\r`]*(?:``|$))/i],["pun",/^[^\w\t\n\r "'\xa0]+/]]),["fs","ml"]); ================================================ FILE: public/packages/google-code-prettify/lang-mumps.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r \u00a0"],["str",/^"(?:[^"]|\\.)*"/,null,'"']],[["com",/^;[^\n\r]*/,null,";"],["dec",/^\$(?:d|device|ec|ecode|es|estack|et|etrap|h|horolog|i|io|j|job|k|key|p|principal|q|quit|st|stack|s|storage|sy|system|t|test|tl|tlevel|tr|trestart|x|y|z[a-z]*|a|ascii|c|char|d|data|e|extract|f|find|fn|fnumber|g|get|j|justify|l|length|na|name|o|order|p|piece|ql|qlength|qs|qsubscript|q|query|r|random|re|reverse|s|select|st|stack|t|text|tr|translate|nan)\b/i, null],["kwd",/^(?:[^$]b|break|c|close|d|do|e|else|f|for|g|goto|h|halt|h|hang|i|if|j|job|k|kill|l|lock|m|merge|n|new|o|open|q|quit|r|read|s|set|tc|tcommit|tre|trestart|tro|trollback|ts|tstart|u|use|v|view|w|write|x|xecute)\b/i,null],["lit",/^[+-]?(?:\.\d+|\d+(?:\.\d*)?)(?:e[+-]?\d+)?/i],["pln",/^[a-z][^\W_]*/i],["pun",/^[^\w\t\n\r"$%;^\xa0]|_/]]),["mumps"]); ================================================ FILE: public/packages/google-code-prettify/lang-n.js ================================================ var a=null; PR.registerLangHandler(PR.createSimpleLexer([["str",/^(?:'(?:[^\n\r'\\]|\\.)*'|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,a,'"'],["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,a,"#"],["pln",/^\s+/,a," \r\n\t\u00a0"]],[["str",/^@"(?:[^"]|"")*(?:"|$)/,a],["str",/^<#[^#>]*(?:#>|$)/,a],["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,a],["com",/^\/\/[^\n\r]*/,a],["com",/^\/\*[\S\s]*?(?:\*\/|$)/, a],["kwd",/^(?:abstract|and|as|base|catch|class|def|delegate|enum|event|extern|false|finally|fun|implements|interface|internal|is|macro|match|matches|module|mutable|namespace|new|null|out|override|params|partial|private|protected|public|ref|sealed|static|struct|syntax|this|throw|true|try|type|typeof|using|variant|virtual|volatile|when|where|with|assert|assert2|async|break|checked|continue|do|else|ensures|for|foreach|if|late|lock|new|nolate|otherwise|regexp|repeat|requires|return|surroundwith|unchecked|unless|using|while|yield)\b/, a],["typ",/^(?:array|bool|byte|char|decimal|double|float|int|list|long|object|sbyte|short|string|ulong|uint|ufloat|ulong|ushort|void)\b/,a],["lit",/^@[$_a-z][\w$@]*/i,a],["typ",/^@[A-Z]+[a-z][\w$@]*/,a],["pln",/^'?[$_a-z][\w$@]*/i,a],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,a,"0123456789"],["pun",/^.[^\s\w"-$'./@`]*/,a]]),["n","nemerle"]); ================================================ FILE: public/packages/google-code-prettify/lang-pascal.js ================================================ var a=null; PR.registerLangHandler(PR.createSimpleLexer([["str",/^'(?:[^\n\r'\\]|\\.)*(?:'|$)/,a,"'"],["pln",/^\s+/,a," \r\n\t\u00a0"]],[["com",/^\(\*[\S\s]*?(?:\*\)|$)|^{[\S\s]*?(?:}|$)/,a],["kwd",/^(?:absolute|and|array|asm|assembler|begin|case|const|constructor|destructor|div|do|downto|else|end|external|for|forward|function|goto|if|implementation|in|inline|interface|interrupt|label|mod|not|object|of|or|packed|procedure|program|record|repeat|set|shl|shr|then|to|type|unit|until|uses|var|virtual|while|with|xor)\b/i,a], ["lit",/^(?:true|false|self|nil)/i,a],["pln",/^[a-z][^\W_]*/i,a],["lit",/^(?:\$[\da-f]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)/i,a,"0123456789"],["pun",/^.[^\s\w$'./@]*/,a]]),["pascal"]); ================================================ FILE: public/packages/google-code-prettify/lang-proto.js ================================================ PR.registerLangHandler(PR.sourceDecorator({keywords:"bytes,default,double,enum,extend,extensions,false,group,import,max,message,option,optional,package,repeated,required,returns,rpc,service,syntax,to,true",types:/^(bool|(double|s?fixed|[su]?int)(32|64)|float|string)\b/,cStyleComments:!0}),["proto"]); ================================================ FILE: public/packages/google-code-prettify/lang-r.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r \u00a0"],["str",/^"(?:[^"\\]|\\[\S\s])*(?:"|$)/,null,'"'],["str",/^'(?:[^'\\]|\\[\S\s])*(?:'|$)/,null,"'"]],[["com",/^#.*/],["kwd",/^(?:if|else|for|while|repeat|in|next|break|return|switch|function)(?![\w.])/],["lit",/^0[Xx][\dA-Fa-f]+([Pp]\d+)?[Li]?/],["lit",/^[+-]?(\d+(\.\d+)?|\.\d+)([Ee][+-]?\d+)?[Li]?/],["lit",/^(?:NULL|NA(?:_(?:integer|real|complex|character)_)?|Inf|TRUE|FALSE|NaN|\.\.(?:\.|\d+))(?![\w.])/], ["pun",/^(?:<>?|-|==|<=|>=|<|>|&&?|!=|\|\|?|[!*+/^]|%.*?%|[$=@~]|:{1,3}|[(),;?[\]{}])/],["pln",/^(?:[A-Za-z]+[\w.]*|\.[^\W\d][\w.]*)(?![\w.])/],["str",/^`.+`/]]),["r","s","R","S","Splus"]); ================================================ FILE: public/packages/google-code-prettify/lang-rd.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r \u00a0"],["com",/^%[^\n\r]*/,null,"%"]],[["lit",/^\\(?:cr|l?dots|R|tab)\b/],["kwd",/^\\[@-Za-z]+/],["kwd",/^#(?:ifn?def|endif)/],["pln",/^\\[{}]/],["pun",/^[()[\]{}]+/]]),["Rd","rd"]); ================================================ FILE: public/packages/google-code-prettify/lang-scala.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r \u00a0"],["str",/^"(?:""(?:""?(?!")|[^"\\]|\\.)*"{0,3}|(?:[^\n\r"\\]|\\.)*"?)/,null,'"'],["lit",/^`(?:[^\n\r\\`]|\\.)*`?/,null,"`"],["pun",/^[!#%&(--:-@[-^{-~]+/,null,"!#%&()*+,-:;<=>?@[\\]^{|}~"]],[["str",/^'(?:[^\n\r'\\]|\\(?:'|[^\n\r']+))'/],["lit",/^'[$A-Z_a-z][\w$]*(?![\w$'])/],["kwd",/^(?:abstract|case|catch|class|def|do|else|extends|final|finally|for|forSome|if|implicit|import|lazy|match|new|object|override|package|private|protected|requires|return|sealed|super|throw|trait|try|type|val|var|while|with|yield)\b/], ["lit",/^(?:true|false|null|this)\b/],["lit",/^(?:0(?:[0-7]+|x[\da-f]+)l?|(?:0|[1-9]\d*)(?:(?:\.\d+)?(?:e[+-]?\d+)?f?|l?)|\\.\d+(?:e[+-]?\d+)?f?)/i],["typ",/^[$_]*[A-Z][\d$A-Z_]*[a-z][\w$]*/],["pln",/^[$A-Z_a-z][\w$]*/],["com",/^\/(?:\/.*|\*(?:\/|\**[^*/])*(?:\*+\/?)?)/],["pun",/^(?:\.+|\/)/]]),["scala"]); ================================================ FILE: public/packages/google-code-prettify/lang-sql.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r \u00a0"],["str",/^(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/,null,"\"'"]],[["com",/^(?:--[^\n\r]*|\/\*[\S\s]*?(?:\*\/|$))/],["kwd",/^(?:add|all|alter|and|any|apply|as|asc|authorization|backup|begin|between|break|browse|bulk|by|cascade|case|check|checkpoint|close|clustered|coalesce|collate|column|commit|compute|connect|constraint|contains|containstable|continue|convert|create|cross|current|current_date|current_time|current_timestamp|current_user|cursor|database|dbcc|deallocate|declare|default|delete|deny|desc|disk|distinct|distributed|double|drop|dummy|dump|else|end|errlvl|escape|except|exec|execute|exists|exit|fetch|file|fillfactor|following|for|foreign|freetext|freetexttable|from|full|function|goto|grant|group|having|holdlock|identity|identitycol|identity_insert|if|in|index|inner|insert|intersect|into|is|join|key|kill|left|like|lineno|load|match|matched|merge|natural|national|nocheck|nonclustered|nocycle|not|null|nullif|of|off|offsets|on|open|opendatasource|openquery|openrowset|openxml|option|or|order|outer|over|partition|percent|pivot|plan|preceding|precision|primary|print|proc|procedure|public|raiserror|read|readtext|reconfigure|references|replication|restore|restrict|return|revoke|right|rollback|rowcount|rowguidcol|rows?|rule|save|schema|select|session_user|set|setuser|shutdown|some|start|statistics|system_user|table|textsize|then|to|top|tran|transaction|trigger|truncate|tsequal|unbounded|union|unique|unpivot|update|updatetext|use|user|using|values|varying|view|waitfor|when|where|while|with|within|writetext|xml)(?=[^\w-]|$)/i, null],["lit",/^[+-]?(?:0x[\da-f]+|(?:\.\d+|\d+(?:\.\d*)?)(?:e[+-]?\d+)?)/i],["pln",/^[_a-z][\w-]*/i],["pun",/^[^\w\t\n\r "'\xa0][^\w\t\n\r "'+\xa0-]*/]]),["sql"]); ================================================ FILE: public/packages/google-code-prettify/lang-tcl.js ================================================ var a=null; PR.registerLangHandler(PR.createSimpleLexer([["opn",/^{+/,a,"{"],["clo",/^}+/,a,"}"],["com",/^#[^\n\r]*/,a,"#"],["pln",/^[\t\n\r \xa0]+/,a,"\t\n\r \u00a0"],["str",/^"(?:[^"\\]|\\[\S\s])*(?:"|$)/,a,'"']],[["kwd",/^(?:after|append|apply|array|break|case|catch|continue|error|eval|exec|exit|expr|for|foreach|if|incr|info|proc|return|set|switch|trace|uplevel|upvar|while)\b/,a],["lit",/^[+-]?(?:[#0]x[\da-f]+|\d+\/\d+|(?:\.\d+|\d+(?:\.\d*)?)(?:[de][+-]?\d+)?)/i],["lit", /^'(?:-*(?:\w|\\[!-~])(?:[\w-]*|\\[!-~])[!=?]?)?/],["pln",/^-*(?:[_a-z]|\\[!-~])(?:[\w-]*|\\[!-~])[!=?]?/i],["pun",/^[^\w\t\n\r "'-);\\\xa0]+/]]),["tcl"]); ================================================ FILE: public/packages/google-code-prettify/lang-tex.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r \u00a0"],["com",/^%[^\n\r]*/,null,"%"]],[["kwd",/^\\[@-Za-z]+/],["kwd",/^\\./],["typ",/^[$&]/],["lit",/[+-]?(?:\.\d+|\d+(?:\.\d*)?)(cm|em|ex|in|pc|pt|bp|mm)/i],["pun",/^[()=[\]{}]+/]]),["latex","tex"]); ================================================ FILE: public/packages/google-code-prettify/lang-vb.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0\u2028\u2029]+/,null,"\t\n\r \u00a0\u2028\u2029"],["str",/^(?:["\u201c\u201d](?:[^"\u201c\u201d]|["\u201c\u201d]{2})(?:["\u201c\u201d]c|$)|["\u201c\u201d](?:[^"\u201c\u201d]|["\u201c\u201d]{2})*(?:["\u201c\u201d]|$))/i,null,'"\u201c\u201d'],["com",/^['\u2018\u2019](?:_(?:\r\n?|[^\r]?)|[^\n\r_\u2028\u2029])*/,null,"'\u2018\u2019"]],[["kwd",/^(?:addhandler|addressof|alias|and|andalso|ansi|as|assembly|auto|boolean|byref|byte|byval|call|case|catch|cbool|cbyte|cchar|cdate|cdbl|cdec|char|cint|class|clng|cobj|const|cshort|csng|cstr|ctype|date|decimal|declare|default|delegate|dim|directcast|do|double|each|else|elseif|end|endif|enum|erase|error|event|exit|finally|for|friend|function|get|gettype|gosub|goto|handles|if|implements|imports|in|inherits|integer|interface|is|let|lib|like|long|loop|me|mod|module|mustinherit|mustoverride|mybase|myclass|namespace|new|next|not|notinheritable|notoverridable|object|on|option|optional|or|orelse|overloads|overridable|overrides|paramarray|preserve|private|property|protected|public|raiseevent|readonly|redim|removehandler|resume|return|select|set|shadows|shared|short|single|static|step|stop|string|structure|sub|synclock|then|throw|to|try|typeof|unicode|until|variant|wend|when|while|with|withevents|writeonly|xor|endif|gosub|let|variant|wend)\b/i, null],["com",/^rem\b.*/i],["lit",/^(?:true\b|false\b|nothing\b|\d+(?:e[+-]?\d+[dfr]?|[dfilrs])?|(?:&h[\da-f]+|&o[0-7]+)[ils]?|\d*\.\d+(?:e[+-]?\d+)?[dfr]?|#\s+(?:\d+[/-]\d+[/-]\d+(?:\s+\d+:\d+(?::\d+)?(\s*(?:am|pm))?)?|\d+:\d+(?::\d+)?(\s*(?:am|pm))?)\s+#)/i],["pln",/^(?:(?:[a-z]|_\w)\w*(?:\[[!#%&@]+])?|\[(?:[a-z]|_\w)\w*])/i],["pun",/^[^\w\t\n\r "'[\]\xa0\u2018\u2019\u201c\u201d\u2028\u2029]+/],["pun",/^(?:\[|])/]]),["vb","vbs"]); ================================================ FILE: public/packages/google-code-prettify/lang-vhdl.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r \u00a0"]],[["str",/^(?:[box]?"(?:[^"]|"")*"|'.')/i],["com",/^--[^\n\r]*/],["kwd",/^(?:abs|access|after|alias|all|and|architecture|array|assert|attribute|begin|block|body|buffer|bus|case|component|configuration|constant|disconnect|downto|else|elsif|end|entity|exit|file|for|function|generate|generic|group|guarded|if|impure|in|inertial|inout|is|label|library|linkage|literal|loop|map|mod|nand|new|next|nor|not|null|of|on|open|or|others|out|package|port|postponed|procedure|process|pure|range|record|register|reject|rem|report|return|rol|ror|select|severity|shared|signal|sla|sll|sra|srl|subtype|then|to|transport|type|unaffected|units|until|use|variable|wait|when|while|with|xnor|xor)(?=[^\w-]|$)/i, null],["typ",/^(?:bit|bit_vector|character|boolean|integer|real|time|string|severity_level|positive|natural|signed|unsigned|line|text|std_u?logic(?:_vector)?)(?=[^\w-]|$)/i,null],["typ",/^'(?:active|ascending|base|delayed|driving|driving_value|event|high|image|instance_name|last_active|last_event|last_value|left|leftof|length|low|path_name|pos|pred|quiet|range|reverse_range|right|rightof|simple_name|stable|succ|transaction|val|value)(?=[^\w-]|$)/i,null],["lit",/^\d+(?:_\d+)*(?:#[\w.\\]+#(?:[+-]?\d+(?:_\d+)*)?|(?:\.\d+(?:_\d+)*)?(?:e[+-]?\d+(?:_\d+)*)?)/i], ["pln",/^(?:[a-z]\w*|\\[^\\]*\\)/i],["pun",/^[^\w\t\n\r "'\xa0][^\w\t\n\r "'\xa0-]*/]]),["vhdl","vhd"]); ================================================ FILE: public/packages/google-code-prettify/lang-wiki.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\d\t a-gi-z\xa0]+/,null,"\t \u00a0abcdefgijklmnopqrstuvwxyz0123456789"],["pun",/^[*=[\]^~]+/,null,"=*~^[]"]],[["lang-wiki.meta",/(?:^^|\r\n?|\n)(#[a-z]+)\b/],["lit",/^[A-Z][a-z][\da-z]+[A-Z][a-z][^\W_]+\b/],["lang-",/^{{{([\S\s]+?)}}}/],["lang-",/^`([^\n\r`]+)`/],["str",/^https?:\/\/[^\s#/?]*(?:\/[^\s#?]*)?(?:\?[^\s#]*)?(?:#\S*)?/i],["pln",/^(?:\r\n|[\S\s])[^\n\r#*=A-[^`h{~]*/]]),["wiki"]); PR.registerLangHandler(PR.createSimpleLexer([["kwd",/^#[a-z]+/i,null,"#"]],[]),["wiki.meta"]); ================================================ FILE: public/packages/google-code-prettify/lang-xq.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["var pln",/^\$[\w-]+/,null,"$"]],[["pln",/^[\s=][<>][\s=]/],["lit",/^@[\w-]+/],["tag",/^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["com",/^\(:[\S\s]*?:\)/],["pln",/^[(),/;[\]{}]$/],["str",/^(?:"(?:[^"\\{]|\\[\S\s])*(?:"|$)|'(?:[^'\\{]|\\[\S\s])*(?:'|$))/,null,"\"'"],["kwd",/^(?:xquery|where|version|variable|union|typeswitch|treat|to|then|text|stable|sortby|some|self|schema|satisfies|returns|return|ref|processing-instruction|preceding-sibling|preceding|precedes|parent|only|of|node|namespace|module|let|item|intersect|instance|in|import|if|function|for|follows|following-sibling|following|external|except|every|else|element|descending|descendant-or-self|descendant|define|default|declare|comment|child|cast|case|before|attribute|assert|ascending|as|ancestor-or-self|ancestor|after|eq|order|by|or|and|schema-element|document-node|node|at)\b/], ["typ",/^(?:xs:yearMonthDuration|xs:unsignedLong|xs:time|xs:string|xs:short|xs:QName|xs:Name|xs:long|xs:integer|xs:int|xs:gYearMonth|xs:gYear|xs:gMonthDay|xs:gDay|xs:float|xs:duration|xs:double|xs:decimal|xs:dayTimeDuration|xs:dateTime|xs:date|xs:byte|xs:boolean|xs:anyURI|xf:yearMonthDuration)\b/,null],["fun pln",/^(?:xp:dereference|xinc:node-expand|xinc:link-references|xinc:link-expand|xhtml:restructure|xhtml:clean|xhtml:add-lists|xdmp:zip-manifest|xdmp:zip-get|xdmp:zip-create|xdmp:xquery-version|xdmp:word-convert|xdmp:with-namespaces|xdmp:version|xdmp:value|xdmp:user-roles|xdmp:user-last-login|xdmp:user|xdmp:url-encode|xdmp:url-decode|xdmp:uri-is-file|xdmp:uri-format|xdmp:uri-content-type|xdmp:unquote|xdmp:unpath|xdmp:triggers-database|xdmp:trace|xdmp:to-json|xdmp:tidy|xdmp:subbinary|xdmp:strftime|xdmp:spawn-in|xdmp:spawn|xdmp:sleep|xdmp:shutdown|xdmp:set-session-field|xdmp:set-response-encoding|xdmp:set-response-content-type|xdmp:set-response-code|xdmp:set-request-time-limit|xdmp:set|xdmp:servers|xdmp:server-status|xdmp:server-name|xdmp:server|xdmp:security-database|xdmp:security-assert|xdmp:schema-database|xdmp:save|xdmp:role-roles|xdmp:role|xdmp:rethrow|xdmp:restart|xdmp:request-timestamp|xdmp:request-status|xdmp:request-cancel|xdmp:request|xdmp:redirect-response|xdmp:random|xdmp:quote|xdmp:query-trace|xdmp:query-meters|xdmp:product-edition|xdmp:privilege-roles|xdmp:privilege|xdmp:pretty-print|xdmp:powerpoint-convert|xdmp:platform|xdmp:permission|xdmp:pdf-convert|xdmp:path|xdmp:octal-to-integer|xdmp:node-uri|xdmp:node-replace|xdmp:node-kind|xdmp:node-insert-child|xdmp:node-insert-before|xdmp:node-insert-after|xdmp:node-delete|xdmp:node-database|xdmp:mul64|xdmp:modules-root|xdmp:modules-database|xdmp:merging|xdmp:merge-cancel|xdmp:merge|xdmp:md5|xdmp:logout|xdmp:login|xdmp:log-level|xdmp:log|xdmp:lock-release|xdmp:lock-acquire|xdmp:load|xdmp:invoke-in|xdmp:invoke|xdmp:integer-to-octal|xdmp:integer-to-hex|xdmp:http-put|xdmp:http-post|xdmp:http-options|xdmp:http-head|xdmp:http-get|xdmp:http-delete|xdmp:hosts|xdmp:host-status|xdmp:host-name|xdmp:host|xdmp:hex-to-integer|xdmp:hash64|xdmp:hash32|xdmp:has-privilege|xdmp:groups|xdmp:group-serves|xdmp:group-servers|xdmp:group-name|xdmp:group-hosts|xdmp:group|xdmp:get-session-field-names|xdmp:get-session-field|xdmp:get-response-encoding|xdmp:get-response-code|xdmp:get-request-username|xdmp:get-request-user|xdmp:get-request-url|xdmp:get-request-protocol|xdmp:get-request-path|xdmp:get-request-method|xdmp:get-request-header-names|xdmp:get-request-header|xdmp:get-request-field-names|xdmp:get-request-field-filename|xdmp:get-request-field-content-type|xdmp:get-request-field|xdmp:get-request-client-certificate|xdmp:get-request-client-address|xdmp:get-request-body|xdmp:get-current-user|xdmp:get-current-roles|xdmp:get|xdmp:function-name|xdmp:function-module|xdmp:function|xdmp:from-json|xdmp:forests|xdmp:forest-status|xdmp:forest-restore|xdmp:forest-restart|xdmp:forest-name|xdmp:forest-delete|xdmp:forest-databases|xdmp:forest-counts|xdmp:forest-clear|xdmp:forest-backup|xdmp:forest|xdmp:filesystem-file|xdmp:filesystem-directory|xdmp:exists|xdmp:excel-convert|xdmp:eval-in|xdmp:eval|xdmp:estimate|xdmp:email|xdmp:element-content-type|xdmp:elapsed-time|xdmp:document-set-quality|xdmp:document-set-property|xdmp:document-set-properties|xdmp:document-set-permissions|xdmp:document-set-collections|xdmp:document-remove-properties|xdmp:document-remove-permissions|xdmp:document-remove-collections|xdmp:document-properties|xdmp:document-locks|xdmp:document-load|xdmp:document-insert|xdmp:document-get-quality|xdmp:document-get-properties|xdmp:document-get-permissions|xdmp:document-get-collections|xdmp:document-get|xdmp:document-forest|xdmp:document-delete|xdmp:document-add-properties|xdmp:document-add-permissions|xdmp:document-add-collections|xdmp:directory-properties|xdmp:directory-locks|xdmp:directory-delete|xdmp:directory-create|xdmp:directory|xdmp:diacritic-less|xdmp:describe|xdmp:default-permissions|xdmp:default-collections|xdmp:databases|xdmp:database-restore-validate|xdmp:database-restore-status|xdmp:database-restore-cancel|xdmp:database-restore|xdmp:database-name|xdmp:database-forests|xdmp:database-backup-validate|xdmp:database-backup-status|xdmp:database-backup-purge|xdmp:database-backup-cancel|xdmp:database-backup|xdmp:database|xdmp:collection-properties|xdmp:collection-locks|xdmp:collection-delete|xdmp:collation-canonical-uri|xdmp:castable-as|xdmp:can-grant-roles|xdmp:base64-encode|xdmp:base64-decode|xdmp:architecture|xdmp:apply|xdmp:amp-roles|xdmp:amp|xdmp:add64|xdmp:add-response-header|xdmp:access|trgr:trigger-set-recursive|trgr:trigger-set-permissions|trgr:trigger-set-name|trgr:trigger-set-module|trgr:trigger-set-event|trgr:trigger-set-description|trgr:trigger-remove-permissions|trgr:trigger-module|trgr:trigger-get-permissions|trgr:trigger-enable|trgr:trigger-disable|trgr:trigger-database-online-event|trgr:trigger-data-event|trgr:trigger-add-permissions|trgr:remove-trigger|trgr:property-content|trgr:pre-commit|trgr:post-commit|trgr:get-trigger-by-id|trgr:get-trigger|trgr:document-scope|trgr:document-content|trgr:directory-scope|trgr:create-trigger|trgr:collection-scope|trgr:any-property-content|thsr:set-entry|thsr:remove-term|thsr:remove-synonym|thsr:remove-entry|thsr:query-lookup|thsr:lookup|thsr:load|thsr:insert|thsr:expand|thsr:add-synonym|spell:suggest-detailed|spell:suggest|spell:remove-word|spell:make-dictionary|spell:load|spell:levenshtein-distance|spell:is-correct|spell:insert|spell:double-metaphone|spell:add-word|sec:users-collection|sec:user-set-roles|sec:user-set-password|sec:user-set-name|sec:user-set-description|sec:user-set-default-permissions|sec:user-set-default-collections|sec:user-remove-roles|sec:user-privileges|sec:user-get-roles|sec:user-get-description|sec:user-get-default-permissions|sec:user-get-default-collections|sec:user-doc-permissions|sec:user-doc-collections|sec:user-add-roles|sec:unprotect-collection|sec:uid-for-name|sec:set-realm|sec:security-version|sec:security-namespace|sec:security-installed|sec:security-collection|sec:roles-collection|sec:role-set-roles|sec:role-set-name|sec:role-set-description|sec:role-set-default-permissions|sec:role-set-default-collections|sec:role-remove-roles|sec:role-privileges|sec:role-get-roles|sec:role-get-description|sec:role-get-default-permissions|sec:role-get-default-collections|sec:role-doc-permissions|sec:role-doc-collections|sec:role-add-roles|sec:remove-user|sec:remove-role-from-users|sec:remove-role-from-role|sec:remove-role-from-privileges|sec:remove-role-from-amps|sec:remove-role|sec:remove-privilege|sec:remove-amp|sec:protect-collection|sec:privileges-collection|sec:privilege-set-roles|sec:privilege-set-name|sec:privilege-remove-roles|sec:privilege-get-roles|sec:privilege-add-roles|sec:priv-doc-permissions|sec:priv-doc-collections|sec:get-user-names|sec:get-unique-elem-id|sec:get-role-names|sec:get-role-ids|sec:get-privilege|sec:get-distinct-permissions|sec:get-collection|sec:get-amp|sec:create-user-with-role|sec:create-user|sec:create-role|sec:create-privilege|sec:create-amp|sec:collections-collection|sec:collection-set-permissions|sec:collection-remove-permissions|sec:collection-get-permissions|sec:collection-add-permissions|sec:check-admin|sec:amps-collection|sec:amp-set-roles|sec:amp-remove-roles|sec:amp-get-roles|sec:amp-doc-permissions|sec:amp-doc-collections|sec:amp-add-roles|search:unparse|search:suggest|search:snippet|search:search|search:resolve-nodes|search:resolve|search:remove-constraint|search:parse|search:get-default-options|search:estimate|search:check-options|prof:value|prof:reset|prof:report|prof:invoke|prof:eval|prof:enable|prof:disable|prof:allowed|ppt:clean|pki:template-set-request|pki:template-set-name|pki:template-set-key-type|pki:template-set-key-options|pki:template-set-description|pki:template-in-use|pki:template-get-version|pki:template-get-request|pki:template-get-name|pki:template-get-key-type|pki:template-get-key-options|pki:template-get-id|pki:template-get-description|pki:need-certificate|pki:is-temporary|pki:insert-trusted-certificates|pki:insert-template|pki:insert-signed-certificates|pki:insert-certificate-revocation-list|pki:get-trusted-certificate-ids|pki:get-template-ids|pki:get-template-certificate-authority|pki:get-template-by-name|pki:get-template|pki:get-pending-certificate-requests-xml|pki:get-pending-certificate-requests-pem|pki:get-pending-certificate-request|pki:get-certificates-for-template-xml|pki:get-certificates-for-template|pki:get-certificates|pki:get-certificate-xml|pki:get-certificate-pem|pki:get-certificate|pki:generate-temporary-certificate-if-necessary|pki:generate-temporary-certificate|pki:generate-template-certificate-authority|pki:generate-certificate-request|pki:delete-template|pki:delete-certificate|pki:create-template|pdf:make-toc|pdf:insert-toc-headers|pdf:get-toc|pdf:clean|p:status-transition|p:state-transition|p:remove|p:pipelines|p:insert|p:get-by-id|p:get|p:execute|p:create|p:condition|p:collection|p:action|ooxml:runs-merge|ooxml:package-uris|ooxml:package-parts-insert|ooxml:package-parts|msword:clean|mcgm:polygon|mcgm:point|mcgm:geospatial-query-from-elements|mcgm:geospatial-query|mcgm:circle|math:tanh|math:tan|math:sqrt|math:sinh|math:sin|math:pow|math:modf|math:log10|math:log|math:ldexp|math:frexp|math:fmod|math:floor|math:fabs|math:exp|math:cosh|math:cos|math:ceil|math:atan2|math:atan|math:asin|math:acos|map:put|map:map|map:keys|map:get|map:delete|map:count|map:clear|lnk:to|lnk:remove|lnk:insert|lnk:get|lnk:from|lnk:create|kml:polygon|kml:point|kml:interior-polygon|kml:geospatial-query-from-elements|kml:geospatial-query|kml:circle|kml:box|gml:polygon|gml:point|gml:interior-polygon|gml:geospatial-query-from-elements|gml:geospatial-query|gml:circle|gml:box|georss:point|georss:geospatial-query|georss:circle|geo:polygon|geo:point|geo:interior-polygon|geo:geospatial-query-from-elements|geo:geospatial-query|geo:circle|geo:box|fn:zero-or-one|fn:years-from-duration|fn:year-from-dateTime|fn:year-from-date|fn:upper-case|fn:unordered|fn:true|fn:translate|fn:trace|fn:tokenize|fn:timezone-from-time|fn:timezone-from-dateTime|fn:timezone-from-date|fn:sum|fn:subtract-dateTimes-yielding-yearMonthDuration|fn:subtract-dateTimes-yielding-dayTimeDuration|fn:substring-before|fn:substring-after|fn:substring|fn:subsequence|fn:string-to-codepoints|fn:string-pad|fn:string-length|fn:string-join|fn:string|fn:static-base-uri|fn:starts-with|fn:seconds-from-time|fn:seconds-from-duration|fn:seconds-from-dateTime|fn:round-half-to-even|fn:round|fn:root|fn:reverse|fn:resolve-uri|fn:resolve-QName|fn:replace|fn:remove|fn:QName|fn:prefix-from-QName|fn:position|fn:one-or-more|fn:number|fn:not|fn:normalize-unicode|fn:normalize-space|fn:node-name|fn:node-kind|fn:nilled|fn:namespace-uri-from-QName|fn:namespace-uri-for-prefix|fn:namespace-uri|fn:name|fn:months-from-duration|fn:month-from-dateTime|fn:month-from-date|fn:minutes-from-time|fn:minutes-from-duration|fn:minutes-from-dateTime|fn:min|fn:max|fn:matches|fn:lower-case|fn:local-name-from-QName|fn:local-name|fn:last|fn:lang|fn:iri-to-uri|fn:insert-before|fn:index-of|fn:in-scope-prefixes|fn:implicit-timezone|fn:idref|fn:id|fn:hours-from-time|fn:hours-from-duration|fn:hours-from-dateTime|fn:floor|fn:false|fn:expanded-QName|fn:exists|fn:exactly-one|fn:escape-uri|fn:escape-html-uri|fn:error|fn:ends-with|fn:encode-for-uri|fn:empty|fn:document-uri|fn:doc-available|fn:doc|fn:distinct-values|fn:distinct-nodes|fn:default-collation|fn:deep-equal|fn:days-from-duration|fn:day-from-dateTime|fn:day-from-date|fn:data|fn:current-time|fn:current-dateTime|fn:current-date|fn:count|fn:contains|fn:concat|fn:compare|fn:collection|fn:codepoints-to-string|fn:codepoint-equal|fn:ceiling|fn:boolean|fn:base-uri|fn:avg|fn:adjust-time-to-timezone|fn:adjust-dateTime-to-timezone|fn:adjust-date-to-timezone|fn:abs|feed:unsubscribe|feed:subscription|feed:subscribe|feed:request|feed:item|feed:description|excel:clean|entity:enrich|dom:set-pipelines|dom:set-permissions|dom:set-name|dom:set-evaluation-context|dom:set-domain-scope|dom:set-description|dom:remove-pipeline|dom:remove-permissions|dom:remove|dom:get|dom:evaluation-context|dom:domains|dom:domain-scope|dom:create|dom:configuration-set-restart-user|dom:configuration-set-permissions|dom:configuration-set-evaluation-context|dom:configuration-set-default-domain|dom:configuration-get|dom:configuration-create|dom:collection|dom:add-pipeline|dom:add-permissions|dls:retention-rules|dls:retention-rule-remove|dls:retention-rule-insert|dls:retention-rule|dls:purge|dls:node-expand|dls:link-references|dls:link-expand|dls:documents-query|dls:document-versions-query|dls:document-version-uri|dls:document-version-query|dls:document-version-delete|dls:document-version-as-of|dls:document-version|dls:document-update|dls:document-unmanage|dls:document-set-quality|dls:document-set-property|dls:document-set-properties|dls:document-set-permissions|dls:document-set-collections|dls:document-retention-rules|dls:document-remove-properties|dls:document-remove-permissions|dls:document-remove-collections|dls:document-purge|dls:document-manage|dls:document-is-managed|dls:document-insert-and-manage|dls:document-include-query|dls:document-history|dls:document-get-permissions|dls:document-extract-part|dls:document-delete|dls:document-checkout-status|dls:document-checkout|dls:document-checkin|dls:document-add-properties|dls:document-add-permissions|dls:document-add-collections|dls:break-checkout|dls:author-query|dls:as-of-query|dbk:convert|dbg:wait|dbg:value|dbg:stopped|dbg:stop|dbg:step|dbg:status|dbg:stack|dbg:out|dbg:next|dbg:line|dbg:invoke|dbg:function|dbg:finish|dbg:expr|dbg:eval|dbg:disconnect|dbg:detach|dbg:continue|dbg:connect|dbg:clear|dbg:breakpoints|dbg:break|dbg:attached|dbg:attach|cvt:save-converted-documents|cvt:part-uri|cvt:destination-uri|cvt:basepath|cvt:basename|cts:words|cts:word-query-weight|cts:word-query-text|cts:word-query-options|cts:word-query|cts:word-match|cts:walk|cts:uris|cts:uri-match|cts:train|cts:tokenize|cts:thresholds|cts:stem|cts:similar-query-weight|cts:similar-query-nodes|cts:similar-query|cts:shortest-distance|cts:search|cts:score|cts:reverse-query-weight|cts:reverse-query-nodes|cts:reverse-query|cts:remainder|cts:registered-query-weight|cts:registered-query-options|cts:registered-query-ids|cts:registered-query|cts:register|cts:query|cts:quality|cts:properties-query-query|cts:properties-query|cts:polygon-vertices|cts:polygon|cts:point-longitude|cts:point-latitude|cts:point|cts:or-query-queries|cts:or-query|cts:not-query-weight|cts:not-query-query|cts:not-query|cts:near-query-weight|cts:near-query-queries|cts:near-query-options|cts:near-query-distance|cts:near-query|cts:highlight|cts:geospatial-co-occurrences|cts:frequency|cts:fitness|cts:field-words|cts:field-word-query-weight|cts:field-word-query-text|cts:field-word-query-options|cts:field-word-query-field-name|cts:field-word-query|cts:field-word-match|cts:entity-highlight|cts:element-words|cts:element-word-query-weight|cts:element-word-query-text|cts:element-word-query-options|cts:element-word-query-element-name|cts:element-word-query|cts:element-word-match|cts:element-values|cts:element-value-ranges|cts:element-value-query-weight|cts:element-value-query-text|cts:element-value-query-options|cts:element-value-query-element-name|cts:element-value-query|cts:element-value-match|cts:element-value-geospatial-co-occurrences|cts:element-value-co-occurrences|cts:element-range-query-weight|cts:element-range-query-value|cts:element-range-query-options|cts:element-range-query-operator|cts:element-range-query-element-name|cts:element-range-query|cts:element-query-query|cts:element-query-element-name|cts:element-query|cts:element-pair-geospatial-values|cts:element-pair-geospatial-value-match|cts:element-pair-geospatial-query-weight|cts:element-pair-geospatial-query-region|cts:element-pair-geospatial-query-options|cts:element-pair-geospatial-query-longitude-name|cts:element-pair-geospatial-query-latitude-name|cts:element-pair-geospatial-query-element-name|cts:element-pair-geospatial-query|cts:element-pair-geospatial-boxes|cts:element-geospatial-values|cts:element-geospatial-value-match|cts:element-geospatial-query-weight|cts:element-geospatial-query-region|cts:element-geospatial-query-options|cts:element-geospatial-query-element-name|cts:element-geospatial-query|cts:element-geospatial-boxes|cts:element-child-geospatial-values|cts:element-child-geospatial-value-match|cts:element-child-geospatial-query-weight|cts:element-child-geospatial-query-region|cts:element-child-geospatial-query-options|cts:element-child-geospatial-query-element-name|cts:element-child-geospatial-query-child-name|cts:element-child-geospatial-query|cts:element-child-geospatial-boxes|cts:element-attribute-words|cts:element-attribute-word-query-weight|cts:element-attribute-word-query-text|cts:element-attribute-word-query-options|cts:element-attribute-word-query-element-name|cts:element-attribute-word-query-attribute-name|cts:element-attribute-word-query|cts:element-attribute-word-match|cts:element-attribute-values|cts:element-attribute-value-ranges|cts:element-attribute-value-query-weight|cts:element-attribute-value-query-text|cts:element-attribute-value-query-options|cts:element-attribute-value-query-element-name|cts:element-attribute-value-query-attribute-name|cts:element-attribute-value-query|cts:element-attribute-value-match|cts:element-attribute-value-geospatial-co-occurrences|cts:element-attribute-value-co-occurrences|cts:element-attribute-range-query-weight|cts:element-attribute-range-query-value|cts:element-attribute-range-query-options|cts:element-attribute-range-query-operator|cts:element-attribute-range-query-element-name|cts:element-attribute-range-query-attribute-name|cts:element-attribute-range-query|cts:element-attribute-pair-geospatial-values|cts:element-attribute-pair-geospatial-value-match|cts:element-attribute-pair-geospatial-query-weight|cts:element-attribute-pair-geospatial-query-region|cts:element-attribute-pair-geospatial-query-options|cts:element-attribute-pair-geospatial-query-longitude-name|cts:element-attribute-pair-geospatial-query-latitude-name|cts:element-attribute-pair-geospatial-query-element-name|cts:element-attribute-pair-geospatial-query|cts:element-attribute-pair-geospatial-boxes|cts:document-query-uris|cts:document-query|cts:distance|cts:directory-query-uris|cts:directory-query-depth|cts:directory-query|cts:destination|cts:deregister|cts:contains|cts:confidence|cts:collections|cts:collection-query-uris|cts:collection-query|cts:collection-match|cts:classify|cts:circle-radius|cts:circle-center|cts:circle|cts:box-west|cts:box-south|cts:box-north|cts:box-east|cts:box|cts:bearing|cts:arc-intersection|cts:and-query-queries|cts:and-query-options|cts:and-query|cts:and-not-query-positive-query|cts:and-not-query-negative-query|cts:and-not-query|css:get|css:convert|cpf:success|cpf:failure|cpf:document-set-state|cpf:document-set-processing-status|cpf:document-set-last-updated|cpf:document-set-error|cpf:document-get-state|cpf:document-get-processing-status|cpf:document-get-last-updated|cpf:document-get-error|cpf:check-transition|alert:spawn-matching-actions|alert:rule-user-id-query|alert:rule-set-user-id|alert:rule-set-query|alert:rule-set-options|alert:rule-set-name|alert:rule-set-description|alert:rule-set-action|alert:rule-remove|alert:rule-name-query|alert:rule-insert|alert:rule-id-query|alert:rule-get-user-id|alert:rule-get-query|alert:rule-get-options|alert:rule-get-name|alert:rule-get-id|alert:rule-get-description|alert:rule-get-action|alert:rule-action-query|alert:remove-triggers|alert:make-rule|alert:make-log-action|alert:make-config|alert:make-action|alert:invoke-matching-actions|alert:get-my-rules|alert:get-all-rules|alert:get-actions|alert:find-matching-rules|alert:create-triggers|alert:config-set-uri|alert:config-set-trigger-ids|alert:config-set-options|alert:config-set-name|alert:config-set-description|alert:config-set-cpf-domain-names|alert:config-set-cpf-domain-ids|alert:config-insert|alert:config-get-uri|alert:config-get-trigger-ids|alert:config-get-options|alert:config-get-name|alert:config-get-id|alert:config-get-description|alert:config-get-cpf-domain-names|alert:config-get-cpf-domain-ids|alert:config-get|alert:config-delete|alert:action-set-options|alert:action-set-name|alert:action-set-module-root|alert:action-set-module-db|alert:action-set-module|alert:action-set-description|alert:action-remove|alert:action-insert|alert:action-get-options|alert:action-get-name|alert:action-get-module-root|alert:action-get-module-db|alert:action-get-module|alert:action-get-description|zero-or-one|years-from-duration|year-from-dateTime|year-from-date|upper-case|unordered|true|translate|trace|tokenize|timezone-from-time|timezone-from-dateTime|timezone-from-date|sum|subtract-dateTimes-yielding-yearMonthDuration|subtract-dateTimes-yielding-dayTimeDuration|substring-before|substring-after|substring|subsequence|string-to-codepoints|string-pad|string-length|string-join|string|static-base-uri|starts-with|seconds-from-time|seconds-from-duration|seconds-from-dateTime|round-half-to-even|round|root|reverse|resolve-uri|resolve-QName|replace|remove|QName|prefix-from-QName|position|one-or-more|number|not|normalize-unicode|normalize-space|node-name|node-kind|nilled|namespace-uri-from-QName|namespace-uri-for-prefix|namespace-uri|name|months-from-duration|month-from-dateTime|month-from-date|minutes-from-time|minutes-from-duration|minutes-from-dateTime|min|max|matches|lower-case|local-name-from-QName|local-name|last|lang|iri-to-uri|insert-before|index-of|in-scope-prefixes|implicit-timezone|idref|id|hours-from-time|hours-from-duration|hours-from-dateTime|floor|false|expanded-QName|exists|exactly-one|escape-uri|escape-html-uri|error|ends-with|encode-for-uri|empty|document-uri|doc-available|doc|distinct-values|distinct-nodes|default-collation|deep-equal|days-from-duration|day-from-dateTime|day-from-date|data|current-time|current-dateTime|current-date|count|contains|concat|compare|collection|codepoints-to-string|codepoint-equal|ceiling|boolean|base-uri|avg|adjust-time-to-timezone|adjust-dateTime-to-timezone|adjust-date-to-timezone|abs)\b/], ["pln",/^[\w:-]+/],["pln",/^[\t\n\r \xa0]+/]]),["xq","xquery"]); ================================================ FILE: public/packages/google-code-prettify/lang-yaml.js ================================================ var a=null; PR.registerLangHandler(PR.createSimpleLexer([["pun",/^[:>?|]+/,a,":|>?"],["dec",/^%(?:YAML|TAG)[^\n\r#]+/,a,"%"],["typ",/^&\S+/,a,"&"],["typ",/^!\S*/,a,"!"],["str",/^"(?:[^"\\]|\\.)*(?:"|$)/,a,'"'],["str",/^'(?:[^']|'')*(?:'|$)/,a,"'"],["com",/^#[^\n\r]*/,a,"#"],["pln",/^\s+/,a," \t\r\n"]],[["dec",/^(?:---|\.\.\.)(?:[\n\r]|$)/],["pun",/^-/],["kwd",/^\w+:[\n\r ]/],["pln",/^\w+/]]),["yaml","yml"]); ================================================ FILE: public/packages/google-code-prettify/prettify.css ================================================ .pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} ================================================ FILE: public/packages/google-code-prettify/prettify.js ================================================ !function(){var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; (function(){function S(a){function d(e){var b=e.charCodeAt(0);if(b!==92)return b;var a=e.charAt(1);return(b=r[a])?b:"0"<=a&&a<="7"?parseInt(e.substring(1),8):a==="u"||a==="x"?parseInt(e.substring(2),16):e.charCodeAt(1)}function g(e){if(e<32)return(e<16?"\\x0":"\\x")+e.toString(16);e=String.fromCharCode(e);return e==="\\"||e==="-"||e==="]"||e==="^"?"\\"+e:e}function b(e){var b=e.substring(1,e.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),e=[],a= b[0]==="^",c=["["];a&&c.push("^");for(var a=a?1:0,f=b.length;a122||(l<65||h>90||e.push([Math.max(65,h)|32,Math.min(l,90)|32]),l<97||h>122||e.push([Math.max(97,h)&-33,Math.min(l,122)&-33]))}}e.sort(function(e,a){return e[0]-a[0]||a[1]-e[1]});b=[];f=[];for(a=0;ah[0]&&(h[1]+1>h[0]&&c.push("-"),c.push(g(h[1])));c.push("]");return c.join("")}function s(e){for(var a=e.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),c=a.length,d=[],f=0,h=0;f=2&&e==="["?a[f]=b(l):e!=="\\"&&(a[f]=l.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return a.join("")}for(var x=0,m=!1,j=!1,k=0,c=a.length;k=5&&"lang-"===w.substring(0,5))&&!(t&&typeof t[1]==="string"))f=!1,w="src";f||(r[z]=w)}h=c;c+=z.length;if(f){f=t[1];var l=z.indexOf(f),B=l+f.length;t[2]&&(B=z.length-t[2].length,l=B-f.length);w=w.substring(5);H(j+h,z.substring(0,l),g,k);H(j+h+l,f,I(w,f),k);H(j+h+B,z.substring(B),g,k)}else k.push(j+h,w)}a.g=k}var b={},s;(function(){for(var g=a.concat(d),j=[],k={},c=0,i=g.length;c=0;)b[n.charAt(e)]=r;r=r[1];n=""+r;k.hasOwnProperty(n)||(j.push(r),k[n]=q)}j.push(/[\S\s]/);s=S(j)})();var x=d.length;return g}function v(a){var d=[],g=[];a.tripleQuotedStrings?d.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?d.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, q,"'\"`"]):d.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&g.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var b=a.hashComments;b&&(a.cStyleComments?(b>1?d.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):d.push(["com",/^#(?:(?:define|e(?:l|nd)if|else|error|ifn?def|include|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),g.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/,q])):d.push(["com", /^#[^\n\r]*/,q,"#"]));a.cStyleComments&&(g.push(["com",/^\/\/[^\n\r]*/,q]),g.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));if(b=a.regexLiterals){var s=(b=b>1?"":"\n\r")?".":"[\\S\\s]";g.push(["lang-regex",RegExp("^(?:^^\\.?|[+-]|[!=]=?=?|\\#|%=?|&&?=?|\\(|\\*=?|[+\\-]=|->|\\/=?|::?|<>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*("+("/(?=[^/*"+b+"])(?:[^/\\x5B\\x5C"+b+"]|\\x5C"+s+"|\\x5B(?:[^\\x5C\\x5D"+b+"]|\\x5C"+ s+")*(?:\\x5D|$))+/")+")")])}(b=a.types)&&g.push(["typ",b]);b=(""+a.keywords).replace(/^ | $/g,"");b.length&&g.push(["kwd",RegExp("^(?:"+b.replace(/[\s,]+/g,"|")+")\\b"),q]);d.push(["pln",/^\s+/,q," \r\n\t\u00a0"]);b="^.[^\\s\\w.$@'\"`/\\\\]*";a.regexLiterals&&(b+="(?!s*/)");g.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/, q],["pun",RegExp(b),q]);return C(d,g)}function J(a,d,g){function b(a){var c=a.nodeType;if(c==1&&!x.test(a.className))if("br"===a.nodeName)s(a),a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)b(a);else if((c==3||c==4)&&g){var d=a.nodeValue,i=d.match(m);if(i)c=d.substring(0,i.index),a.nodeValue=c,(d=d.substring(i.index+i[0].length))&&a.parentNode.insertBefore(j.createTextNode(d),a.nextSibling),s(a),c||a.parentNode.removeChild(a)}}function s(a){function b(a,c){var d= c?a.cloneNode(!1):a,e=a.parentNode;if(e){var e=b(e,1),g=a.nextSibling;e.appendChild(d);for(var i=g;i;i=g)g=i.nextSibling,e.appendChild(i)}return d}for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),d;(d=a.parentNode)&&d.nodeType===1;)a=d;c.push(a)}for(var x=/(?:^|\s)nocode(?:\s|$)/,m=/\r\n?|\n/,j=a.ownerDocument,k=j.createElement("li");a.firstChild;)k.appendChild(a.firstChild);for(var c=[k],i=0;i=0;){var b=d[g];F.hasOwnProperty(b)?D.console&&console.warn("cannot override language handler %s",b):F[b]=a}}function I(a,d){if(!a||!F.hasOwnProperty(a))a=/^\s*=l&&(b+=2);g>=B&&(r+=2)}}finally{if(f)f.style.display=h}}catch(u){D.console&&console.log(u&&u.stack||u)}}var D=window,y=["break,continue,do,else,for,if,return,while"],E=[[y,"auto,case,char,const,default,double,enum,extern,float,goto,inline,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],M=[E,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,delegate,dynamic_cast,explicit,export,friend,generic,late_check,mutable,namespace,nullptr,property,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],N=[E,"abstract,assert,boolean,byte,extends,final,finally,implements,import,instanceof,interface,null,native,package,strictfp,super,synchronized,throws,transient"], O=[N,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,internal,into,is,let,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var,virtual,where"],E=[E,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],P=[y,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], Q=[y,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],W=[y,"as,assert,const,copy,drop,enum,extern,fail,false,fn,impl,let,log,loop,match,mod,move,mut,priv,pub,pure,ref,self,static,struct,true,trait,type,unsafe,use"],y=[y,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],R=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)\b/, V=/\S/,X=v({keywords:[M,O,E,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",P,Q,y],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),F={};p(X,["default-code"]);p(C([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-", /^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);p(C([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/], ["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css",/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);p(C([],[["atv",/^[\S\s]+/]]),["uq.val"]);p(v({keywords:M,hashComments:!0,cStyleComments:!0,types:R}),["c","cc","cpp","cxx","cyc","m"]);p(v({keywords:"null,true,false"}),["json"]);p(v({keywords:O,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:R}), ["cs"]);p(v({keywords:N,cStyleComments:!0}),["java"]);p(v({keywords:y,hashComments:!0,multiLineStrings:!0}),["bash","bsh","csh","sh"]);p(v({keywords:P,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),["cv","py","python"]);p(v({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:2}),["perl","pl","pm"]);p(v({keywords:Q, hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb","ruby"]);p(v({keywords:E,cStyleComments:!0,regexLiterals:!0}),["javascript","js"]);p(v({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,throw,true,try,unless,until,when,while,yes",hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);p(v({keywords:W,cStyleComments:!0,multilineStrings:!0}),["rc","rs","rust"]); p(C([],[["str",/^[\S\s]+/]]),["regex"]);var Y=D.PR={createSimpleLexer:C,registerLangHandler:p,sourceDecorator:v,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit",PR_NOCODE:"nocode",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ",prettyPrintOne:D.prettyPrintOne=function(a,d,g){var b=document.createElement("div");b.innerHTML="
            "+a+"
            ";b=b.firstChild;g&&J(b,g,!0);K({h:d,j:g,c:b,i:1}); return b.innerHTML},prettyPrint:D.prettyPrint=function(a,d){function g(){for(var b=D.PR_SHOULD_USE_CONTINUATION?c.now()+250:Infinity;i=0;){var M=A[m],T=M.src.match(/^[^#?]*\/run_prettify\.js(\?[^#]*)?(?:#.*)?$/);if(T){z=T[1]||"";M.parentNode.removeChild(M);break}}var S=!0,D= [],N=[],K=[];z.replace(/[&?]([^&=]+)=([^&]+)/g,function(e,j,w){w=decodeURIComponent(w);j=decodeURIComponent(j);j=="autorun"?S=!/^[0fn]/i.test(w):j=="lang"?D.push(w):j=="skin"?N.push(w):j=="callback"&&K.push(w)});m=0;for(z=D.length;m122||(o<65||k>90||f.push([Math.max(65,k)|32,Math.min(o,90)|32]),o<97||k>122||f.push([Math.max(97,k)&-33,Math.min(o,122)&-33]))}}f.sort(function(f,a){return f[0]- a[0]||a[1]-f[1]});b=[];g=[];for(a=0;ak[0]&&(k[1]+1>k[0]&&c.push("-"),c.push(h(k[1])));c.push("]");return c.join("")}function e(f){for(var a=f.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),c=a.length,d=[],g=0,k=0;g=2&&f==="["?a[g]=b(o):f!=="\\"&&(a[g]=o.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return a.join("")}for(var j=0,F=!1,l=!1,I=0,c=a.length;I=5&&"lang-"===y.substring(0,5))&&!(u&&typeof u[1]==="string"))g=!1,y="src";g||(m[B]=y)}k=c;c+=B.length;if(g){g=u[1];var o=B.indexOf(g),H=o+g.length;u[2]&&(H=B.length-u[2].length,o=H-g.length);y=y.substring(5);n(l+k,B.substring(0,o),h,j);n(l+k+o,g,A(y, g),j);n(l+k+H,B.substring(H),h,j)}else j.push(l+k,y)}a.g=j}var b={},e;(function(){for(var h=a.concat(d),l=[],i={},c=0,p=h.length;c=0;)b[q.charAt(f)]=m;m=m[1];q=""+m;i.hasOwnProperty(q)||(l.push(m),i[q]=r)}l.push(/[\S\s]/);e=j(l)})();var i=d.length;return h}function t(a){var d=[],h=[];a.tripleQuotedStrings?d.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/, r,"'\""]):a.multiLineStrings?d.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,r,"'\"`"]):d.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,r,"\"'"]);a.verbatimStrings&&h.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,r]);var b=a.hashComments;b&&(a.cStyleComments?(b>1?d.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,r,"#"]):d.push(["com",/^#(?:(?:define|e(?:l|nd)if|else|error|ifn?def|include|line|pragma|undef|warning)\b|[^\n\r]*)/, r,"#"]),h.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/,r])):d.push(["com",/^#[^\n\r]*/,r,"#"]));a.cStyleComments&&(h.push(["com",/^\/\/[^\n\r]*/,r]),h.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,r]));if(b=a.regexLiterals){var e=(b=b>1?"":"\n\r")?".":"[\\S\\s]";h.push(["lang-regex",RegExp("^(?:^^\\.?|[+-]|[!=]=?=?|\\#|%=?|&&?=?|\\(|\\*=?|[+\\-]=|->|\\/=?|::?|<>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*("+ ("/(?=[^/*"+b+"])(?:[^/\\x5B\\x5C"+b+"]|\\x5C"+e+"|\\x5B(?:[^\\x5C\\x5D"+b+"]|\\x5C"+e+")*(?:\\x5D|$))+/")+")")])}(b=a.types)&&h.push(["typ",b]);b=(""+a.keywords).replace(/^ | $/g,"");b.length&&h.push(["kwd",RegExp("^(?:"+b.replace(/[\s,]+/g,"|")+")\\b"),r]);d.push(["pln",/^\s+/,r," \r\n\t\u00a0"]);b="^.[^\\s\\w.$@'\"`/\\\\]*";a.regexLiterals&&(b+="(?!s*/)");h.push(["lit",/^@[$_a-z][\w$@]*/i,r],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,r],["pln",/^[$_a-z][\w$@]*/i,r],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i, r,"0123456789"],["pln",/^\\[\S\s]?/,r],["pun",RegExp(b),r]);return C(d,h)}function z(a,d,h){function b(a){var c=a.nodeType;if(c==1&&!j.test(a.className))if("br"===a.nodeName)e(a),a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)b(a);else if((c==3||c==4)&&h){var d=a.nodeValue,i=d.match(m);if(i)c=d.substring(0,i.index),a.nodeValue=c,(d=d.substring(i.index+i[0].length))&&a.parentNode.insertBefore(l.createTextNode(d),a.nextSibling),e(a),c||a.parentNode.removeChild(a)}} function e(a){function b(a,c){var d=c?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),h=a.nextSibling;f.appendChild(d);for(var e=h;e;e=h)h=e.nextSibling,f.appendChild(e)}return d}for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),d;(d=a.parentNode)&&d.nodeType===1;)a=d;c.push(a)}for(var j=/(?:^|\s)nocode(?:\s|$)/,m=/\r\n?|\n/,l=a.ownerDocument,i=l.createElement("li");a.firstChild;)i.appendChild(a.firstChild);for(var c=[i],p=0;p=0;){var b=d[h];U.hasOwnProperty(b)?V.console&&console.warn("cannot override language handler %s",b):U[b]=a}}function A(a,d){if(!a||!U.hasOwnProperty(a))a=/^\s*=o&&(b+=2);h>=H&&(t+=2)}}finally{if(g)g.style.display=k}}catch(v){V.console&&console.log(v&&v.stack||v)}}var V=window,G=["break,continue,do,else,for,if,return,while"],O=[[G,"auto,case,char,const,default,double,enum,extern,float,goto,inline,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],J=[O,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,delegate,dynamic_cast,explicit,export,friend,generic,late_check,mutable,namespace,nullptr,property,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],K=[O,"abstract,assert,boolean,byte,extends,final,finally,implements,import,instanceof,interface,null,native,package,strictfp,super,synchronized,throws,transient"], L=[K,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,internal,into,is,let,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var,virtual,where"],O=[O,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],M=[G,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], N=[G,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],R=[G,"as,assert,const,copy,drop,enum,extern,fail,false,fn,impl,let,log,loop,match,mod,move,mut,priv,pub,pure,ref,self,static,struct,true,trait,type,unsafe,use"],G=[G,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],Q=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)\b/, S=/\S/,T=t({keywords:[J,L,O,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",M,N,G],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),U={};i(T,["default-code"]);i(C([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-", /^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);i(C([["pln",/^\s+/,r," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,r,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/], ["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css",/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);i(C([],[["atv",/^[\S\s]+/]]),["uq.val"]);i(t({keywords:J,hashComments:!0,cStyleComments:!0,types:Q}),["c","cc","cpp","cxx","cyc","m"]);i(t({keywords:"null,true,false"}),["json"]);i(t({keywords:L,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:Q}), ["cs"]);i(t({keywords:K,cStyleComments:!0}),["java"]);i(t({keywords:G,hashComments:!0,multiLineStrings:!0}),["bash","bsh","csh","sh"]);i(t({keywords:M,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),["cv","py","python"]);i(t({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:2}),["perl","pl","pm"]);i(t({keywords:N, hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb","ruby"]);i(t({keywords:O,cStyleComments:!0,regexLiterals:!0}),["javascript","js"]);i(t({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,throw,true,try,unless,until,when,while,yes",hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);i(t({keywords:R,cStyleComments:!0,multilineStrings:!0}),["rc","rs","rust"]); i(C([],[["str",/^[\S\s]+/]]),["regex"]);var X=V.PR={createSimpleLexer:C,registerLangHandler:i,sourceDecorator:t,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit",PR_NOCODE:"nocode",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ",prettyPrintOne:function(a,d,e){var b=document.createElement("div");b.innerHTML="
            "+a+"
            ";b=b.firstChild;e&&z(b,e,!0);D({h:d,j:e,c:b,i:1});return b.innerHTML}, prettyPrint:e=e=function(a,d){function e(){for(var b=V.PR_SHOULD_USE_CONTINUATION?c.now()+250:Infinity;p jQuery File Upload Demo - AngularJS version

            jQuery File Upload Demo

            AngularJS version


            File Upload widget with multiple file selection, drag&drop support, progress bars, validation and preview images, audio and video for AngularJS.
            Supports cross-domain, chunked and resumable file uploads and client-side image resizing.
            Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.


            Add files...
             

            {{file.name}} {{file.name}} {{file.name}}

            Error {{file.error}}

            {{file.size | formatFileSize}}


            Demo Notes

            • The maximum file size for uploads in this demo is 5 MB (default file size is unlimited).
            • Only image files (JPG, GIF, PNG) are allowed in this demo (by default there is no file type restriction).
            • Uploaded files will be deleted automatically after 5 minutes (demo setting).
            • You can drag & drop files from your desktop on this webpage (see Browser support).
            • Please refer to the project website and documentation for more information.
            • Built with Twitter's Bootstrap CSS framework and Icons from Glyphicons.
            ================================================ FILE: public/packages/jquery-file-upload-8.9.0/basic-plus.html ================================================ jQuery File Upload Demo - Basic Plus version

            jQuery File Upload Demo

            Basic Plus version


            File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery.
            Supports cross-domain, chunked and resumable file uploads and client-side image resizing.
            Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.


            Add files...


            Demo Notes

            • The maximum file size for uploads in this demo is 5 MB (default file size is unlimited).
            • Only image files (JPG, GIF, PNG) are allowed in this demo (by default there is no file type restriction).
            • Uploaded files will be deleted automatically after 5 minutes (demo setting).
            • You can drag & drop files from your desktop on this webpage (see Browser support).
            • Please refer to the project website and documentation for more information.
            • Built with Twitter's Bootstrap CSS framework and Icons from Glyphicons.
            ================================================ FILE: public/packages/jquery-file-upload-8.9.0/basic.html ================================================ jQuery File Upload Demo - Basic version

            jQuery File Upload Demo

            Basic version


            File Upload widget with multiple file selection, drag&drop support and progress bar for jQuery.
            Supports cross-domain, chunked and resumable file uploads.
            Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.


            Select files...


            Demo Notes

            • The maximum file size for uploads in this demo is 5 MB (default file size is unlimited).
            • Only image files (JPG, GIF, PNG) are allowed in this demo (by default there is no file type restriction).
            • Uploaded files will be deleted automatically after 5 minutes (demo setting).
            • You can drag & drop files from your desktop on this webpage (see Browser support).
            • Please refer to the project website and documentation for more information.
            • Built with Twitter's Bootstrap CSS framework and Icons from Glyphicons.
            ================================================ FILE: public/packages/jquery-file-upload-8.9.0/blueimp-file-upload.jquery.json ================================================ { "name": "blueimp-file-upload", "version": "8.9.0", "title": "jQuery File Upload", "author": { "name": "Sebastian Tschan", "url": "https://blueimp.net" }, "licenses": [ { "type": "MIT", "url": "http://www.opensource.org/licenses/MIT" } ], "dependencies": { "jquery": ">=1.6" }, "description": "File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (Google App Engine, PHP, Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads.", "keywords": [ "jquery", "file", "upload", "widget", "multiple", "selection", "drag", "drop", "progress", "preview", "cross-domain", "cross-site", "chunk", "resume", "gae", "go", "python", "php", "bootstrap" ], "homepage": "https://github.com/blueimp/jQuery-File-Upload", "docs": "https://github.com/blueimp/jQuery-File-Upload/wiki", "demo": "http://blueimp.github.io/jQuery-File-Upload/", "bugs": "https://github.com/blueimp/jQuery-File-Upload/issues", "maintainers": [ { "name": "Sebastian Tschan", "url": "https://blueimp.net" } ] } ================================================ FILE: public/packages/jquery-file-upload-8.9.0/bower.json ================================================ { "name": "blueimp-file-upload", "version": "8.9.0", "title": "jQuery File Upload", "description": "File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (Google App Engine, PHP, Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads.", "keywords": [ "jquery", "file", "upload", "widget", "multiple", "selection", "drag", "drop", "progress", "preview", "cross-domain", "cross-site", "chunk", "resume", "gae", "go", "python", "php", "bootstrap" ], "homepage": "https://github.com/blueimp/jQuery-File-Upload", "author": { "name": "Sebastian Tschan", "url": "https://blueimp.net" }, "maintainers": [ { "name": "Sebastian Tschan", "url": "https://blueimp.net" } ], "repository": { "type": "git", "url": "git://github.com/blueimp/jQuery-File-Upload.git" }, "bugs": "https://github.com/blueimp/jQuery-File-Upload/issues", "licenses": [ { "type": "MIT", "url": "http://www.opensource.org/licenses/MIT" } ], "dependencies": { "jquery": ">=1.6", "blueimp-tmpl": ">=2.3.0", "blueimp-load-image": ">=1.9.1", "blueimp-canvas-to-blob": ">=2.0.7" }, "main": [ "js/vendor/jquery.ui.widget.js", "js/jquery.fileupload-angular.js", "js/jquery.fileupload-audio.js", "js/jquery.fileupload-image.js", "js/jquery.fileupload-process.js", "js/jquery.fileupload-ui.js", "js/jquery.fileupload-validate.js", "js/jquery.fileupload-video.js", "js/jquery.fileupload.js", "js/jquery.iframe-transport.js" ] } ================================================ FILE: public/packages/jquery-file-upload-8.9.0/cors/postmessage.html ================================================ jQuery File Upload Plugin postMessage API ================================================ FILE: public/packages/jquery-file-upload-8.9.0/cors/result.html ================================================ jQuery Iframe Transport Plugin Redirect Page ================================================ FILE: public/packages/jquery-file-upload-8.9.0/css/demo-ie8.css ================================================ @charset "UTF-8"; /* * jQuery File Upload Demo CSS Fixes for IE<9 1.0.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ .navigation { list-style: none; padding: 0; margin: 1em 0; } .navigation li { display: inline; margin-right: 10px; } ================================================ FILE: public/packages/jquery-file-upload-8.9.0/css/demo.css ================================================ @charset "UTF-8"; /* * jQuery File Upload Demo CSS 1.1.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ body { max-width: 750px; margin: 0 auto; padding: 1em; font-family: "Lucida Grande", "Lucida Sans Unicode", Arial, sans-serif; font-size: 1em; line-height: 1.4em; background: #222; color: #fff; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } a { color: orange; text-decoration: none; } img { border: 0; vertical-align: middle; } h1 { line-height: 1em; } blockquote { padding: 0 0 0 15px; margin: 0 0 20px; border-left: 5px solid #eee; } table { width: 100%; margin: 10px 0; } .fileupload-progress { margin: 10px 0; } .fileupload-progress .progress-extended { margin-top: 5px; } .error { color: red; } @media (min-width: 481px) { .navigation { list-style: none; padding: 0; } .navigation li { display: inline-block; } .navigation li:not(:first-child):before { content: "| "; } } ================================================ FILE: public/packages/jquery-file-upload-8.9.0/css/jquery.fileupload-noscript.css ================================================ @charset "UTF-8"; /* * jQuery File Upload Plugin NoScript CSS 1.2.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ .fileinput-button input { position: static; opacity: 1; filter: none; font-size: inherit; direction: inherit; } .fileinput-button span { display: none; } ================================================ FILE: public/packages/jquery-file-upload-8.9.0/css/jquery.fileupload-ui-noscript.css ================================================ @charset "UTF-8"; /* * jQuery File Upload UI Plugin NoScript CSS 8.8.5 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2012, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ .fileinput-button i, .fileupload-buttonbar .delete, .fileupload-buttonbar .toggle { display: none; } ================================================ FILE: public/packages/jquery-file-upload-8.9.0/css/jquery.fileupload-ui.css ================================================ @charset "UTF-8"; /* * jQuery File Upload UI Plugin CSS 8.8.5 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ .fileupload-buttonbar .btn, .fileupload-buttonbar .toggle { margin-bottom: 5px; } .progress-animated .progress-bar, .progress-animated .bar { background: url("../img/progressbar.gif") !important; filter: none; } .fileupload-loading { float: right; width: 32px; height: 32px; background: url("../img/loading.gif") center no-repeat; background-size: contain; display: none; } .fileupload-processing .fileupload-loading { display: block; } .files audio, .files video { max-width: 300px; } @media (max-width: 767px) { .fileupload-buttonbar .toggle, .files .toggle, .files .btn span { display: none; } .files .name { width: 80px; word-wrap: break-word; } .files audio, .files video { max-width: 80px; } } ================================================ FILE: public/packages/jquery-file-upload-8.9.0/css/jquery.fileupload.css ================================================ @charset "UTF-8"; /* * jQuery File Upload Plugin CSS 1.3.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ .fileinput-button { position: relative; overflow: hidden; } .fileinput-button input { position: absolute; top: 0; right: 0; margin: 0; opacity: 0; -ms-filter: 'alpha(opacity=0)'; font-size: 200px; direction: ltr; cursor: pointer; } /* Fixes for IE < 8 */ @media screen\9 { .fileinput-button input { filter: alpha(opacity=0); font-size: 100%; height: 100%; } } ================================================ FILE: public/packages/jquery-file-upload-8.9.0/css/style.css ================================================ @charset "UTF-8"; /* * jQuery File Upload Plugin CSS Example 8.8.2 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ body { padding-top: 60px; } ================================================ FILE: public/packages/jquery-file-upload-8.9.0/index.html ================================================ jQuery File Upload Demo

            jQuery File Upload Demo

            Basic Plus UI version


            File Upload widget with multiple file selection, drag&drop support, progress bars, validation and preview images, audio and video for jQuery.
            Supports cross-domain, chunked and resumable file uploads and client-side image resizing.
            Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.


            Add files...
             

            Demo Notes

            • The maximum file size for uploads in this demo is 5 MB (default file size is unlimited).
            • Only image files (JPG, GIF, PNG) are allowed in this demo (by default there is no file type restriction).
            • Uploaded files will be deleted automatically after 5 minutes (demo setting).
            • You can drag & drop files from your desktop on this webpage (see Browser support).
            • Please refer to the project website and documentation for more information.
            • Built with Twitter's Bootstrap CSS framework and Icons from Glyphicons.
            ================================================ FILE: public/packages/jquery-file-upload-8.9.0/jquery-ui.html ================================================ jQuery File Upload Demo - jQuery UI version

            jQuery File Upload Demo

            jQuery UI version

            File Upload widget with multiple file selection, drag&drop support, progress bars, validation and preview images, audio and video for jQuery UI.
            Supports cross-domain, chunked and resumable file uploads and client-side image resizing.
            Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.

            Add files...

            Demo Notes

            • The maximum file size for uploads in this demo is 5 MB (default file size is unlimited).
            • Only image files (JPG, GIF, PNG) are allowed in this demo (by default there is no file type restriction).
            • Uploaded files will be deleted automatically after 5 minutes (demo setting).
            • You can drag & drop files from your desktop on this webpage (see Browser support).
            • Please refer to the project website and documentation for more information.
            • Built with jQuery UI.
            ================================================ FILE: public/packages/jquery-file-upload-8.9.0/js/app.js ================================================ /* * jQuery File Upload Plugin Angular JS Example 1.2.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, regexp: true */ /*global window, angular */ (function () { 'use strict'; var isOnGitHub = window.location.hostname === 'blueimp.github.io', url = isOnGitHub ? '//jquery-file-upload.appspot.com/' : 'server/php/'; angular.module('demo', [ 'blueimp.fileupload' ]) .config([ '$httpProvider', 'fileUploadProvider', function ($httpProvider, fileUploadProvider) { delete $httpProvider.defaults.headers.common['X-Requested-With']; fileUploadProvider.defaults.redirect = window.location.href.replace( /\/[^\/]*$/, '/cors/result.html?%s' ); if (isOnGitHub) { // Demo settings: angular.extend(fileUploadProvider.defaults, { // Enable image resizing, except for Android and Opera, // which actually support image resizing, but fail to // send Blob objects via XHR requests: disableImageResize: /Android(?!.*Chrome)|Opera/ .test(window.navigator.userAgent), maxFileSize: 5000000, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i }); } } ]) .controller('DemoFileUploadController', [ '$scope', '$http', '$filter', '$window', function ($scope, $http) { $scope.options = { url: url }; if (!isOnGitHub) { $scope.loadingFiles = true; $http.get(url) .then( function (response) { $scope.loadingFiles = false; $scope.queue = response.data.files || []; }, function () { $scope.loadingFiles = false; } ); } } ]) .controller('FileDestroyController', [ '$scope', '$http', function ($scope, $http) { var file = $scope.file, state; if (file.url) { file.$state = function () { return state; }; file.$destroy = function () { state = 'pending'; return $http({ url: file.deleteUrl, method: file.deleteType }).then( function () { state = 'resolved'; $scope.clear(file); }, function () { state = 'rejected'; } ); }; } else if (!file.$cancel && !file._index) { file.$cancel = function () { $scope.clear(file); }; } } ]); }()); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/js/cors/jquery.postmessage-transport.js ================================================ /* * jQuery postMessage Transport Plugin 1.1.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint unparam: true, nomen: true */ /*global define, window, document */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery'], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; var counter = 0, names = [ 'accepts', 'cache', 'contents', 'contentType', 'crossDomain', 'data', 'dataType', 'headers', 'ifModified', 'mimeType', 'password', 'processData', 'timeout', 'traditional', 'type', 'url', 'username' ], convert = function (p) { return p; }; $.ajaxSetup({ converters: { 'postmessage text': convert, 'postmessage json': convert, 'postmessage html': convert } }); $.ajaxTransport('postmessage', function (options) { if (options.postMessage && window.postMessage) { var iframe, loc = $('').prop('href', options.postMessage)[0], target = loc.protocol + '//' + loc.host, xhrUpload = options.xhr().upload; return { send: function (_, completeCallback) { counter += 1; var message = { id: 'postmessage-transport-' + counter }, eventName = 'message.' + message.id; iframe = $( '' ).bind('load', function () { $.each(names, function (i, name) { message[name] = options[name]; }); message.dataType = message.dataType.replace('postmessage ', ''); $(window).bind(eventName, function (e) { e = e.originalEvent; var data = e.data, ev; if (e.origin === target && data.id === message.id) { if (data.type === 'progress') { ev = document.createEvent('Event'); ev.initEvent(data.type, false, true); $.extend(ev, data); xhrUpload.dispatchEvent(ev); } else { completeCallback( data.status, data.statusText, {postmessage: data.result}, data.headers ); iframe.remove(); $(window).unbind(eventName); } } }); iframe[0].contentWindow.postMessage( message, target ); }).appendTo(document.body); }, abort: function () { if (iframe) { iframe.remove(); } } }; } }); })); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/js/cors/jquery.xdr-transport.js ================================================ /* * jQuery XDomainRequest Transport Plugin 1.1.3 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * Based on Julian Aubourg's ajaxHooks xdr.js: * https://github.com/jaubourg/ajaxHooks/ */ /*jslint unparam: true */ /*global define, window, XDomainRequest */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery'], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; if (window.XDomainRequest && !$.support.cors) { $.ajaxTransport(function (s) { if (s.crossDomain && s.async) { if (s.timeout) { s.xdrTimeout = s.timeout; delete s.timeout; } var xdr; return { send: function (headers, completeCallback) { var addParamChar = /\?/.test(s.url) ? '&' : '?'; function callback(status, statusText, responses, responseHeaders) { xdr.onload = xdr.onerror = xdr.ontimeout = $.noop; xdr = null; completeCallback(status, statusText, responses, responseHeaders); } xdr = new XDomainRequest(); // XDomainRequest only supports GET and POST: if (s.type === 'DELETE') { s.url = s.url + addParamChar + '_method=DELETE'; s.type = 'POST'; } else if (s.type === 'PUT') { s.url = s.url + addParamChar + '_method=PUT'; s.type = 'POST'; } else if (s.type === 'PATCH') { s.url = s.url + addParamChar + '_method=PATCH'; s.type = 'POST'; } xdr.open(s.type, s.url); xdr.onload = function () { callback( 200, 'OK', {text: xdr.responseText}, 'Content-Type: ' + xdr.contentType ); }; xdr.onerror = function () { callback(404, 'Not Found'); }; if (s.xdrTimeout) { xdr.ontimeout = function () { callback(0, 'timeout'); }; xdr.timeout = s.xdrTimeout; } xdr.send((s.hasContent && s.data) || null); }, abort: function () { if (xdr) { xdr.onerror = $.noop(); xdr.abort(); } } }; } }); } })); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/js/jquery.fileupload-angular.js ================================================ /* * jQuery File Upload AngularJS Plugin 1.5.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, unparam: true */ /*global define, angular */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', 'angular', './jquery.fileupload-image', './jquery.fileupload-audio', './jquery.fileupload-video', './jquery.fileupload-validate' ], factory); } else { factory(); } }(function () { 'use strict'; angular.module('blueimp.fileupload', []) // The fileUpload service provides configuration options // for the fileUpload directive and default handlers for // File Upload events: .provider('fileUpload', function () { var scopeApply = function () { var scope = angular.element(this) .fileupload('option', 'scope')(), $timeout = angular.injector(['ng']) .get('$timeout'); // Safe apply, makes sure $apply is called // asynchronously outside of the $digest cycle: $timeout(function () { scope.$apply(); }); }, $config; $config = this.defaults = { handleResponse: function (e, data) { var files = data.result && data.result.files; if (files) { data.scope().replace(data.files, files); } else if (data.errorThrown || data.textStatus === 'error') { data.files[0].error = data.errorThrown || data.textStatus; } }, add: function (e, data) { if (e.isDefaultPrevented()) { return false; } var scope = data.scope(); data.process(function () { return scope.process(data); }).always( function () { var file = data.files[0], submit = function () { return data.submit(); }; angular.forEach(data.files, function (file, index) { file._index = index; file.$state = function () { return data.state(); }; file.$progress = function () { return data.progress(); }; file.$response = function () { return data.response(); }; }); file.$cancel = function () { scope.clear(data.files); return data.abort(); }; if (file.$state() === 'rejected') { file._$submit = submit; } else { file.$submit = submit; } scope.$apply(function () { var method = scope.option('prependFiles') ? 'unshift' : 'push'; Array.prototype[method].apply( scope.queue, data.files ); if (file.$submit && (scope.option('autoUpload') || data.autoUpload) && data.autoUpload !== false) { file.$submit(); } }); } ); }, progress: function (e, data) { if (e.isDefaultPrevented()) { return false; } data.scope().$apply(); }, done: function (e, data) { if (e.isDefaultPrevented()) { return false; } var that = this; data.scope().$apply(function () { data.handleResponse.call(that, e, data); }); }, fail: function (e, data) { if (e.isDefaultPrevented()) { return false; } var that = this; if (data.errorThrown === 'abort') { return; } if (data.dataType && data.dataType.indexOf('json') === data.dataType.length - 4) { try { data.result = angular.fromJson(data.jqXHR.responseText); } catch (ignore) {} } data.scope().$apply(function () { data.handleResponse.call(that, e, data); }); }, stop: scopeApply, processstart: scopeApply, processstop: scopeApply, getNumberOfFiles: function () { return this.scope().queue.length; }, dataType: 'json', autoUpload: false }; this.$get = [ function () { return { defaults: $config }; } ]; }) // Format byte numbers to readable presentations: .provider('formatFileSizeFilter', function () { var $config = { // Byte units following the IEC format // http://en.wikipedia.org/wiki/Kilobyte units: [ {size: 1000000000, suffix: ' GB'}, {size: 1000000, suffix: ' MB'}, {size: 1000, suffix: ' KB'} ] }; this.defaults = $config; this.$get = function () { return function (bytes) { if (!angular.isNumber(bytes)) { return ''; } var unit = true, i = 0, prefix, suffix; while (unit) { unit = $config.units[i]; prefix = unit.prefix || ''; suffix = unit.suffix || ''; if (i === $config.units.length - 1 || bytes >= unit.size) { return prefix + (bytes / unit.size).toFixed(2) + suffix; } i += 1; } }; }; }) // The FileUploadController initializes the fileupload widget and // provides scope methods to control the File Upload functionality: .controller('FileUploadController', [ '$scope', '$element', '$attrs', '$window', 'fileUpload', function ($scope, $element, $attrs, $window, fileUpload) { var uploadMethods = { progress: function () { return $element.fileupload('progress'); }, active: function () { return $element.fileupload('active'); }, option: function (option, data) { return $element.fileupload('option', option, data); }, add: function (data) { return $element.fileupload('add', data); }, send: function (data) { return $element.fileupload('send', data); }, process: function (data) { return $element.fileupload('process', data); }, processing: function (data) { return $element.fileupload('processing', data); } }; $scope.disabled = !$window.jQuery.support.fileInput; $scope.queue = $scope.queue || []; $scope.clear = function (files) { var queue = this.queue, i = queue.length, file = files, length = 1; if (angular.isArray(files)) { file = files[0]; length = files.length; } while (i) { i -= 1; if (queue[i] === file) { return queue.splice(i, length); } } }; $scope.replace = function (oldFiles, newFiles) { var queue = this.queue, file = oldFiles[0], i, j; for (i = 0; i < queue.length; i += 1) { if (queue[i] === file) { for (j = 0; j < newFiles.length; j += 1) { queue[i + j] = newFiles[j]; } return; } } }; $scope.applyOnQueue = function (method) { var list = this.queue.slice(0), i, file; for (i = 0; i < list.length; i += 1) { file = list[i]; if (file[method]) { file[method](); } } }; $scope.submit = function () { this.applyOnQueue('$submit'); }; $scope.cancel = function () { this.applyOnQueue('$cancel'); }; // Add upload methods to the scope: angular.extend($scope, uploadMethods); // The fileupload widget will initialize with // the options provided via "data-"-parameters, // as well as those given via options object: $element.fileupload(angular.extend( {scope: function () { return $scope; }}, fileUpload.defaults )).on('fileuploadadd', function (e, data) { data.scope = $scope.option('scope'); }).on([ 'fileuploadadd', 'fileuploadsubmit', 'fileuploadsend', 'fileuploaddone', 'fileuploadfail', 'fileuploadalways', 'fileuploadprogress', 'fileuploadprogressall', 'fileuploadstart', 'fileuploadstop', 'fileuploadchange', 'fileuploadpaste', 'fileuploaddrop', 'fileuploaddragover', 'fileuploadchunksend', 'fileuploadchunkdone', 'fileuploadchunkfail', 'fileuploadchunkalways', 'fileuploadprocessstart', 'fileuploadprocess', 'fileuploadprocessdone', 'fileuploadprocessfail', 'fileuploadprocessalways', 'fileuploadprocessstop' ].join(' '), function (e, data) { if ($scope.$emit(e.type, data).defaultPrevented) { e.preventDefault(); } }).on('remove', function () { // Remove upload methods from the scope, // when the widget is removed: var method; for (method in uploadMethods) { if (uploadMethods.hasOwnProperty(method)) { delete $scope[method]; } } }); // Observe option changes: $scope.$watch( $attrs.fileUpload, function (newOptions) { if (newOptions) { $element.fileupload('option', newOptions); } } ); } ]) // Provide File Upload progress feedback: .controller('FileUploadProgressController', [ '$scope', '$attrs', '$parse', function ($scope, $attrs, $parse) { var fn = $parse($attrs.fileUploadProgress), update = function () { var progress = fn($scope); if (!progress || !progress.total) { return; } $scope.num = Math.floor( progress.loaded / progress.total * 100 ); }; update(); $scope.$watch( $attrs.fileUploadProgress + '.loaded', function (newValue, oldValue) { if (newValue !== oldValue) { update(); } } ); } ]) // Display File Upload previews: .controller('FileUploadPreviewController', [ '$scope', '$element', '$attrs', '$parse', function ($scope, $element, $attrs, $parse) { var fn = $parse($attrs.fileUploadPreview), file = fn($scope); if (file.preview) { $element.append(file.preview); } } ]) .directive('fileUpload', function () { return { controller: 'FileUploadController', scope: true }; }) .directive('fileUploadProgress', function () { return { controller: 'FileUploadProgressController', scope: true }; }) .directive('fileUploadPreview', function () { return { controller: 'FileUploadPreviewController' }; }) // Enhance the HTML5 download attribute to // allow drag&drop of files to the desktop: .directive('download', function () { return function (scope, elm) { elm.on('dragstart', function (e) { try { e.originalEvent.dataTransfer.setData( 'DownloadURL', [ 'application/octet-stream', elm.prop('download'), elm.prop('href') ].join(':') ); } catch (ignore) {} }); }; }); })); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/js/jquery.fileupload-audio.js ================================================ /* * jQuery File Upload Audio Preview Plugin 1.0.3 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, unparam: true, regexp: true */ /*global define, window, document */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', 'load-image', './jquery.fileupload-process' ], factory); } else { // Browser globals: factory( window.jQuery, window.loadImage ); } }(function ($, loadImage) { 'use strict'; // Prepend to the default processQueue: $.blueimp.fileupload.prototype.options.processQueue.unshift( { action: 'loadAudio', // Use the action as prefix for the "@" options: prefix: true, fileTypes: '@', maxFileSize: '@', disabled: '@disableAudioPreview' }, { action: 'setAudio', name: '@audioPreviewName', disabled: '@disableAudioPreview' } ); // The File Upload Audio Preview plugin extends the fileupload widget // with audio preview functionality: $.widget('blueimp.fileupload', $.blueimp.fileupload, { options: { // The regular expression for the types of audio files to load, // matched against the file type: loadAudioFileTypes: /^audio\/.*$/ }, _audioElement: document.createElement('audio'), processActions: { // Loads the audio file given via data.files and data.index // as audio element if the browser supports playing it. // Accepts the options fileTypes (regular expression) // and maxFileSize (integer) to limit the files to load: loadAudio: function (data, options) { if (options.disabled) { return data; } var file = data.files[data.index], url, audio; if (this._audioElement.canPlayType && this._audioElement.canPlayType(file.type) && ($.type(options.maxFileSize) !== 'number' || file.size <= options.maxFileSize) && (!options.fileTypes || options.fileTypes.test(file.type))) { url = loadImage.createObjectURL(file); if (url) { audio = this._audioElement.cloneNode(false); audio.src = url; audio.controls = true; data.audio = audio; return data; } } return data; }, // Sets the audio element as a property of the file object: setAudio: function (data, options) { if (data.audio && !options.disabled) { data.files[data.index][options.name || 'preview'] = data.audio; } return data; } } }); })); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/js/jquery.fileupload-image.js ================================================ /* * jQuery File Upload Image Preview & Resize Plugin 1.3.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, unparam: true, regexp: true */ /*global define, window, document, DataView, Blob, Uint8Array */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', 'load-image', 'load-image-meta', 'load-image-exif', 'load-image-ios', 'canvas-to-blob', './jquery.fileupload-process' ], factory); } else { // Browser globals: factory( window.jQuery, window.loadImage ); } }(function ($, loadImage) { 'use strict'; // Prepend to the default processQueue: $.blueimp.fileupload.prototype.options.processQueue.unshift( { action: 'loadImageMetaData', disableImageHead: '@', disableExif: '@', disableExifThumbnail: '@', disableExifSub: '@', disableExifGps: '@', disabled: '@disableImageMetaDataLoad' }, { action: 'loadImage', // Use the action as prefix for the "@" options: prefix: true, fileTypes: '@', maxFileSize: '@', noRevoke: '@', disabled: '@disableImageLoad' }, { action: 'resizeImage', // Use "image" as prefix for the "@" options: prefix: 'image', maxWidth: '@', maxHeight: '@', minWidth: '@', minHeight: '@', crop: '@', orientation: '@', disabled: '@disableImageResize' }, { action: 'saveImage', disabled: '@disableImageResize' }, { action: 'saveImageMetaData', disabled: '@disableImageMetaDataSave' }, { action: 'resizeImage', // Use "preview" as prefix for the "@" options: prefix: 'preview', maxWidth: '@', maxHeight: '@', minWidth: '@', minHeight: '@', crop: '@', orientation: '@', thumbnail: '@', canvas: '@', disabled: '@disableImagePreview' }, { action: 'setImage', name: '@imagePreviewName', disabled: '@disableImagePreview' } ); // The File Upload Resize plugin extends the fileupload widget // with image resize functionality: $.widget('blueimp.fileupload', $.blueimp.fileupload, { options: { // The regular expression for the types of images to load: // matched against the file type: loadImageFileTypes: /^image\/(gif|jpeg|png)$/, // The maximum file size of images to load: loadImageMaxFileSize: 10000000, // 10MB // The maximum width of resized images: imageMaxWidth: 1920, // The maximum height of resized images: imageMaxHeight: 1080, // Defines the image orientation (1-8) or takes the orientation // value from Exif data if set to true: imageOrientation: false, // Define if resized images should be cropped or only scaled: imageCrop: false, // Disable the resize image functionality by default: disableImageResize: true, // The maximum width of the preview images: previewMaxWidth: 80, // The maximum height of the preview images: previewMaxHeight: 80, // Defines the preview orientation (1-8) or takes the orientation // value from Exif data if set to true: previewOrientation: true, // Create the preview using the Exif data thumbnail: previewThumbnail: true, // Define if preview images should be cropped or only scaled: previewCrop: false, // Define if preview images should be resized as canvas elements: previewCanvas: true }, processActions: { // Loads the image given via data.files and data.index // as img element, if the browser supports the File API. // Accepts the options fileTypes (regular expression) // and maxFileSize (integer) to limit the files to load: loadImage: function (data, options) { if (options.disabled) { return data; } var that = this, file = data.files[data.index], dfd = $.Deferred(); if (($.type(options.maxFileSize) === 'number' && file.size > options.maxFileSize) || (options.fileTypes && !options.fileTypes.test(file.type)) || !loadImage( file, function (img) { if (img.src) { data.img = img; } dfd.resolveWith(that, [data]); }, options )) { return data; } return dfd.promise(); }, // Resizes the image given as data.canvas or data.img // and updates data.canvas or data.img with the resized image. // Also stores the resized image as preview property. // Accepts the options maxWidth, maxHeight, minWidth, // minHeight, canvas and crop: resizeImage: function (data, options) { if (options.disabled) { return data; } options = $.extend({canvas: true}, options); var that = this, dfd = $.Deferred(), img = (options.canvas && data.canvas) || data.img, resolve = function (newImg) { if (newImg && (newImg.width !== img.width || newImg.height !== img.height)) { data[newImg.getContext ? 'canvas' : 'img'] = newImg; } data.preview = newImg; dfd.resolveWith(that, [data]); }, thumbnail; if (data.exif) { if (options.orientation === true) { options.orientation = data.exif.get('Orientation'); } if (options.thumbnail) { thumbnail = data.exif.get('Thumbnail'); if (thumbnail) { loadImage(thumbnail, resolve, options); return dfd.promise(); } } } if (img) { resolve(loadImage.scale(img, options)); return dfd.promise(); } return data; }, // Saves the processed image given as data.canvas // inplace at data.index of data.files: saveImage: function (data, options) { if (!data.canvas || options.disabled) { return data; } var that = this, file = data.files[data.index], name = file.name, dfd = $.Deferred(), callback = function (blob) { if (!blob.name) { if (file.type === blob.type) { blob.name = file.name; } else if (file.name) { blob.name = file.name.replace( /\..+$/, '.' + blob.type.substr(6) ); } } // Store the created blob at the position // of the original file in the files list: data.files[data.index] = blob; dfd.resolveWith(that, [data]); }; // Use canvas.mozGetAsFile directly, to retain the filename, as // Gecko doesn't support the filename option for FormData.append: if (data.canvas.mozGetAsFile) { callback(data.canvas.mozGetAsFile( (/^image\/(jpeg|png)$/.test(file.type) && name) || ((name && name.replace(/\..+$/, '')) || 'blob') + '.png', file.type )); } else if (data.canvas.toBlob) { data.canvas.toBlob(callback, file.type); } else { return data; } return dfd.promise(); }, loadImageMetaData: function (data, options) { if (options.disabled) { return data; } var that = this, dfd = $.Deferred(); loadImage.parseMetaData(data.files[data.index], function (result) { $.extend(data, result); dfd.resolveWith(that, [data]); }, options); return dfd.promise(); }, saveImageMetaData: function (data, options) { if (!(data.imageHead && data.canvas && data.canvas.toBlob && !options.disabled)) { return data; } var file = data.files[data.index], blob = new Blob([ data.imageHead, // Resized images always have a head size of 20 bytes, // including the JPEG marker and a minimal JFIF header: this._blobSlice.call(file, 20) ], {type: file.type}); blob.name = file.name; data.files[data.index] = blob; return data; }, // Sets the resized version of the image as a property of the // file object, must be called after "saveImage": setImage: function (data, options) { if (data.preview && !options.disabled) { data.files[data.index][options.name || 'preview'] = data.preview; } return data; } } }); })); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/js/jquery.fileupload-jquery-ui.js ================================================ /* * jQuery File Upload jQuery UI Plugin 8.7.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, unparam: true */ /*global define, window */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery', './jquery.fileupload-ui'], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; $.widget('blueimp.fileupload', $.blueimp.fileupload, { options: { progress: function (e, data) { if (data.context) { data.context.find('.progress').progressbar( 'option', 'value', parseInt(data.loaded / data.total * 100, 10) ); } }, progressall: function (e, data) { var $this = $(this); $this.find('.fileupload-progress') .find('.progress').progressbar( 'option', 'value', parseInt(data.loaded / data.total * 100, 10) ).end() .find('.progress-extended').each(function () { $(this).html( ($this.data('blueimp-fileupload') || $this.data('fileupload')) ._renderExtendedProgress(data) ); }); } }, _renderUpload: function (func, files) { var node = this._super(func, files), showIconText = $(window).width() > 480; node.find('.progress').empty().progressbar(); node.find('.start').button({ icons: {primary: 'ui-icon-circle-arrow-e'}, text: showIconText }); node.find('.cancel').button({ icons: {primary: 'ui-icon-cancel'}, text: showIconText }); if (node.hasClass('fade')) { node.hide(); } return node; }, _renderDownload: function (func, files) { var node = this._super(func, files), showIconText = $(window).width() > 480; node.find('.delete').button({ icons: {primary: 'ui-icon-trash'}, text: showIconText }); if (node.hasClass('fade')) { node.hide(); } return node; }, _transition: function (node) { var deferred = $.Deferred(); if (node.hasClass('fade')) { node.fadeToggle( this.options.transitionDuration, this.options.transitionEasing, function () { deferred.resolveWith(node); } ); } else { deferred.resolveWith(node); } return deferred; }, _create: function () { this._super(); this.element .find('.fileupload-buttonbar') .find('.fileinput-button').each(function () { var input = $(this).find('input:file').detach(); $(this) .button({icons: {primary: 'ui-icon-plusthick'}}) .append(input); }) .end().find('.start') .button({icons: {primary: 'ui-icon-circle-arrow-e'}}) .end().find('.cancel') .button({icons: {primary: 'ui-icon-cancel'}}) .end().find('.delete') .button({icons: {primary: 'ui-icon-trash'}}) .end().find('.progress').progressbar(); }, _destroy: function () { this.element .find('.fileupload-buttonbar') .find('.fileinput-button').each(function () { var input = $(this).find('input:file').detach(); $(this) .button('destroy') .append(input); }) .end().find('.start') .button('destroy') .end().find('.cancel') .button('destroy') .end().find('.delete') .button('destroy') .end().find('.progress').progressbar('destroy'); this._super(); } }); })); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/js/jquery.fileupload-process.js ================================================ /* * jQuery File Upload Processing Plugin 1.2.2 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2012, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, unparam: true */ /*global define, window */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', './jquery.fileupload' ], factory); } else { // Browser globals: factory( window.jQuery ); } }(function ($) { 'use strict'; var originalAdd = $.blueimp.fileupload.prototype.options.add; // The File Upload Processing plugin extends the fileupload widget // with file processing functionality: $.widget('blueimp.fileupload', $.blueimp.fileupload, { options: { // The list of processing actions: processQueue: [ /* { action: 'log', type: 'debug' } */ ], add: function (e, data) { var $this = $(this); data.process(function () { return $this.fileupload('process', data); }); originalAdd.call(this, e, data); } }, processActions: { /* log: function (data, options) { console[options.type]( 'Processing "' + data.files[data.index].name + '"' ); } */ }, _processFile: function (data) { var that = this, dfd = $.Deferred().resolveWith(that, [data]), chain = dfd.promise(); this._trigger('process', null, data); $.each(data.processQueue, function (i, settings) { var func = function (data) { return that.processActions[settings.action].call( that, data, settings ); }; chain = chain.pipe(func, settings.always && func); }); chain .done(function () { that._trigger('processdone', null, data); that._trigger('processalways', null, data); }) .fail(function () { that._trigger('processfail', null, data); that._trigger('processalways', null, data); }); return chain; }, // Replaces the settings of each processQueue item that // are strings starting with an "@", using the remaining // substring as key for the option map, // e.g. "@autoUpload" is replaced with options.autoUpload: _transformProcessQueue: function (options) { var processQueue = []; $.each(options.processQueue, function () { var settings = {}, action = this.action, prefix = this.prefix === true ? action : this.prefix; $.each(this, function (key, value) { if ($.type(value) === 'string' && value.charAt(0) === '@') { settings[key] = options[ value.slice(1) || (prefix ? prefix + key.charAt(0).toUpperCase() + key.slice(1) : key) ]; } else { settings[key] = value; } }); processQueue.push(settings); }); options.processQueue = processQueue; }, // Returns the number of files currently in the processsing queue: processing: function () { return this._processing; }, // Processes the files given as files property of the data parameter, // returns a Promise object that allows to bind callbacks: process: function (data) { var that = this, options = $.extend({}, this.options, data); if (options.processQueue && options.processQueue.length) { this._transformProcessQueue(options); if (this._processing === 0) { this._trigger('processstart'); } $.each(data.files, function (index) { var opts = index ? $.extend({}, options) : options, func = function () { return that._processFile(opts); }; opts.index = index; that._processing += 1; that._processingQueue = that._processingQueue.pipe(func, func) .always(function () { that._processing -= 1; if (that._processing === 0) { that._trigger('processstop'); } }); }); } return this._processingQueue; }, _create: function () { this._super(); this._processing = 0; this._processingQueue = $.Deferred().resolveWith(this) .promise(); } }); })); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/js/jquery.fileupload-ui.js ================================================ /* * jQuery File Upload User Interface Plugin 8.9.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, unparam: true, regexp: true */ /*global define, window, URL, webkitURL, FileReader */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', 'tmpl', './jquery.fileupload-image', './jquery.fileupload-audio', './jquery.fileupload-video', './jquery.fileupload-validate' ], factory); } else { // Browser globals: factory( window.jQuery, window.tmpl ); } }(function ($, tmpl, loadImage) { 'use strict'; $.blueimp.fileupload.prototype._specialOptions.push( 'filesContainer', 'uploadTemplateId', 'downloadTemplateId' ); // The UI version extends the file upload widget // and adds complete user interface interaction: $.widget('blueimp.fileupload', $.blueimp.fileupload, { options: { // By default, files added to the widget are uploaded as soon // as the user clicks on the start buttons. To enable automatic // uploads, set the following option to true: autoUpload: false, // The ID of the upload template: uploadTemplateId: 'template-upload', // The ID of the download template: downloadTemplateId: 'template-download', // The container for the list of files. If undefined, it is set to // an element with class "files" inside of the widget element: filesContainer: undefined, // By default, files are appended to the files container. // Set the following option to true, to prepend files instead: prependFiles: false, // The expected data type of the upload response, sets the dataType // option of the $.ajax upload requests: dataType: 'json', // Function returning the current number of files, // used by the maxNumberOfFiles validation: getNumberOfFiles: function () { return this.filesContainer.children().length; }, // Callback to retrieve the list of files from the server response: getFilesFromResponse: function (data) { if (data.result && $.isArray(data.result.files)) { return data.result.files; } return []; }, // The add callback is invoked as soon as files are added to the fileupload // widget (via file input selection, drag & drop or add API call). // See the basic file upload widget for more information: add: function (e, data) { if (e.isDefaultPrevented()) { return false; } var $this = $(this), that = $this.data('blueimp-fileupload') || $this.data('fileupload'), options = that.options, files = data.files; data.process(function () { return $this.fileupload('process', data); }).always(function () { data.context = that._renderUpload(files).data('data', data); that._renderPreviews(data); options.filesContainer[ options.prependFiles ? 'prepend' : 'append' ](data.context); that._forceReflow(data.context); that._transition(data.context).done( function () { if ((that._trigger('added', e, data) !== false) && (options.autoUpload || data.autoUpload) && data.autoUpload !== false && !data.files.error) { data.submit(); } } ); }); }, // Callback for the start of each file upload request: send: function (e, data) { if (e.isDefaultPrevented()) { return false; } var that = $(this).data('blueimp-fileupload') || $(this).data('fileupload'); if (data.context && data.dataType && data.dataType.substr(0, 6) === 'iframe') { // Iframe Transport does not support progress events. // In lack of an indeterminate progress bar, we set // the progress to 100%, showing the full animated bar: data.context .find('.progress').addClass( !$.support.transition && 'progress-animated' ) .attr('aria-valuenow', 100) .children().first().css( 'width', '100%' ); } return that._trigger('sent', e, data); }, // Callback for successful uploads: done: function (e, data) { if (e.isDefaultPrevented()) { return false; } var that = $(this).data('blueimp-fileupload') || $(this).data('fileupload'), getFilesFromResponse = data.getFilesFromResponse || that.options.getFilesFromResponse, files = getFilesFromResponse(data), template, deferred; if (data.context) { data.context.each(function (index) { var file = files[index] || {error: 'Empty file upload result'}; deferred = that._addFinishedDeferreds(); that._transition($(this)).done( function () { var node = $(this); template = that._renderDownload([file]) .replaceAll(node); that._forceReflow(template); that._transition(template).done( function () { data.context = $(this); that._trigger('completed', e, data); that._trigger('finished', e, data); deferred.resolve(); } ); } ); }); } else { template = that._renderDownload(files)[ that.options.prependFiles ? 'prependTo' : 'appendTo' ](that.options.filesContainer); that._forceReflow(template); deferred = that._addFinishedDeferreds(); that._transition(template).done( function () { data.context = $(this); that._trigger('completed', e, data); that._trigger('finished', e, data); deferred.resolve(); } ); } }, // Callback for failed (abort or error) uploads: fail: function (e, data) { if (e.isDefaultPrevented()) { return false; } var that = $(this).data('blueimp-fileupload') || $(this).data('fileupload'), template, deferred; if (data.context) { data.context.each(function (index) { if (data.errorThrown !== 'abort') { var file = data.files[index]; file.error = file.error || data.errorThrown || true; deferred = that._addFinishedDeferreds(); that._transition($(this)).done( function () { var node = $(this); template = that._renderDownload([file]) .replaceAll(node); that._forceReflow(template); that._transition(template).done( function () { data.context = $(this); that._trigger('failed', e, data); that._trigger('finished', e, data); deferred.resolve(); } ); } ); } else { deferred = that._addFinishedDeferreds(); that._transition($(this)).done( function () { $(this).remove(); that._trigger('failed', e, data); that._trigger('finished', e, data); deferred.resolve(); } ); } }); } else if (data.errorThrown !== 'abort') { data.context = that._renderUpload(data.files)[ that.options.prependFiles ? 'prependTo' : 'appendTo' ](that.options.filesContainer) .data('data', data); that._forceReflow(data.context); deferred = that._addFinishedDeferreds(); that._transition(data.context).done( function () { data.context = $(this); that._trigger('failed', e, data); that._trigger('finished', e, data); deferred.resolve(); } ); } else { that._trigger('failed', e, data); that._trigger('finished', e, data); that._addFinishedDeferreds().resolve(); } }, // Callback for upload progress events: progress: function (e, data) { if (e.isDefaultPrevented()) { return false; } var progress = Math.floor(data.loaded / data.total * 100); if (data.context) { data.context.each(function () { $(this).find('.progress') .attr('aria-valuenow', progress) .children().first().css( 'width', progress + '%' ); }); } }, // Callback for global upload progress events: progressall: function (e, data) { if (e.isDefaultPrevented()) { return false; } var $this = $(this), progress = Math.floor(data.loaded / data.total * 100), globalProgressNode = $this.find('.fileupload-progress'), extendedProgressNode = globalProgressNode .find('.progress-extended'); if (extendedProgressNode.length) { extendedProgressNode.html( ($this.data('blueimp-fileupload') || $this.data('fileupload')) ._renderExtendedProgress(data) ); } globalProgressNode .find('.progress') .attr('aria-valuenow', progress) .children().first().css( 'width', progress + '%' ); }, // Callback for uploads start, equivalent to the global ajaxStart event: start: function (e) { if (e.isDefaultPrevented()) { return false; } var that = $(this).data('blueimp-fileupload') || $(this).data('fileupload'); that._resetFinishedDeferreds(); that._transition($(this).find('.fileupload-progress')).done( function () { that._trigger('started', e); } ); }, // Callback for uploads stop, equivalent to the global ajaxStop event: stop: function (e) { if (e.isDefaultPrevented()) { return false; } var that = $(this).data('blueimp-fileupload') || $(this).data('fileupload'), deferred = that._addFinishedDeferreds(); $.when.apply($, that._getFinishedDeferreds()) .done(function () { that._trigger('stopped', e); }); that._transition($(this).find('.fileupload-progress')).done( function () { $(this).find('.progress') .attr('aria-valuenow', '0') .children().first().css('width', '0%'); $(this).find('.progress-extended').html(' '); deferred.resolve(); } ); }, processstart: function (e) { if (e.isDefaultPrevented()) { return false; } $(this).addClass('fileupload-processing'); }, processstop: function (e) { if (e.isDefaultPrevented()) { return false; } $(this).removeClass('fileupload-processing'); }, // Callback for file deletion: destroy: function (e, data) { if (e.isDefaultPrevented()) { return false; } var that = $(this).data('blueimp-fileupload') || $(this).data('fileupload'), removeNode = function () { that._transition(data.context).done( function () { $(this).remove(); that._trigger('destroyed', e, data); } ); }; if (data.url) { data.dataType = data.dataType || that.options.dataType; $.ajax(data).done(removeNode); } else { removeNode(); } } }, _resetFinishedDeferreds: function () { this._finishedUploads = []; }, _addFinishedDeferreds: function (deferred) { if (!deferred) { deferred = $.Deferred(); } this._finishedUploads.push(deferred); return deferred; }, _getFinishedDeferreds: function () { return this._finishedUploads; }, // Link handler, that allows to download files // by drag & drop of the links to the desktop: _enableDragToDesktop: function () { var link = $(this), url = link.prop('href'), name = link.prop('download'), type = 'application/octet-stream'; link.bind('dragstart', function (e) { try { e.originalEvent.dataTransfer.setData( 'DownloadURL', [type, name, url].join(':') ); } catch (ignore) {} }); }, _formatFileSize: function (bytes) { if (typeof bytes !== 'number') { return ''; } if (bytes >= 1000000000) { return (bytes / 1000000000).toFixed(2) + ' GB'; } if (bytes >= 1000000) { return (bytes / 1000000).toFixed(2) + ' MB'; } return (bytes / 1000).toFixed(2) + ' KB'; }, _formatBitrate: function (bits) { if (typeof bits !== 'number') { return ''; } if (bits >= 1000000000) { return (bits / 1000000000).toFixed(2) + ' Gbit/s'; } if (bits >= 1000000) { return (bits / 1000000).toFixed(2) + ' Mbit/s'; } if (bits >= 1000) { return (bits / 1000).toFixed(2) + ' kbit/s'; } return bits.toFixed(2) + ' bit/s'; }, _formatTime: function (seconds) { var date = new Date(seconds * 1000), days = Math.floor(seconds / 86400); days = days ? days + 'd ' : ''; return days + ('0' + date.getUTCHours()).slice(-2) + ':' + ('0' + date.getUTCMinutes()).slice(-2) + ':' + ('0' + date.getUTCSeconds()).slice(-2); }, _formatPercentage: function (floatValue) { return (floatValue * 100).toFixed(2) + ' %'; }, _renderExtendedProgress: function (data) { return this._formatBitrate(data.bitrate) + ' | ' + this._formatTime( (data.total - data.loaded) * 8 / data.bitrate ) + ' | ' + this._formatPercentage( data.loaded / data.total ) + ' | ' + this._formatFileSize(data.loaded) + ' / ' + this._formatFileSize(data.total); }, _renderTemplate: function (func, files) { if (!func) { return $(); } var result = func({ files: files, formatFileSize: this._formatFileSize, options: this.options }); if (result instanceof $) { return result; } return $(this.options.templatesContainer).html(result).children(); }, _renderPreviews: function (data) { data.context.find('.preview').each(function (index, elm) { $(elm).append(data.files[index].preview); }); }, _renderUpload: function (files) { return this._renderTemplate( this.options.uploadTemplate, files ); }, _renderDownload: function (files) { return this._renderTemplate( this.options.downloadTemplate, files ).find('a[download]').each(this._enableDragToDesktop).end(); }, _startHandler: function (e) { e.preventDefault(); var button = $(e.currentTarget), template = button.closest('.template-upload'), data = template.data('data'); button.prop('disabled', true); if (data && data.submit) { data.submit(); } }, _cancelHandler: function (e) { e.preventDefault(); var template = $(e.currentTarget) .closest('.template-upload,.template-download'), data = template.data('data') || {}; if (!data.jqXHR) { data.context = data.context || template; data.errorThrown = 'abort'; this._trigger('fail', e, data); } else { data.jqXHR.abort(); } }, _deleteHandler: function (e) { e.preventDefault(); var button = $(e.currentTarget); this._trigger('destroy', e, $.extend({ context: button.closest('.template-download'), type: 'DELETE' }, button.data())); }, _forceReflow: function (node) { return $.support.transition && node.length && node[0].offsetWidth; }, _transition: function (node) { var dfd = $.Deferred(); if ($.support.transition && node.hasClass('fade') && node.is(':visible')) { node.bind( $.support.transition.end, function (e) { // Make sure we don't respond to other transitions events // in the container element, e.g. from button elements: if (e.target === node[0]) { node.unbind($.support.transition.end); dfd.resolveWith(node); } } ).toggleClass('in'); } else { node.toggleClass('in'); dfd.resolveWith(node); } return dfd; }, _initButtonBarEventHandlers: function () { var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'), filesList = this.options.filesContainer; this._on(fileUploadButtonBar.find('.start'), { click: function (e) { e.preventDefault(); filesList.find('.start').click(); } }); this._on(fileUploadButtonBar.find('.cancel'), { click: function (e) { e.preventDefault(); filesList.find('.cancel').click(); } }); this._on(fileUploadButtonBar.find('.delete'), { click: function (e) { e.preventDefault(); filesList.find('.toggle:checked') .closest('.template-download') .find('.delete').click(); fileUploadButtonBar.find('.toggle') .prop('checked', false); } }); this._on(fileUploadButtonBar.find('.toggle'), { change: function (e) { filesList.find('.toggle').prop( 'checked', $(e.currentTarget).is(':checked') ); } }); }, _destroyButtonBarEventHandlers: function () { this._off( this.element.find('.fileupload-buttonbar') .find('.start, .cancel, .delete'), 'click' ); this._off( this.element.find('.fileupload-buttonbar .toggle'), 'change.' ); }, _initEventHandlers: function () { this._super(); this._on(this.options.filesContainer, { 'click .start': this._startHandler, 'click .cancel': this._cancelHandler, 'click .delete': this._deleteHandler }); this._initButtonBarEventHandlers(); }, _destroyEventHandlers: function () { this._destroyButtonBarEventHandlers(); this._off(this.options.filesContainer, 'click'); this._super(); }, _enableFileInputButton: function () { this.element.find('.fileinput-button input') .prop('disabled', false) .parent().removeClass('disabled'); }, _disableFileInputButton: function () { this.element.find('.fileinput-button input') .prop('disabled', true) .parent().addClass('disabled'); }, _initTemplates: function () { var options = this.options; options.templatesContainer = this.document[0].createElement( options.filesContainer.prop('nodeName') ); if (tmpl) { if (options.uploadTemplateId) { options.uploadTemplate = tmpl(options.uploadTemplateId); } if (options.downloadTemplateId) { options.downloadTemplate = tmpl(options.downloadTemplateId); } } }, _initFilesContainer: function () { var options = this.options; if (options.filesContainer === undefined) { options.filesContainer = this.element.find('.files'); } else if (!(options.filesContainer instanceof $)) { options.filesContainer = $(options.filesContainer); } }, _initSpecialOptions: function () { this._super(); this._initFilesContainer(); this._initTemplates(); }, _create: function () { this._super(); this._resetFinishedDeferreds(); if (!$.support.fileInput) { this._disableFileInputButton(); } }, enable: function () { var wasDisabled = false; if (this.options.disabled) { wasDisabled = true; } this._super(); if (wasDisabled) { this.element.find('input, button').prop('disabled', false); this._enableFileInputButton(); } }, disable: function () { if (!this.options.disabled) { this.element.find('input, button').prop('disabled', true); this._disableFileInputButton(); } this._super(); } }); })); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/js/jquery.fileupload-validate.js ================================================ /* * jQuery File Upload Validation Plugin 1.1.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, unparam: true, regexp: true */ /*global define, window */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', './jquery.fileupload-process' ], factory); } else { // Browser globals: factory( window.jQuery ); } }(function ($) { 'use strict'; // Append to the default processQueue: $.blueimp.fileupload.prototype.options.processQueue.push( { action: 'validate', // Always trigger this action, // even if the previous action was rejected: always: true, // Options taken from the global options map: acceptFileTypes: '@', maxFileSize: '@', minFileSize: '@', maxNumberOfFiles: '@', disabled: '@disableValidation' } ); // The File Upload Validation plugin extends the fileupload widget // with file validation functionality: $.widget('blueimp.fileupload', $.blueimp.fileupload, { options: { /* // The regular expression for allowed file types, matches // against either file type or file name: acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, // The maximum allowed file size in bytes: maxFileSize: 10000000, // 10 MB // The minimum allowed file size in bytes: minFileSize: undefined, // No minimal file size // The limit of files to be uploaded: maxNumberOfFiles: 10, */ // Function returning the current number of files, // has to be overriden for maxNumberOfFiles validation: getNumberOfFiles: $.noop, // Error and info messages: messages: { maxNumberOfFiles: 'Maximum number of files exceeded', acceptFileTypes: 'File type not allowed', maxFileSize: 'File is too large', minFileSize: 'File is too small' } }, processActions: { validate: function (data, options) { if (options.disabled) { return data; } var dfd = $.Deferred(), settings = this.options, file = data.files[data.index]; if ($.type(options.maxNumberOfFiles) === 'number' && (settings.getNumberOfFiles() || 0) + data.files.length > options.maxNumberOfFiles) { file.error = settings.i18n('maxNumberOfFiles'); } else if (options.acceptFileTypes && !(options.acceptFileTypes.test(file.type) || options.acceptFileTypes.test(file.name))) { file.error = settings.i18n('acceptFileTypes'); } else if (options.maxFileSize && file.size > options.maxFileSize) { file.error = settings.i18n('maxFileSize'); } else if ($.type(file.size) === 'number' && file.size < options.minFileSize) { file.error = settings.i18n('minFileSize'); } else { delete file.error; } if (file.error || data.files.error) { data.files.error = true; dfd.rejectWith(this, [data]); } else { dfd.resolveWith(this, [data]); } return dfd.promise(); } } }); })); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/js/jquery.fileupload-video.js ================================================ /* * jQuery File Upload Video Preview Plugin 1.0.3 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, unparam: true, regexp: true */ /*global define, window, document */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', 'load-image', './jquery.fileupload-process' ], factory); } else { // Browser globals: factory( window.jQuery, window.loadImage ); } }(function ($, loadImage) { 'use strict'; // Prepend to the default processQueue: $.blueimp.fileupload.prototype.options.processQueue.unshift( { action: 'loadVideo', // Use the action as prefix for the "@" options: prefix: true, fileTypes: '@', maxFileSize: '@', disabled: '@disableVideoPreview' }, { action: 'setVideo', name: '@videoPreviewName', disabled: '@disableVideoPreview' } ); // The File Upload Video Preview plugin extends the fileupload widget // with video preview functionality: $.widget('blueimp.fileupload', $.blueimp.fileupload, { options: { // The regular expression for the types of video files to load, // matched against the file type: loadVideoFileTypes: /^video\/.*$/ }, _videoElement: document.createElement('video'), processActions: { // Loads the video file given via data.files and data.index // as video element if the browser supports playing it. // Accepts the options fileTypes (regular expression) // and maxFileSize (integer) to limit the files to load: loadVideo: function (data, options) { if (options.disabled) { return data; } var file = data.files[data.index], url, video; if (this._videoElement.canPlayType && this._videoElement.canPlayType(file.type) && ($.type(options.maxFileSize) !== 'number' || file.size <= options.maxFileSize) && (!options.fileTypes || options.fileTypes.test(file.type))) { url = loadImage.createObjectURL(file); if (url) { video = this._videoElement.cloneNode(false); video.src = url; video.controls = true; data.video = video; return data; } } return data; }, // Sets the video element as a property of the file object: setVideo: function (data, options) { if (data.video && !options.disabled) { data.files[data.index][options.name || 'preview'] = data.video; } return data; } } }); })); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/js/jquery.fileupload.js ================================================ /* * jQuery File Upload Plugin 5.34.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, unparam: true, regexp: true */ /*global define, window, document, location, File, Blob, FormData */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', 'jquery.ui.widget' ], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; // Detect file input support, based on // http://viljamis.com/blog/2012/file-upload-support-on-mobile/ $.support.fileInput = !(new RegExp( // Handle devices which give false positives for the feature detection: '(Android (1\\.[0156]|2\\.[01]))' + '|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)|(WPDesktop)' + '|(w(eb)?OSBrowser)|(webOS)' + '|(Kindle/(1\\.0|2\\.[05]|3\\.0))' ).test(window.navigator.userAgent) || // Feature detection for all other devices: $('').prop('disabled')); // The FileReader API is not actually used, but works as feature detection, // as e.g. Safari supports XHR file uploads via the FormData API, // but not non-multipart XHR file uploads: $.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader); $.support.xhrFormDataFileUpload = !!window.FormData; // Detect support for Blob slicing (required for chunked uploads): $.support.blobSlice = window.Blob && (Blob.prototype.slice || Blob.prototype.webkitSlice || Blob.prototype.mozSlice); // The fileupload widget listens for change events on file input fields defined // via fileInput setting and paste or drop events of the given dropZone. // In addition to the default jQuery Widget methods, the fileupload widget // exposes the "add" and "send" methods, to add or directly send files using // the fileupload API. // By default, files added via file input selection, paste, drag & drop or // "add" method are uploaded immediately, but it is possible to override // the "add" callback option to queue file uploads. $.widget('blueimp.fileupload', { options: { // The drop target element(s), by the default the complete document. // Set to null to disable drag & drop support: dropZone: $(document), // The paste target element(s), by the default the complete document. // Set to null to disable paste support: pasteZone: $(document), // The file input field(s), that are listened to for change events. // If undefined, it is set to the file input fields inside // of the widget element on plugin initialization. // Set to null to disable the change listener. fileInput: undefined, // By default, the file input field is replaced with a clone after // each input field change event. This is required for iframe transport // queues and allows change events to be fired for the same file // selection, but can be disabled by setting the following option to false: replaceFileInput: true, // The parameter name for the file form data (the request argument name). // If undefined or empty, the name property of the file input field is // used, or "files[]" if the file input name property is also empty, // can be a string or an array of strings: paramName: undefined, // By default, each file of a selection is uploaded using an individual // request for XHR type uploads. Set to false to upload file // selections in one request each: singleFileUploads: true, // To limit the number of files uploaded with one XHR request, // set the following option to an integer greater than 0: limitMultiFileUploads: undefined, // Set the following option to true to issue all file upload requests // in a sequential order: sequentialUploads: false, // To limit the number of concurrent uploads, // set the following option to an integer greater than 0: limitConcurrentUploads: undefined, // Set the following option to true to force iframe transport uploads: forceIframeTransport: false, // Set the following option to the location of a redirect url on the // origin server, for cross-domain iframe transport uploads: redirect: undefined, // The parameter name for the redirect url, sent as part of the form // data and set to 'redirect' if this option is empty: redirectParamName: undefined, // Set the following option to the location of a postMessage window, // to enable postMessage transport uploads: postMessage: undefined, // By default, XHR file uploads are sent as multipart/form-data. // The iframe transport is always using multipart/form-data. // Set to false to enable non-multipart XHR uploads: multipart: true, // To upload large files in smaller chunks, set the following option // to a preferred maximum chunk size. If set to 0, null or undefined, // or the browser does not support the required Blob API, files will // be uploaded as a whole. maxChunkSize: undefined, // When a non-multipart upload or a chunked multipart upload has been // aborted, this option can be used to resume the upload by setting // it to the size of the already uploaded bytes. This option is most // useful when modifying the options object inside of the "add" or // "send" callbacks, as the options are cloned for each file upload. uploadedBytes: undefined, // By default, failed (abort or error) file uploads are removed from the // global progress calculation. Set the following option to false to // prevent recalculating the global progress data: recalculateProgress: true, // Interval in milliseconds to calculate and trigger progress events: progressInterval: 100, // Interval in milliseconds to calculate progress bitrate: bitrateInterval: 500, // By default, uploads are started automatically when adding files: autoUpload: true, // Error and info messages: messages: { uploadedBytes: 'Uploaded bytes exceed file size' }, // Translation function, gets the message key to be translated // and an object with context specific data as arguments: i18n: function (message, context) { message = this.messages[message] || message.toString(); if (context) { $.each(context, function (key, value) { message = message.replace('{' + key + '}', value); }); } return message; }, // Additional form data to be sent along with the file uploads can be set // using this option, which accepts an array of objects with name and // value properties, a function returning such an array, a FormData // object (for XHR file uploads), or a simple object. // The form of the first fileInput is given as parameter to the function: formData: function (form) { return form.serializeArray(); }, // The add callback is invoked as soon as files are added to the fileupload // widget (via file input selection, drag & drop, paste or add API call). // If the singleFileUploads option is enabled, this callback will be // called once for each file in the selection for XHR file uploads, else // once for each file selection. // // The upload starts when the submit method is invoked on the data parameter. // The data object contains a files property holding the added files // and allows you to override plugin options as well as define ajax settings. // // Listeners for this callback can also be bound the following way: // .bind('fileuploadadd', func); // // data.submit() returns a Promise object and allows to attach additional // handlers using jQuery's Deferred callbacks: // data.submit().done(func).fail(func).always(func); add: function (e, data) { if (e.isDefaultPrevented()) { return false; } if (data.autoUpload || (data.autoUpload !== false && $(this).fileupload('option', 'autoUpload'))) { data.process().done(function () { data.submit(); }); } }, // Other callbacks: // Callback for the submit event of each file upload: // submit: function (e, data) {}, // .bind('fileuploadsubmit', func); // Callback for the start of each file upload request: // send: function (e, data) {}, // .bind('fileuploadsend', func); // Callback for successful uploads: // done: function (e, data) {}, // .bind('fileuploaddone', func); // Callback for failed (abort or error) uploads: // fail: function (e, data) {}, // .bind('fileuploadfail', func); // Callback for completed (success, abort or error) requests: // always: function (e, data) {}, // .bind('fileuploadalways', func); // Callback for upload progress events: // progress: function (e, data) {}, // .bind('fileuploadprogress', func); // Callback for global upload progress events: // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func); // Callback for uploads start, equivalent to the global ajaxStart event: // start: function (e) {}, // .bind('fileuploadstart', func); // Callback for uploads stop, equivalent to the global ajaxStop event: // stop: function (e) {}, // .bind('fileuploadstop', func); // Callback for change events of the fileInput(s): // change: function (e, data) {}, // .bind('fileuploadchange', func); // Callback for paste events to the pasteZone(s): // paste: function (e, data) {}, // .bind('fileuploadpaste', func); // Callback for drop events of the dropZone(s): // drop: function (e, data) {}, // .bind('fileuploaddrop', func); // Callback for dragover events of the dropZone(s): // dragover: function (e) {}, // .bind('fileuploaddragover', func); // Callback for the start of each chunk upload request: // chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func); // Callback for successful chunk uploads: // chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func); // Callback for failed (abort or error) chunk uploads: // chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func); // Callback for completed (success, abort or error) chunk upload requests: // chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func); // The plugin options are used as settings object for the ajax calls. // The following are jQuery ajax settings required for the file uploads: processData: false, contentType: false, cache: false }, // A list of options that require reinitializing event listeners and/or // special initialization code: _specialOptions: [ 'fileInput', 'dropZone', 'pasteZone', 'multipart', 'forceIframeTransport' ], _blobSlice: $.support.blobSlice && function () { var slice = this.slice || this.webkitSlice || this.mozSlice; return slice.apply(this, arguments); }, _BitrateTimer: function () { this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime()); this.loaded = 0; this.bitrate = 0; this.getBitrate = function (now, loaded, interval) { var timeDiff = now - this.timestamp; if (!this.bitrate || !interval || timeDiff > interval) { this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8; this.loaded = loaded; this.timestamp = now; } return this.bitrate; }; }, _isXHRUpload: function (options) { return !options.forceIframeTransport && ((!options.multipart && $.support.xhrFileUpload) || $.support.xhrFormDataFileUpload); }, _getFormData: function (options) { var formData; if (typeof options.formData === 'function') { return options.formData(options.form); } if ($.isArray(options.formData)) { return options.formData; } if ($.type(options.formData) === 'object') { formData = []; $.each(options.formData, function (name, value) { formData.push({name: name, value: value}); }); return formData; } return []; }, _getTotal: function (files) { var total = 0; $.each(files, function (index, file) { total += file.size || 1; }); return total; }, _initProgressObject: function (obj) { var progress = { loaded: 0, total: 0, bitrate: 0 }; if (obj._progress) { $.extend(obj._progress, progress); } else { obj._progress = progress; } }, _initResponseObject: function (obj) { var prop; if (obj._response) { for (prop in obj._response) { if (obj._response.hasOwnProperty(prop)) { delete obj._response[prop]; } } } else { obj._response = {}; } }, _onProgress: function (e, data) { if (e.lengthComputable) { var now = ((Date.now) ? Date.now() : (new Date()).getTime()), loaded; if (data._time && data.progressInterval && (now - data._time < data.progressInterval) && e.loaded !== e.total) { return; } data._time = now; loaded = Math.floor( e.loaded / e.total * (data.chunkSize || data._progress.total) ) + (data.uploadedBytes || 0); // Add the difference from the previously loaded state // to the global loaded counter: this._progress.loaded += (loaded - data._progress.loaded); this._progress.bitrate = this._bitrateTimer.getBitrate( now, this._progress.loaded, data.bitrateInterval ); data._progress.loaded = data.loaded = loaded; data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate( now, loaded, data.bitrateInterval ); // Trigger a custom progress event with a total data property set // to the file size(s) of the current upload and a loaded data // property calculated accordingly: this._trigger( 'progress', $.Event('progress', {delegatedEvent: e}), data ); // Trigger a global progress event for all current file uploads, // including ajax calls queued for sequential file uploads: this._trigger( 'progressall', $.Event('progressall', {delegatedEvent: e}), this._progress ); } }, _initProgressListener: function (options) { var that = this, xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr(); // Accesss to the native XHR object is required to add event listeners // for the upload progress event: if (xhr.upload) { $(xhr.upload).bind('progress', function (e) { var oe = e.originalEvent; // Make sure the progress event properties get copied over: e.lengthComputable = oe.lengthComputable; e.loaded = oe.loaded; e.total = oe.total; that._onProgress(e, options); }); options.xhr = function () { return xhr; }; } }, _isInstanceOf: function (type, obj) { // Cross-frame instanceof check return Object.prototype.toString.call(obj) === '[object ' + type + ']'; }, _initXHRData: function (options) { var that = this, formData, file = options.files[0], // Ignore non-multipart setting if not supported: multipart = options.multipart || !$.support.xhrFileUpload, paramName = options.paramName[0]; options.headers = $.extend({}, options.headers); if (options.contentRange) { options.headers['Content-Range'] = options.contentRange; } if (!multipart || options.blob || !this._isInstanceOf('File', file)) { options.headers['Content-Disposition'] = 'attachment; filename="' + encodeURI(file.name) + '"'; } if (!multipart) { options.contentType = file.type; options.data = options.blob || file; } else if ($.support.xhrFormDataFileUpload) { if (options.postMessage) { // window.postMessage does not allow sending FormData // objects, so we just add the File/Blob objects to // the formData array and let the postMessage window // create the FormData object out of this array: formData = this._getFormData(options); if (options.blob) { formData.push({ name: paramName, value: options.blob }); } else { $.each(options.files, function (index, file) { formData.push({ name: options.paramName[index] || paramName, value: file }); }); } } else { if (that._isInstanceOf('FormData', options.formData)) { formData = options.formData; } else { formData = new FormData(); $.each(this._getFormData(options), function (index, field) { formData.append(field.name, field.value); }); } if (options.blob) { formData.append(paramName, options.blob, file.name); } else { $.each(options.files, function (index, file) { // This check allows the tests to run with // dummy objects: if (that._isInstanceOf('File', file) || that._isInstanceOf('Blob', file)) { formData.append( options.paramName[index] || paramName, file, file.name ); } }); } } options.data = formData; } // Blob reference is not needed anymore, free memory: options.blob = null; }, _initIframeSettings: function (options) { var targetHost = $('').prop('href', options.url).prop('host'); // Setting the dataType to iframe enables the iframe transport: options.dataType = 'iframe ' + (options.dataType || ''); // The iframe transport accepts a serialized array as form data: options.formData = this._getFormData(options); // Add redirect url to form data on cross-domain uploads: if (options.redirect && targetHost && targetHost !== location.host) { options.formData.push({ name: options.redirectParamName || 'redirect', value: options.redirect }); } }, _initDataSettings: function (options) { if (this._isXHRUpload(options)) { if (!this._chunkedUpload(options, true)) { if (!options.data) { this._initXHRData(options); } this._initProgressListener(options); } if (options.postMessage) { // Setting the dataType to postmessage enables the // postMessage transport: options.dataType = 'postmessage ' + (options.dataType || ''); } } else { this._initIframeSettings(options); } }, _getParamName: function (options) { var fileInput = $(options.fileInput), paramName = options.paramName; if (!paramName) { paramName = []; fileInput.each(function () { var input = $(this), name = input.prop('name') || 'files[]', i = (input.prop('files') || [1]).length; while (i) { paramName.push(name); i -= 1; } }); if (!paramName.length) { paramName = [fileInput.prop('name') || 'files[]']; } } else if (!$.isArray(paramName)) { paramName = [paramName]; } return paramName; }, _initFormSettings: function (options) { // Retrieve missing options from the input field and the // associated form, if available: if (!options.form || !options.form.length) { options.form = $(options.fileInput.prop('form')); // If the given file input doesn't have an associated form, // use the default widget file input's form: if (!options.form.length) { options.form = $(this.options.fileInput.prop('form')); } } options.paramName = this._getParamName(options); if (!options.url) { options.url = options.form.prop('action') || location.href; } // The HTTP request method must be "POST" or "PUT": options.type = (options.type || ($.type(options.form.prop('method')) === 'string' && options.form.prop('method')) || '' ).toUpperCase(); if (options.type !== 'POST' && options.type !== 'PUT' && options.type !== 'PATCH') { options.type = 'POST'; } if (!options.formAcceptCharset) { options.formAcceptCharset = options.form.attr('accept-charset'); } }, _getAJAXSettings: function (data) { var options = $.extend({}, this.options, data); this._initFormSettings(options); this._initDataSettings(options); return options; }, // jQuery 1.6 doesn't provide .state(), // while jQuery 1.8+ removed .isRejected() and .isResolved(): _getDeferredState: function (deferred) { if (deferred.state) { return deferred.state(); } if (deferred.isResolved()) { return 'resolved'; } if (deferred.isRejected()) { return 'rejected'; } return 'pending'; }, // Maps jqXHR callbacks to the equivalent // methods of the given Promise object: _enhancePromise: function (promise) { promise.success = promise.done; promise.error = promise.fail; promise.complete = promise.always; return promise; }, // Creates and returns a Promise object enhanced with // the jqXHR methods abort, success, error and complete: _getXHRPromise: function (resolveOrReject, context, args) { var dfd = $.Deferred(), promise = dfd.promise(); context = context || this.options.context || promise; if (resolveOrReject === true) { dfd.resolveWith(context, args); } else if (resolveOrReject === false) { dfd.rejectWith(context, args); } promise.abort = dfd.promise; return this._enhancePromise(promise); }, // Adds convenience methods to the data callback argument: _addConvenienceMethods: function (e, data) { var that = this, getPromise = function (data) { return $.Deferred().resolveWith(that, [data]).promise(); }; data.process = function (resolveFunc, rejectFunc) { if (resolveFunc || rejectFunc) { data._processQueue = this._processQueue = (this._processQueue || getPromise(this)) .pipe(resolveFunc, rejectFunc); } return this._processQueue || getPromise(this); }; data.submit = function () { if (this.state() !== 'pending') { data.jqXHR = this.jqXHR = (that._trigger( 'submit', $.Event('submit', {delegatedEvent: e}), this ) !== false) && that._onSend(e, this); } return this.jqXHR || that._getXHRPromise(); }; data.abort = function () { if (this.jqXHR) { return this.jqXHR.abort(); } return that._getXHRPromise(); }; data.state = function () { if (this.jqXHR) { return that._getDeferredState(this.jqXHR); } if (this._processQueue) { return that._getDeferredState(this._processQueue); } }; data.progress = function () { return this._progress; }; data.response = function () { return this._response; }; }, // Parses the Range header from the server response // and returns the uploaded bytes: _getUploadedBytes: function (jqXHR) { var range = jqXHR.getResponseHeader('Range'), parts = range && range.split('-'), upperBytesPos = parts && parts.length > 1 && parseInt(parts[1], 10); return upperBytesPos && upperBytesPos + 1; }, // Uploads a file in multiple, sequential requests // by splitting the file up in multiple blob chunks. // If the second parameter is true, only tests if the file // should be uploaded in chunks, but does not invoke any // upload requests: _chunkedUpload: function (options, testOnly) { options.uploadedBytes = options.uploadedBytes || 0; var that = this, file = options.files[0], fs = file.size, ub = options.uploadedBytes, mcs = options.maxChunkSize || fs, slice = this._blobSlice, dfd = $.Deferred(), promise = dfd.promise(), jqXHR, upload; if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) || options.data) { return false; } if (testOnly) { return true; } if (ub >= fs) { file.error = options.i18n('uploadedBytes'); return this._getXHRPromise( false, options.context, [null, 'error', file.error] ); } // The chunk upload method: upload = function () { // Clone the options object for each chunk upload: var o = $.extend({}, options), currentLoaded = o._progress.loaded; o.blob = slice.call( file, ub, ub + mcs, file.type ); // Store the current chunk size, as the blob itself // will be dereferenced after data processing: o.chunkSize = o.blob.size; // Expose the chunk bytes position range: o.contentRange = 'bytes ' + ub + '-' + (ub + o.chunkSize - 1) + '/' + fs; // Process the upload data (the blob and potential form data): that._initXHRData(o); // Add progress listeners for this chunk upload: that._initProgressListener(o); jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) || that._getXHRPromise(false, o.context)) .done(function (result, textStatus, jqXHR) { ub = that._getUploadedBytes(jqXHR) || (ub + o.chunkSize); // Create a progress event if no final progress event // with loaded equaling total has been triggered // for this chunk: if (currentLoaded + o.chunkSize - o._progress.loaded) { that._onProgress($.Event('progress', { lengthComputable: true, loaded: ub - o.uploadedBytes, total: ub - o.uploadedBytes }), o); } options.uploadedBytes = o.uploadedBytes = ub; o.result = result; o.textStatus = textStatus; o.jqXHR = jqXHR; that._trigger('chunkdone', null, o); that._trigger('chunkalways', null, o); if (ub < fs) { // File upload not yet complete, // continue with the next chunk: upload(); } else { dfd.resolveWith( o.context, [result, textStatus, jqXHR] ); } }) .fail(function (jqXHR, textStatus, errorThrown) { o.jqXHR = jqXHR; o.textStatus = textStatus; o.errorThrown = errorThrown; that._trigger('chunkfail', null, o); that._trigger('chunkalways', null, o); dfd.rejectWith( o.context, [jqXHR, textStatus, errorThrown] ); }); }; this._enhancePromise(promise); promise.abort = function () { return jqXHR.abort(); }; upload(); return promise; }, _beforeSend: function (e, data) { if (this._active === 0) { // the start callback is triggered when an upload starts // and no other uploads are currently running, // equivalent to the global ajaxStart event: this._trigger('start'); // Set timer for global bitrate progress calculation: this._bitrateTimer = new this._BitrateTimer(); // Reset the global progress values: this._progress.loaded = this._progress.total = 0; this._progress.bitrate = 0; } // Make sure the container objects for the .response() and // .progress() methods on the data object are available // and reset to their initial state: this._initResponseObject(data); this._initProgressObject(data); data._progress.loaded = data.loaded = data.uploadedBytes || 0; data._progress.total = data.total = this._getTotal(data.files) || 1; data._progress.bitrate = data.bitrate = 0; this._active += 1; // Initialize the global progress values: this._progress.loaded += data.loaded; this._progress.total += data.total; }, _onDone: function (result, textStatus, jqXHR, options) { var total = options._progress.total, response = options._response; if (options._progress.loaded < total) { // Create a progress event if no final progress event // with loaded equaling total has been triggered: this._onProgress($.Event('progress', { lengthComputable: true, loaded: total, total: total }), options); } response.result = options.result = result; response.textStatus = options.textStatus = textStatus; response.jqXHR = options.jqXHR = jqXHR; this._trigger('done', null, options); }, _onFail: function (jqXHR, textStatus, errorThrown, options) { var response = options._response; if (options.recalculateProgress) { // Remove the failed (error or abort) file upload from // the global progress calculation: this._progress.loaded -= options._progress.loaded; this._progress.total -= options._progress.total; } response.jqXHR = options.jqXHR = jqXHR; response.textStatus = options.textStatus = textStatus; response.errorThrown = options.errorThrown = errorThrown; this._trigger('fail', null, options); }, _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) { // jqXHRorResult, textStatus and jqXHRorError are added to the // options object via done and fail callbacks this._trigger('always', null, options); }, _onSend: function (e, data) { if (!data.submit) { this._addConvenienceMethods(e, data); } var that = this, jqXHR, aborted, slot, pipe, options = that._getAJAXSettings(data), send = function () { that._sending += 1; // Set timer for bitrate progress calculation: options._bitrateTimer = new that._BitrateTimer(); jqXHR = jqXHR || ( ((aborted || that._trigger( 'send', $.Event('send', {delegatedEvent: e}), options ) === false) && that._getXHRPromise(false, options.context, aborted)) || that._chunkedUpload(options) || $.ajax(options) ).done(function (result, textStatus, jqXHR) { that._onDone(result, textStatus, jqXHR, options); }).fail(function (jqXHR, textStatus, errorThrown) { that._onFail(jqXHR, textStatus, errorThrown, options); }).always(function (jqXHRorResult, textStatus, jqXHRorError) { that._onAlways( jqXHRorResult, textStatus, jqXHRorError, options ); that._sending -= 1; that._active -= 1; if (options.limitConcurrentUploads && options.limitConcurrentUploads > that._sending) { // Start the next queued upload, // that has not been aborted: var nextSlot = that._slots.shift(); while (nextSlot) { if (that._getDeferredState(nextSlot) === 'pending') { nextSlot.resolve(); break; } nextSlot = that._slots.shift(); } } if (that._active === 0) { // The stop callback is triggered when all uploads have // been completed, equivalent to the global ajaxStop event: that._trigger('stop'); } }); return jqXHR; }; this._beforeSend(e, options); if (this.options.sequentialUploads || (this.options.limitConcurrentUploads && this.options.limitConcurrentUploads <= this._sending)) { if (this.options.limitConcurrentUploads > 1) { slot = $.Deferred(); this._slots.push(slot); pipe = slot.pipe(send); } else { this._sequence = this._sequence.pipe(send, send); pipe = this._sequence; } // Return the piped Promise object, enhanced with an abort method, // which is delegated to the jqXHR object of the current upload, // and jqXHR callbacks mapped to the equivalent Promise methods: pipe.abort = function () { aborted = [undefined, 'abort', 'abort']; if (!jqXHR) { if (slot) { slot.rejectWith(options.context, aborted); } return send(); } return jqXHR.abort(); }; return this._enhancePromise(pipe); } return send(); }, _onAdd: function (e, data) { var that = this, result = true, options = $.extend({}, this.options, data), limit = options.limitMultiFileUploads, paramName = this._getParamName(options), paramNameSet, paramNameSlice, fileSet, i; if (!(options.singleFileUploads || limit) || !this._isXHRUpload(options)) { fileSet = [data.files]; paramNameSet = [paramName]; } else if (!options.singleFileUploads && limit) { fileSet = []; paramNameSet = []; for (i = 0; i < data.files.length; i += limit) { fileSet.push(data.files.slice(i, i + limit)); paramNameSlice = paramName.slice(i, i + limit); if (!paramNameSlice.length) { paramNameSlice = paramName; } paramNameSet.push(paramNameSlice); } } else { paramNameSet = paramName; } data.originalFiles = data.files; $.each(fileSet || data.files, function (index, element) { var newData = $.extend({}, data); newData.files = fileSet ? element : [element]; newData.paramName = paramNameSet[index]; that._initResponseObject(newData); that._initProgressObject(newData); that._addConvenienceMethods(e, newData); result = that._trigger( 'add', $.Event('add', {delegatedEvent: e}), newData ); return result; }); return result; }, _replaceFileInput: function (input) { var inputClone = input.clone(true); $('
            ').append(inputClone)[0].reset(); // Detaching allows to insert the fileInput on another form // without loosing the file input value: input.after(inputClone).detach(); // Avoid memory leaks with the detached file input: $.cleanData(input.unbind('remove')); // Replace the original file input element in the fileInput // elements set with the clone, which has been copied including // event handlers: this.options.fileInput = this.options.fileInput.map(function (i, el) { if (el === input[0]) { return inputClone[0]; } return el; }); // If the widget has been initialized on the file input itself, // override this.element with the file input clone: if (input[0] === this.element[0]) { this.element = inputClone; } }, _handleFileTreeEntry: function (entry, path) { var that = this, dfd = $.Deferred(), errorHandler = function (e) { if (e && !e.entry) { e.entry = entry; } // Since $.when returns immediately if one // Deferred is rejected, we use resolve instead. // This allows valid files and invalid items // to be returned together in one set: dfd.resolve([e]); }, dirReader; path = path || ''; if (entry.isFile) { if (entry._file) { // Workaround for Chrome bug #149735 entry._file.relativePath = path; dfd.resolve(entry._file); } else { entry.file(function (file) { file.relativePath = path; dfd.resolve(file); }, errorHandler); } } else if (entry.isDirectory) { dirReader = entry.createReader(); dirReader.readEntries(function (entries) { that._handleFileTreeEntries( entries, path + entry.name + '/' ).done(function (files) { dfd.resolve(files); }).fail(errorHandler); }, errorHandler); } else { // Return an empy list for file system items // other than files or directories: dfd.resolve([]); } return dfd.promise(); }, _handleFileTreeEntries: function (entries, path) { var that = this; return $.when.apply( $, $.map(entries, function (entry) { return that._handleFileTreeEntry(entry, path); }) ).pipe(function () { return Array.prototype.concat.apply( [], arguments ); }); }, _getDroppedFiles: function (dataTransfer) { dataTransfer = dataTransfer || {}; var items = dataTransfer.items; if (items && items.length && (items[0].webkitGetAsEntry || items[0].getAsEntry)) { return this._handleFileTreeEntries( $.map(items, function (item) { var entry; if (item.webkitGetAsEntry) { entry = item.webkitGetAsEntry(); if (entry) { // Workaround for Chrome bug #149735: entry._file = item.getAsFile(); } return entry; } return item.getAsEntry(); }) ); } return $.Deferred().resolve( $.makeArray(dataTransfer.files) ).promise(); }, _getSingleFileInputFiles: function (fileInput) { fileInput = $(fileInput); var entries = fileInput.prop('webkitEntries') || fileInput.prop('entries'), files, value; if (entries && entries.length) { return this._handleFileTreeEntries(entries); } files = $.makeArray(fileInput.prop('files')); if (!files.length) { value = fileInput.prop('value'); if (!value) { return $.Deferred().resolve([]).promise(); } // If the files property is not available, the browser does not // support the File API and we add a pseudo File object with // the input value as name with path information removed: files = [{name: value.replace(/^.*\\/, '')}]; } else if (files[0].name === undefined && files[0].fileName) { // File normalization for Safari 4 and Firefox 3: $.each(files, function (index, file) { file.name = file.fileName; file.size = file.fileSize; }); } return $.Deferred().resolve(files).promise(); }, _getFileInputFiles: function (fileInput) { if (!(fileInput instanceof $) || fileInput.length === 1) { return this._getSingleFileInputFiles(fileInput); } return $.when.apply( $, $.map(fileInput, this._getSingleFileInputFiles) ).pipe(function () { return Array.prototype.concat.apply( [], arguments ); }); }, _onChange: function (e) { var that = this, data = { fileInput: $(e.target), form: $(e.target.form) }; this._getFileInputFiles(data.fileInput).always(function (files) { data.files = files; if (that.options.replaceFileInput) { that._replaceFileInput(data.fileInput); } if (that._trigger( 'change', $.Event('change', {delegatedEvent: e}), data ) !== false) { that._onAdd(e, data); } }); }, _onPaste: function (e) { var items = e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.items, data = {files: []}; if (items && items.length) { $.each(items, function (index, item) { var file = item.getAsFile && item.getAsFile(); if (file) { data.files.push(file); } }); if (this._trigger( 'paste', $.Event('paste', {delegatedEvent: e}), data ) !== false) { this._onAdd(e, data); } } }, _onDrop: function (e) { e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer; var that = this, dataTransfer = e.dataTransfer, data = {}; if (dataTransfer && dataTransfer.files && dataTransfer.files.length) { e.preventDefault(); this._getDroppedFiles(dataTransfer).always(function (files) { data.files = files; if (that._trigger( 'drop', $.Event('drop', {delegatedEvent: e}), data ) !== false) { that._onAdd(e, data); } }); } }, _onDragOver: function (e) { e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer; var dataTransfer = e.dataTransfer; if (dataTransfer && $.inArray('Files', dataTransfer.types) !== -1 && this._trigger( 'dragover', $.Event('dragover', {delegatedEvent: e}) ) !== false) { e.preventDefault(); dataTransfer.dropEffect = 'copy'; } }, _initEventHandlers: function () { if (this._isXHRUpload(this.options)) { this._on(this.options.dropZone, { dragover: this._onDragOver, drop: this._onDrop }); this._on(this.options.pasteZone, { paste: this._onPaste }); } if ($.support.fileInput) { this._on(this.options.fileInput, { change: this._onChange }); } }, _destroyEventHandlers: function () { this._off(this.options.dropZone, 'dragover drop'); this._off(this.options.pasteZone, 'paste'); this._off(this.options.fileInput, 'change'); }, _setOption: function (key, value) { var reinit = $.inArray(key, this._specialOptions) !== -1; if (reinit) { this._destroyEventHandlers(); } this._super(key, value); if (reinit) { this._initSpecialOptions(); this._initEventHandlers(); } }, _initSpecialOptions: function () { var options = this.options; if (options.fileInput === undefined) { options.fileInput = this.element.is('input[type="file"]') ? this.element : this.element.find('input[type="file"]'); } else if (!(options.fileInput instanceof $)) { options.fileInput = $(options.fileInput); } if (!(options.dropZone instanceof $)) { options.dropZone = $(options.dropZone); } if (!(options.pasteZone instanceof $)) { options.pasteZone = $(options.pasteZone); } }, _getRegExp: function (str) { var parts = str.split('/'), modifiers = parts.pop(); parts.shift(); return new RegExp(parts.join('/'), modifiers); }, _isRegExpOption: function (key, value) { return key !== 'url' && $.type(value) === 'string' && /^\/.*\/[igm]{0,3}$/.test(value); }, _initDataAttributes: function () { var that = this, options = this.options; // Initialize options set via HTML5 data-attributes: $.each( $(this.element[0].cloneNode(false)).data(), function (key, value) { if (that._isRegExpOption(key, value)) { value = that._getRegExp(value); } options[key] = value; } ); }, _create: function () { this._initDataAttributes(); this._initSpecialOptions(); this._slots = []; this._sequence = this._getXHRPromise(true); this._sending = this._active = 0; this._initProgressObject(this); this._initEventHandlers(); }, // This method is exposed to the widget API and allows to query // the number of active uploads: active: function () { return this._active; }, // This method is exposed to the widget API and allows to query // the widget upload progress. // It returns an object with loaded, total and bitrate properties // for the running uploads: progress: function () { return this._progress; }, // This method is exposed to the widget API and allows adding files // using the fileupload API. The data parameter accepts an object which // must have a files property and can contain additional options: // .fileupload('add', {files: filesList}); add: function (data) { var that = this; if (!data || this.options.disabled) { return; } if (data.fileInput && !data.files) { this._getFileInputFiles(data.fileInput).always(function (files) { data.files = files; that._onAdd(null, data); }); } else { data.files = $.makeArray(data.files); this._onAdd(null, data); } }, // This method is exposed to the widget API and allows sending files // using the fileupload API. The data parameter accepts an object which // must have a files or fileInput property and can contain additional options: // .fileupload('send', {files: filesList}); // The method returns a Promise object for the file upload call. send: function (data) { if (data && !this.options.disabled) { if (data.fileInput && !data.files) { var that = this, dfd = $.Deferred(), promise = dfd.promise(), jqXHR, aborted; promise.abort = function () { aborted = true; if (jqXHR) { return jqXHR.abort(); } dfd.reject(null, 'abort', 'abort'); return promise; }; this._getFileInputFiles(data.fileInput).always( function (files) { if (aborted) { return; } if (!files.length) { dfd.reject(); return; } data.files = files; jqXHR = that._onSend(null, data).then( function (result, textStatus, jqXHR) { dfd.resolve(result, textStatus, jqXHR); }, function (jqXHR, textStatus, errorThrown) { dfd.reject(jqXHR, textStatus, errorThrown); } ); } ); return this._enhancePromise(promise); } data.files = $.makeArray(data.files); if (data.files.length) { return this._onSend(null, data); } } return this._getXHRPromise(false, data && data.context); } }); })); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/js/jquery.iframe-transport.js ================================================ /* * jQuery Iframe Transport Plugin 1.8.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint unparam: true, nomen: true */ /*global define, window, document */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery'], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; // Helper variable to create unique names for the transport iframes: var counter = 0; // The iframe transport accepts four additional options: // options.fileInput: a jQuery collection of file input fields // options.paramName: the parameter name for the file form data, // overrides the name property of the file input field(s), // can be a string or an array of strings. // options.formData: an array of objects with name and value properties, // equivalent to the return data of .serializeArray(), e.g.: // [{name: 'a', value: 1}, {name: 'b', value: 2}] // options.initialIframeSrc: the URL of the initial iframe src, // by default set to "javascript:false;" $.ajaxTransport('iframe', function (options) { if (options.async) { // javascript:false as initial iframe src // prevents warning popups on HTTPS in IE6: var initialIframeSrc = options.initialIframeSrc || 'javascript:false;', form, iframe, addParamChar; return { send: function (_, completeCallback) { form = $('
            '); form.attr('accept-charset', options.formAcceptCharset); addParamChar = /\?/.test(options.url) ? '&' : '?'; // XDomainRequest only supports GET and POST: if (options.type === 'DELETE') { options.url = options.url + addParamChar + '_method=DELETE'; options.type = 'POST'; } else if (options.type === 'PUT') { options.url = options.url + addParamChar + '_method=PUT'; options.type = 'POST'; } else if (options.type === 'PATCH') { options.url = options.url + addParamChar + '_method=PATCH'; options.type = 'POST'; } // IE versions below IE8 cannot set the name property of // elements that have already been added to the DOM, // so we set the name along with the iframe HTML markup: counter += 1; iframe = $( '' ).bind('load', function () { var fileInputClones, paramNames = $.isArray(options.paramName) ? options.paramName : [options.paramName]; iframe .unbind('load') .bind('load', function () { var response; // Wrap in a try/catch block to catch exceptions thrown // when trying to access cross-domain iframe contents: try { response = iframe.contents(); // Google Chrome and Firefox do not throw an // exception when calling iframe.contents() on // cross-domain requests, so we unify the response: if (!response.length || !response[0].firstChild) { throw new Error(); } } catch (e) { response = undefined; } // The complete callback returns the // iframe content document as response object: completeCallback( 200, 'success', {'iframe': response} ); // Fix for IE endless progress bar activity bug // (happens on form submits to iframe targets): $('') .appendTo(form); window.setTimeout(function () { // Removing the form in a setTimeout call // allows Chrome's developer tools to display // the response result form.remove(); }, 0); }); form .prop('target', iframe.prop('name')) .prop('action', options.url) .prop('method', options.type); if (options.formData) { $.each(options.formData, function (index, field) { $('') .prop('name', field.name) .val(field.value) .appendTo(form); }); } if (options.fileInput && options.fileInput.length && options.type === 'POST') { fileInputClones = options.fileInput.clone(); // Insert a clone for each file input field: options.fileInput.after(function (index) { return fileInputClones[index]; }); if (options.paramName) { options.fileInput.each(function (index) { $(this).prop( 'name', paramNames[index] || options.paramName ); }); } // Appending the file input fields to the hidden form // removes them from their original location: form .append(options.fileInput) .prop('enctype', 'multipart/form-data') // enctype must be set as encoding for IE: .prop('encoding', 'multipart/form-data'); } form.submit(); // Insert the file input fields at their original location // by replacing the clones with the originals: if (fileInputClones && fileInputClones.length) { options.fileInput.each(function (index, input) { var clone = $(fileInputClones[index]); $(input).prop('name', clone.prop('name')); clone.replaceWith(input); }); } }); form.append(iframe).appendTo(document.body); }, abort: function () { if (iframe) { // javascript:false as iframe src aborts the request // and prevents warning popups on HTTPS in IE6. // concat is used to avoid the "Script URL" JSLint error: iframe .unbind('load') .prop('src', initialIframeSrc); } if (form) { form.remove(); } } }; } }); // The iframe transport returns the iframe content document as response. // The following adds converters from iframe to text, json, html, xml // and script. // Please note that the Content-Type for JSON responses has to be text/plain // or text/html, if the browser doesn't include application/json in the // Accept header, else IE will show a download dialog. // The Content-Type for XML responses on the other hand has to be always // application/xml or text/xml, so IE properly parses the XML response. // See also // https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation $.ajaxSetup({ converters: { 'iframe text': function (iframe) { return iframe && $(iframe[0].body).text(); }, 'iframe json': function (iframe) { return iframe && $.parseJSON($(iframe[0].body).text()); }, 'iframe html': function (iframe) { return iframe && $(iframe[0].body).html(); }, 'iframe xml': function (iframe) { var xmlDoc = iframe && iframe[0]; return xmlDoc && $.isXMLDoc(xmlDoc) ? xmlDoc : $.parseXML((xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) || $(xmlDoc.body).html()); }, 'iframe script': function (iframe) { return iframe && $.globalEval($(iframe[0].body).text()); } } }); })); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/js/main.js ================================================ /* * jQuery File Upload Plugin JS Example 8.9.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, regexp: true */ /*global $, window, blueimp */ $(function () { 'use strict'; // Initialize the jQuery File Upload widget: $('#fileupload').fileupload({ // Uncomment the following to send cross-domain cookies: //xhrFields: {withCredentials: true}, url: 'server/php/' }); // Enable iframe cross-domain access via redirect option: $('#fileupload').fileupload( 'option', 'redirect', window.location.href.replace( /\/[^\/]*$/, '/cors/result.html?%s' ) ); if (window.location.hostname === 'blueimp.github.io') { // Demo settings: $('#fileupload').fileupload('option', { url: '//jquery-file-upload.appspot.com/', // Enable image resizing, except for Android and Opera, // which actually support image resizing, but fail to // send Blob objects via XHR requests: disableImageResize: /Android(?!.*Chrome)|Opera/ .test(window.navigator.userAgent), maxFileSize: 5000000, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i }); // Upload server status check for browsers with CORS support: if ($.support.cors) { $.ajax({ url: '//jquery-file-upload.appspot.com/', type: 'HEAD' }).fail(function () { $('
            ') .text('Upload server currently unavailable - ' + new Date()) .appendTo('#fileupload'); }); } } else { // Load existing files: $('#fileupload').addClass('fileupload-processing'); $.ajax({ // Uncomment the following to send cross-domain cookies: //xhrFields: {withCredentials: true}, url: $('#fileupload').fileupload('option', 'url'), dataType: 'json', context: $('#fileupload')[0] }).always(function () { $(this).removeClass('fileupload-processing'); }).done(function (result) { $(this).fileupload('option', 'done') .call(this, $.Event('done'), {result: result}); }); } }); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/js/vendor/jquery.ui.widget.js ================================================ /* * jQuery UI Widget 1.10.3+amd * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/jQuery.widget/ */ (function (factory) { if (typeof define === "function" && define.amd) { // Register as an anonymous AMD module: define(["jquery"], factory); } else { // Browser globals: factory(jQuery); } }(function( $, undefined ) { var uuid = 0, slice = Array.prototype.slice, _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } _cleanData( elems ); }; $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); }; $.widget.extend = function( target ) { var input = slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "
            ", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) // 1.9 BC for #7810 // TODO remove dual storage .removeData( this.widgetName ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( value === undefined ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( value === undefined ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value ) .attr( "aria-disabled", value ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } return this; }, enable: function() { return this._setOption( "disabled", false ); }, disable: function() { return this._setOption( "disabled", true ); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { // accept selectors, DOM elements element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^(\w+)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); })); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/package.json ================================================ { "name": "blueimp-file-upload", "version": "8.9.0", "title": "jQuery File Upload", "description": "File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (Google App Engine, PHP, Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads.", "keywords": [ "jquery", "file", "upload", "widget", "multiple", "selection", "drag", "drop", "progress", "preview", "cross-domain", "cross-site", "chunk", "resume", "gae", "go", "python", "php", "bootstrap" ], "homepage": "https://github.com/blueimp/jQuery-File-Upload", "author": { "name": "Sebastian Tschan", "url": "https://blueimp.net" }, "maintainers": [ { "name": "Sebastian Tschan", "url": "https://blueimp.net" } ], "repository": { "type": "git", "url": "git://github.com/blueimp/jQuery-File-Upload.git" }, "bugs": "https://github.com/blueimp/jQuery-File-Upload/issues", "licenses": [ { "type": "MIT", "url": "http://www.opensource.org/licenses/MIT" } ], "dependencies": { "jquery": ">=1.6", "blueimp-tmpl": ">=2.3.0", "blueimp-load-image": ">=1.9.1", "blueimp-canvas-to-blob": ">=2.0.7" } } ================================================ FILE: public/packages/jquery-file-upload-8.9.0/server/gae-go/app/main.go ================================================ /* * jQuery File Upload Plugin GAE Go Example 3.1.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ package app import ( "appengine" "appengine/blobstore" "appengine/image" "appengine/taskqueue" "bytes" "encoding/json" "fmt" "io" "log" "mime/multipart" "net/http" "net/url" "regexp" "strings" "time" ) const ( WEBSITE = "http://blueimp.github.io/jQuery-File-Upload/" MIN_FILE_SIZE = 1 // bytes MAX_FILE_SIZE = 5000000 // bytes IMAGE_TYPES = "image/(gif|p?jpeg|(x-)?png)" ACCEPT_FILE_TYPES = IMAGE_TYPES EXPIRATION_TIME = 300 // seconds THUMBNAIL_PARAM = "=s80" ) var ( imageTypes = regexp.MustCompile(IMAGE_TYPES) acceptFileTypes = regexp.MustCompile(ACCEPT_FILE_TYPES) ) type FileInfo struct { Key appengine.BlobKey `json:"-"` Url string `json:"url,omitempty"` ThumbnailUrl string `json:"thumbnailUrl,omitempty"` Name string `json:"name"` Type string `json:"type"` Size int64 `json:"size"` Error string `json:"error,omitempty"` DeleteUrl string `json:"deleteUrl,omitempty"` DeleteType string `json:"deleteType,omitempty"` } func (fi *FileInfo) ValidateType() (valid bool) { if acceptFileTypes.MatchString(fi.Type) { return true } fi.Error = "Filetype not allowed" return false } func (fi *FileInfo) ValidateSize() (valid bool) { if fi.Size < MIN_FILE_SIZE { fi.Error = "File is too small" } else if fi.Size > MAX_FILE_SIZE { fi.Error = "File is too big" } else { return true } return false } func (fi *FileInfo) CreateUrls(r *http.Request, c appengine.Context) { u := &url.URL{ Scheme: r.URL.Scheme, Host: appengine.DefaultVersionHostname(c), Path: "/", } uString := u.String() fi.Url = uString + escape(string(fi.Key)) + "/" + escape(string(fi.Name)) fi.DeleteUrl = fi.Url + "?delete=true" fi.DeleteType = "DELETE" if imageTypes.MatchString(fi.Type) { servingUrl, err := image.ServingURL( c, fi.Key, &image.ServingURLOptions{ Secure: strings.HasSuffix(u.Scheme, "s"), Size: 0, Crop: false, }, ) check(err) fi.ThumbnailUrl = servingUrl.String() + THUMBNAIL_PARAM } } func check(err error) { if err != nil { panic(err) } } func escape(s string) string { return strings.Replace(url.QueryEscape(s), "+", "%20", -1) } func delayedDelete(c appengine.Context, fi *FileInfo) { if key := string(fi.Key); key != "" { task := &taskqueue.Task{ Path: "/" + escape(key) + "/-", Method: "DELETE", Delay: time.Duration(EXPIRATION_TIME) * time.Second, } taskqueue.Add(c, task, "") } } func handleUpload(r *http.Request, p *multipart.Part) (fi *FileInfo) { fi = &FileInfo{ Name: p.FileName(), Type: p.Header.Get("Content-Type"), } if !fi.ValidateType() { return } defer func() { if rec := recover(); rec != nil { log.Println(rec) fi.Error = rec.(error).Error() } }() lr := &io.LimitedReader{R: p, N: MAX_FILE_SIZE + 1} context := appengine.NewContext(r) w, err := blobstore.Create(context, fi.Type) defer func() { w.Close() fi.Size = MAX_FILE_SIZE + 1 - lr.N fi.Key, err = w.Key() check(err) if !fi.ValidateSize() { err := blobstore.Delete(context, fi.Key) check(err) return } delayedDelete(context, fi) fi.CreateUrls(r, context) }() check(err) _, err = io.Copy(w, lr) return } func getFormValue(p *multipart.Part) string { var b bytes.Buffer io.CopyN(&b, p, int64(1<<20)) // Copy max: 1 MiB return b.String() } func handleUploads(r *http.Request) (fileInfos []*FileInfo) { fileInfos = make([]*FileInfo, 0) mr, err := r.MultipartReader() check(err) r.Form, err = url.ParseQuery(r.URL.RawQuery) check(err) part, err := mr.NextPart() for err == nil { if name := part.FormName(); name != "" { if part.FileName() != "" { fileInfos = append(fileInfos, handleUpload(r, part)) } else { r.Form[name] = append(r.Form[name], getFormValue(part)) } } part, err = mr.NextPart() } return } func get(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/" { http.Redirect(w, r, WEBSITE, http.StatusFound) return } parts := strings.Split(r.URL.Path, "/") if len(parts) == 3 { if key := parts[1]; key != "" { blobKey := appengine.BlobKey(key) bi, err := blobstore.Stat(appengine.NewContext(r), blobKey) if err == nil { w.Header().Add("X-Content-Type-Options", "nosniff") if !imageTypes.MatchString(bi.ContentType) { w.Header().Add("Content-Type", "application/octet-stream") w.Header().Add( "Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", parts[2]), ) } w.Header().Add( "Cache-Control", fmt.Sprintf("public,max-age=%d", EXPIRATION_TIME), ) blobstore.Send(w, blobKey) return } } } http.Error(w, "404 Not Found", http.StatusNotFound) } func post(w http.ResponseWriter, r *http.Request) { result := make(map[string][]*FileInfo, 1) result["files"] = handleUploads(r) b, err := json.Marshal(result) check(err) if redirect := r.FormValue("redirect"); redirect != "" { if strings.Contains(redirect, "%s") { redirect = fmt.Sprintf( redirect, escape(string(b)), ) } http.Redirect(w, r, redirect, http.StatusFound) return } w.Header().Set("Cache-Control", "no-cache") jsonType := "application/json" if strings.Index(r.Header.Get("Accept"), jsonType) != -1 { w.Header().Set("Content-Type", jsonType) } fmt.Fprintln(w, string(b)) } func delete(w http.ResponseWriter, r *http.Request) { parts := strings.Split(r.URL.Path, "/") if len(parts) != 3 { return } if key := parts[1]; key != "" { c := appengine.NewContext(r) blobKey := appengine.BlobKey(key) err := blobstore.Delete(c, blobKey) check(err) err = image.DeleteServingURL(c, blobKey) check(err) } } func handle(w http.ResponseWriter, r *http.Request) { params, err := url.ParseQuery(r.URL.RawQuery) check(err) w.Header().Add("Access-Control-Allow-Origin", "*") w.Header().Add( "Access-Control-Allow-Methods", "OPTIONS, HEAD, GET, POST, PUT, DELETE", ) w.Header().Add( "Access-Control-Allow-Headers", "Content-Type, Content-Range, Content-Disposition", ) switch r.Method { case "OPTIONS": case "HEAD": case "GET": get(w, r) case "POST": if len(params["_method"]) > 0 && params["_method"][0] == "DELETE" { delete(w, r) } else { post(w, r) } case "DELETE": delete(w, r) default: http.Error(w, "501 Not Implemented", http.StatusNotImplemented) } } func init() { http.HandleFunc("/", handle) } ================================================ FILE: public/packages/jquery-file-upload-8.9.0/server/gae-go/app.yaml ================================================ application: jquery-file-upload version: 2 runtime: go api_version: go1 handlers: - url: /(favicon\.ico|robots\.txt) static_files: static/\1 upload: static/(.*) expiration: '1d' - url: /.* script: _go_app ================================================ FILE: public/packages/jquery-file-upload-8.9.0/server/gae-go/static/robots.txt ================================================ User-agent: * Disallow: ================================================ FILE: public/packages/jquery-file-upload-8.9.0/server/gae-python/app.yaml ================================================ application: jquery-file-upload version: 1 runtime: python27 api_version: 1 threadsafe: true builtins: - deferred: on handlers: - url: /(favicon\.ico|robots\.txt) static_files: static/\1 upload: static/(.*) expiration: '1d' - url: /.* script: main.app ================================================ FILE: public/packages/jquery-file-upload-8.9.0/server/gae-python/main.py ================================================ # -*- coding: utf-8 -*- # # jQuery File Upload Plugin GAE Python Example 2.1.0 # https://github.com/blueimp/jQuery-File-Upload # # Copyright 2011, Sebastian Tschan # https://blueimp.net # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # from __future__ import with_statement from google.appengine.api import files, images from google.appengine.ext import blobstore, deferred from google.appengine.ext.webapp import blobstore_handlers import json import re import urllib import webapp2 WEBSITE = 'http://blueimp.github.io/jQuery-File-Upload/' MIN_FILE_SIZE = 1 # bytes MAX_FILE_SIZE = 5000000 # bytes IMAGE_TYPES = re.compile('image/(gif|p?jpeg|(x-)?png)') ACCEPT_FILE_TYPES = IMAGE_TYPES THUMBNAIL_MODIFICATOR = '=s80' # max width / height EXPIRATION_TIME = 300 # seconds def cleanup(blob_keys): blobstore.delete(blob_keys) class UploadHandler(webapp2.RequestHandler): def initialize(self, request, response): super(UploadHandler, self).initialize(request, response) self.response.headers['Access-Control-Allow-Origin'] = '*' self.response.headers[ 'Access-Control-Allow-Methods' ] = 'OPTIONS, HEAD, GET, POST, PUT, DELETE' self.response.headers[ 'Access-Control-Allow-Headers' ] = 'Content-Type, Content-Range, Content-Disposition' def validate(self, file): if file['size'] < MIN_FILE_SIZE: file['error'] = 'File is too small' elif file['size'] > MAX_FILE_SIZE: file['error'] = 'File is too big' elif not ACCEPT_FILE_TYPES.match(file['type']): file['error'] = 'Filetype not allowed' else: return True return False def get_file_size(self, file): file.seek(0, 2) # Seek to the end of the file size = file.tell() # Get the position of EOF file.seek(0) # Reset the file position to the beginning return size def write_blob(self, data, info): blob = files.blobstore.create( mime_type=info['type'], _blobinfo_uploaded_filename=info['name'] ) with files.open(blob, 'a') as f: f.write(data) files.finalize(blob) return files.blobstore.get_blob_key(blob) def handle_upload(self): results = [] blob_keys = [] for name, fieldStorage in self.request.POST.items(): if type(fieldStorage) is unicode: continue result = {} result['name'] = re.sub( r'^.*\\', '', fieldStorage.filename ) result['type'] = fieldStorage.type result['size'] = self.get_file_size(fieldStorage.file) if self.validate(result): blob_key = str( self.write_blob(fieldStorage.value, result) ) blob_keys.append(blob_key) result['deleteType'] = 'DELETE' result['deleteUrl'] = self.request.host_url +\ '/?key=' + urllib.quote(blob_key, '') if (IMAGE_TYPES.match(result['type'])): try: result['url'] = images.get_serving_url( blob_key, secure_url=self.request.host_url.startswith( 'https' ) ) result['thumbnailUrl'] = result['url'] +\ THUMBNAIL_MODIFICATOR except: # Could not get an image serving url pass if not 'url' in result: result['url'] = self.request.host_url +\ '/' + blob_key + '/' + urllib.quote( result['name'].encode('utf-8'), '') results.append(result) deferred.defer( cleanup, blob_keys, _countdown=EXPIRATION_TIME ) return results def options(self): pass def head(self): pass def get(self): self.redirect(WEBSITE) def post(self): if (self.request.get('_method') == 'DELETE'): return self.delete() result = {'files': self.handle_upload()} s = json.dumps(result, separators=(',', ':')) redirect = self.request.get('redirect') if redirect: return self.redirect(str( redirect.replace('%s', urllib.quote(s, ''), 1) )) if 'application/json' in self.request.headers.get('Accept'): self.response.headers['Content-Type'] = 'application/json' self.response.write(s) def delete(self): blobstore.delete(self.request.get('key') or '') class DownloadHandler(blobstore_handlers.BlobstoreDownloadHandler): def get(self, key, filename): if not blobstore.get(key): self.error(404) else: # Prevent browsers from MIME-sniffing the content-type: self.response.headers['X-Content-Type-Options'] = 'nosniff' # Cache for the expiration time: self.response.headers['Cache-Control'] = 'public,max-age=%d' % EXPIRATION_TIME # Send the file forcing a download dialog: self.send_blob(key, save_as=filename, content_type='application/octet-stream') app = webapp2.WSGIApplication( [ ('/', UploadHandler), ('/([^/]+)/([^/]+)', DownloadHandler) ], debug=True ) ================================================ FILE: public/packages/jquery-file-upload-8.9.0/server/gae-python/static/robots.txt ================================================ User-agent: * Disallow: ================================================ FILE: public/packages/jquery-file-upload-8.9.0/server/node/.gitignore ================================================ .DS_Store node_modules ================================================ FILE: public/packages/jquery-file-upload-8.9.0/server/node/package.json ================================================ { "name": "blueimp-file-upload-node", "version": "2.1.0", "title": "jQuery File Upload Node.js example", "description": "Node.js implementation example of a file upload handler for jQuery File Upload.", "keywords": [ "file", "upload", "cross-domain", "cross-site", "node" ], "homepage": "https://github.com/blueimp/jQuery-File-Upload", "author": { "name": "Sebastian Tschan", "url": "https://blueimp.net" }, "maintainers": [ { "name": "Sebastian Tschan", "url": "https://blueimp.net" } ], "repository": { "type": "git", "url": "git://github.com/blueimp/jQuery-File-Upload.git" }, "bugs": "https://github.com/blueimp/jQuery-File-Upload/issues", "licenses": [ { "type": "MIT", "url": "http://www.opensource.org/licenses/MIT" } ], "dependencies": { "formidable": ">=1.0.11", "node-static": ">=0.6.5", "imagemagick": ">=0.1.3" }, "main": "server.js" } ================================================ FILE: public/packages/jquery-file-upload-8.9.0/server/node/public/files/.gitignore ================================================ * !.gitignore ================================================ FILE: public/packages/jquery-file-upload-8.9.0/server/node/server.js ================================================ #!/usr/bin/env node /* * jQuery File Upload Plugin Node.js Example 2.1.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2012, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, regexp: true, unparam: true, stupid: true */ /*global require, __dirname, unescape, console */ (function (port) { 'use strict'; var path = require('path'), fs = require('fs'), // Since Node 0.8, .existsSync() moved from path to fs: _existsSync = fs.existsSync || path.existsSync, formidable = require('formidable'), nodeStatic = require('node-static'), imageMagick = require('imagemagick'), options = { tmpDir: __dirname + '/tmp', publicDir: __dirname + '/public', uploadDir: __dirname + '/public/files', uploadUrl: '/files/', maxPostSize: 11000000000, // 11 GB minFileSize: 1, maxFileSize: 10000000000, // 10 GB acceptFileTypes: /.+/i, // Files not matched by this regular expression force a download dialog, // to prevent executing any scripts in the context of the service domain: inlineFileTypes: /\.(gif|jpe?g|png)$/i, imageTypes: /\.(gif|jpe?g|png)$/i, imageVersions: { 'thumbnail': { width: 80, height: 80 } }, accessControl: { allowOrigin: '*', allowMethods: 'OPTIONS, HEAD, GET, POST, PUT, DELETE', allowHeaders: 'Content-Type, Content-Range, Content-Disposition' }, /* Uncomment and edit this section to provide the service via HTTPS: ssl: { key: fs.readFileSync('/Applications/XAMPP/etc/ssl.key/server.key'), cert: fs.readFileSync('/Applications/XAMPP/etc/ssl.crt/server.crt') }, */ nodeStatic: { cache: 3600 // seconds to cache served files } }, utf8encode = function (str) { return unescape(encodeURIComponent(str)); }, fileServer = new nodeStatic.Server(options.publicDir, options.nodeStatic), nameCountRegexp = /(?:(?: \(([\d]+)\))?(\.[^.]+))?$/, nameCountFunc = function (s, index, ext) { return ' (' + ((parseInt(index, 10) || 0) + 1) + ')' + (ext || ''); }, FileInfo = function (file) { this.name = file.name; this.size = file.size; this.type = file.type; this.deleteType = 'DELETE'; }, UploadHandler = function (req, res, callback) { this.req = req; this.res = res; this.callback = callback; }, serve = function (req, res) { res.setHeader( 'Access-Control-Allow-Origin', options.accessControl.allowOrigin ); res.setHeader( 'Access-Control-Allow-Methods', options.accessControl.allowMethods ); res.setHeader( 'Access-Control-Allow-Headers', options.accessControl.allowHeaders ); var handleResult = function (result, redirect) { if (redirect) { res.writeHead(302, { 'Location': redirect.replace( /%s/, encodeURIComponent(JSON.stringify(result)) ) }); res.end(); } else { res.writeHead(200, { 'Content-Type': req.headers.accept .indexOf('application/json') !== -1 ? 'application/json' : 'text/plain' }); res.end(JSON.stringify(result)); } }, setNoCacheHeaders = function () { res.setHeader('Pragma', 'no-cache'); res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate'); res.setHeader('Content-Disposition', 'inline; filename="files.json"'); }, handler = new UploadHandler(req, res, handleResult); switch (req.method) { case 'OPTIONS': res.end(); break; case 'HEAD': case 'GET': if (req.url === '/') { setNoCacheHeaders(); if (req.method === 'GET') { handler.get(); } else { res.end(); } } else { fileServer.serve(req, res); } break; case 'POST': setNoCacheHeaders(); handler.post(); break; case 'DELETE': handler.destroy(); break; default: res.statusCode = 405; res.end(); } }; fileServer.respond = function (pathname, status, _headers, files, stat, req, res, finish) { // Prevent browsers from MIME-sniffing the content-type: _headers['X-Content-Type-Options'] = 'nosniff'; if (!options.inlineFileTypes.test(files[0])) { // Force a download dialog for unsafe file extensions: _headers['Content-Type'] = 'application/octet-stream'; _headers['Content-Disposition'] = 'attachment; filename="' + utf8encode(path.basename(files[0])) + '"'; } nodeStatic.Server.prototype.respond .call(this, pathname, status, _headers, files, stat, req, res, finish); }; FileInfo.prototype.validate = function () { if (options.minFileSize && options.minFileSize > this.size) { this.error = 'File is too small'; } else if (options.maxFileSize && options.maxFileSize < this.size) { this.error = 'File is too big'; } else if (!options.acceptFileTypes.test(this.name)) { this.error = 'Filetype not allowed'; } return !this.error; }; FileInfo.prototype.safeName = function () { // Prevent directory traversal and creating hidden system files: this.name = path.basename(this.name).replace(/^\.+/, ''); // Prevent overwriting existing files: while (_existsSync(options.uploadDir + '/' + this.name)) { this.name = this.name.replace(nameCountRegexp, nameCountFunc); } }; FileInfo.prototype.initUrls = function (req) { if (!this.error) { var that = this, baseUrl = (options.ssl ? 'https:' : 'http:') + '//' + req.headers.host + options.uploadUrl; this.url = this.deleteUrl = baseUrl + encodeURIComponent(this.name); Object.keys(options.imageVersions).forEach(function (version) { if (_existsSync( options.uploadDir + '/' + version + '/' + that.name )) { that[version + 'Url'] = baseUrl + version + '/' + encodeURIComponent(that.name); } }); } }; UploadHandler.prototype.get = function () { var handler = this, files = []; fs.readdir(options.uploadDir, function (err, list) { list.forEach(function (name) { var stats = fs.statSync(options.uploadDir + '/' + name), fileInfo; if (stats.isFile() && name[0] !== '.') { fileInfo = new FileInfo({ name: name, size: stats.size }); fileInfo.initUrls(handler.req); files.push(fileInfo); } }); handler.callback({files: files}); }); }; UploadHandler.prototype.post = function () { var handler = this, form = new formidable.IncomingForm(), tmpFiles = [], files = [], map = {}, counter = 1, redirect, finish = function () { counter -= 1; if (!counter) { files.forEach(function (fileInfo) { fileInfo.initUrls(handler.req); }); handler.callback({files: files}, redirect); } }; form.uploadDir = options.tmpDir; form.on('fileBegin', function (name, file) { tmpFiles.push(file.path); var fileInfo = new FileInfo(file, handler.req, true); fileInfo.safeName(); map[path.basename(file.path)] = fileInfo; files.push(fileInfo); }).on('field', function (name, value) { if (name === 'redirect') { redirect = value; } }).on('file', function (name, file) { var fileInfo = map[path.basename(file.path)]; fileInfo.size = file.size; if (!fileInfo.validate()) { fs.unlink(file.path); return; } fs.renameSync(file.path, options.uploadDir + '/' + fileInfo.name); if (options.imageTypes.test(fileInfo.name)) { Object.keys(options.imageVersions).forEach(function (version) { counter += 1; var opts = options.imageVersions[version]; imageMagick.resize({ width: opts.width, height: opts.height, srcPath: options.uploadDir + '/' + fileInfo.name, dstPath: options.uploadDir + '/' + version + '/' + fileInfo.name }, finish); }); } }).on('aborted', function () { tmpFiles.forEach(function (file) { fs.unlink(file); }); }).on('error', function (e) { console.log(e); }).on('progress', function (bytesReceived, bytesExpected) { if (bytesReceived > options.maxPostSize) { handler.req.connection.destroy(); } }).on('end', finish).parse(handler.req); }; UploadHandler.prototype.destroy = function () { var handler = this, fileName; if (handler.req.url.slice(0, options.uploadUrl.length) === options.uploadUrl) { fileName = path.basename(decodeURIComponent(handler.req.url)); if (fileName[0] !== '.') { fs.unlink(options.uploadDir + '/' + fileName, function (ex) { Object.keys(options.imageVersions).forEach(function (version) { fs.unlink(options.uploadDir + '/' + version + '/' + fileName); }); handler.callback({success: !ex}); }); return; } } handler.callback({success: false}); }; if (options.ssl) { require('https').createServer(options.ssl, serve).listen(port); } else { require('http').createServer(serve).listen(port); } }(8888)); ================================================ FILE: public/packages/jquery-file-upload-8.9.0/server/node/tmp/.gitignore ================================================ ================================================ FILE: public/packages/jquery-file-upload-8.9.0/server/php/UploadHandler.php ================================================ 'The uploaded file exceeds the upload_max_filesize directive in php.ini', 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', 3 => 'The uploaded file was only partially uploaded', 4 => 'No file was uploaded', 6 => 'Missing a temporary folder', 7 => 'Failed to write file to disk', 8 => 'A PHP extension stopped the file upload', 'post_max_size' => 'The uploaded file exceeds the post_max_size directive in php.ini', 'max_file_size' => 'File is too big', 'min_file_size' => 'File is too small', 'accept_file_types' => 'Filetype not allowed', 'max_number_of_files' => 'Maximum number of files exceeded', 'max_width' => 'Image exceeds maximum width', 'min_width' => 'Image requires a minimum width', 'max_height' => 'Image exceeds maximum height', 'min_height' => 'Image requires a minimum height' ); protected $image_objects = array(); function __construct($options = null, $initialize = true, $error_messages = null) { $this->options = array( 'script_url' => $this->get_full_url().'/', 'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/files/', 'upload_url' => $this->get_full_url().'/files/', 'user_dirs' => false, 'mkdir_mode' => 0755, 'param_name' => 'files', // Set the following option to 'POST', if your server does not support // DELETE requests. This is a parameter sent to the client: 'delete_type' => 'DELETE', 'access_control_allow_origin' => '*', 'access_control_allow_credentials' => false, 'access_control_allow_methods' => array( 'OPTIONS', 'HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE' ), 'access_control_allow_headers' => array( 'Content-Type', 'Content-Range', 'Content-Disposition' ), // Enable to provide file downloads via GET requests to the PHP script: // 1. Set to 1 to download files via readfile method through PHP // 2. Set to 2 to send a X-Sendfile header for lighttpd/Apache // 3. Set to 3 to send a X-Accel-Redirect header for nginx // If set to 2 or 3, adjust the upload_url option to the base path of // the redirect parameter, e.g. '/files/'. 'download_via_php' => false, // Read files in chunks to avoid memory limits when download_via_php // is enabled, set to 0 to disable chunked reading of files: 'readfile_chunk_size' => 10 * 1024 * 1024, // 10 MiB // Defines which files can be displayed inline when downloaded: 'inline_file_types' => '/\.(gif|jpe?g|png)$/i', // Defines which files (based on their names) are accepted for upload: 'accept_file_types' => '/.+$/i', // The php.ini settings upload_max_filesize and post_max_size // take precedence over the following max_file_size setting: 'max_file_size' => null, 'min_file_size' => 1, // The maximum number of files for the upload directory: 'max_number_of_files' => null, // Defines which files are handled as image files: 'image_file_types' => '/\.(gif|jpe?g|png)$/i', // Image resolution restrictions: 'max_width' => null, 'max_height' => null, 'min_width' => 1, 'min_height' => 1, // Set the following option to false to enable resumable uploads: 'discard_aborted_uploads' => true, // Set to 0 to use the GD image extension to scale and orient images // instead of imagick, which is used by default if installed: 'image_library' => 1, // Set to false to disable rotating images based on EXIF meta data: 'orient_image' => true, 'image_versions' => array( // Uncomment the following version to restrict the size of // uploaded images: /* '' => array( 'max_width' => 1920, 'max_height' => 1200, 'jpeg_quality' => 95 ), */ // Uncomment the following to create medium sized images: /* 'medium' => array( 'max_width' => 800, 'max_height' => 600, 'jpeg_quality' => 80 ), */ 'thumbnail' => array( // Uncomment the following to use a defined directory for the thumbnails // instead of a subdirectory based on the version identifier. // Make sure that this directory doesn't allow execution of files if you // don't pose any restrictions on the type of uploaded files, e.g. by // copying the .htaccess file from the files directory for Apache: //'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/thumb/', //'upload_url' => $this->get_full_url().'/thumb/', // Uncomment the following to force the max // dimensions and e.g. create square thumbnails: //'crop' => true, 'max_width' => 80, 'max_height' => 80 ) ) ); if ($options) { $this->options = $options + $this->options; } if ($error_messages) { $this->error_messages = $error_messages + $this->error_messages; } if ($initialize) { $this->initialize(); } } protected function initialize() { switch ($this->get_server_var('REQUEST_METHOD')) { case 'OPTIONS': case 'HEAD': $this->head(); break; case 'GET': $this->get(); break; case 'PATCH': case 'PUT': case 'POST': $this->post(); break; case 'DELETE': $this->delete(); break; default: $this->header('HTTP/1.1 405 Method Not Allowed'); } } protected function get_full_url() { $https = !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'on') === 0; return ($https ? 'https://' : 'http://'). (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : ''). (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME']. ($https && $_SERVER['SERVER_PORT'] === 443 || $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))). substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/')); } protected function get_user_id() { @session_start(); return session_id(); } protected function get_user_path() { if ($this->options['user_dirs']) { return $this->get_user_id().'/'; } return ''; } protected function get_upload_path($file_name = null, $version = null) { $file_name = $file_name ? $file_name : ''; if (empty($version)) { $version_path = ''; } else { $version_dir = @$this->options['image_versions'][$version]['upload_dir']; if ($version_dir) { return $version_dir.$this->get_user_path().$file_name; } $version_path = $version.'/'; } return $this->options['upload_dir'].$this->get_user_path() .$version_path.$file_name; } protected function get_query_separator($url) { return strpos($url, '?') === false ? '?' : '&'; } protected function get_download_url($file_name, $version = null, $direct = false) { if (!$direct && $this->options['download_via_php']) { $url = $this->options['script_url'] .$this->get_query_separator($this->options['script_url']) .'file='.rawurlencode($file_name); if ($version) { $url .= '&version='.rawurlencode($version); } return $url.'&download=1'; } if (empty($version)) { $version_path = ''; } else { $version_url = @$this->options['image_versions'][$version]['upload_url']; if ($version_url) { return $version_url.$this->get_user_path().rawurlencode($file_name); } $version_path = rawurlencode($version).'/'; } return $this->options['upload_url'].$this->get_user_path() .$version_path.rawurlencode($file_name); } protected function set_additional_file_properties($file) { $file->deleteUrl = $this->options['script_url'] .$this->get_query_separator($this->options['script_url']) .$this->get_singular_param_name() .'='.rawurlencode($file->name); $file->deleteType = $this->options['delete_type']; if ($file->deleteType !== 'DELETE') { $file->deleteUrl .= '&_method=DELETE'; } if ($this->options['access_control_allow_credentials']) { $file->deleteWithCredentials = true; } } // Fix for overflowing signed 32 bit integers, // works for sizes up to 2^32-1 bytes (4 GiB - 1): protected function fix_integer_overflow($size) { if ($size < 0) { $size += 2.0 * (PHP_INT_MAX + 1); } return $size; } protected function get_file_size($file_path, $clear_stat_cache = false) { if ($clear_stat_cache) { clearstatcache(true, $file_path); } return $this->fix_integer_overflow(filesize($file_path)); } protected function is_valid_file_object($file_name) { $file_path = $this->get_upload_path($file_name); if (is_file($file_path) && $file_name[0] !== '.') { return true; } return false; } protected function get_file_object($file_name) { if ($this->is_valid_file_object($file_name)) { $file = new stdClass(); $file->name = $file_name; $file->size = $this->get_file_size( $this->get_upload_path($file_name) ); $file->url = $this->get_download_url($file->name); foreach($this->options['image_versions'] as $version => $options) { if (!empty($version)) { if (is_file($this->get_upload_path($file_name, $version))) { $file->{$version.'Url'} = $this->get_download_url( $file->name, $version ); } } } $this->set_additional_file_properties($file); return $file; } return null; } protected function get_file_objects($iteration_method = 'get_file_object') { $upload_dir = $this->get_upload_path(); if (!is_dir($upload_dir)) { return array(); } return array_values(array_filter(array_map( array($this, $iteration_method), scandir($upload_dir) ))); } protected function count_file_objects() { return count($this->get_file_objects('is_valid_file_object')); } protected function get_error_message($error) { return array_key_exists($error, $this->error_messages) ? $this->error_messages[$error] : $error; } function get_config_bytes($val) { $val = trim($val); $last = strtolower($val[strlen($val)-1]); switch($last) { case 'g': $val *= 1024; case 'm': $val *= 1024; case 'k': $val *= 1024; } return $this->fix_integer_overflow($val); } protected function validate($uploaded_file, $file, $error, $index) { if ($error) { $file->error = $this->get_error_message($error); return false; } $content_length = $this->fix_integer_overflow(intval( $this->get_server_var('CONTENT_LENGTH') )); $post_max_size = $this->get_config_bytes(ini_get('post_max_size')); if ($post_max_size && ($content_length > $post_max_size)) { $file->error = $this->get_error_message('post_max_size'); return false; } if (!preg_match($this->options['accept_file_types'], $file->name)) { $file->error = $this->get_error_message('accept_file_types'); return false; } if ($uploaded_file && is_uploaded_file($uploaded_file)) { $file_size = $this->get_file_size($uploaded_file); } else { $file_size = $content_length; } if ($this->options['max_file_size'] && ( $file_size > $this->options['max_file_size'] || $file->size > $this->options['max_file_size']) ) { $file->error = $this->get_error_message('max_file_size'); return false; } if ($this->options['min_file_size'] && $file_size < $this->options['min_file_size']) { $file->error = $this->get_error_message('min_file_size'); return false; } if (is_int($this->options['max_number_of_files']) && ( $this->count_file_objects() >= $this->options['max_number_of_files']) ) { $file->error = $this->get_error_message('max_number_of_files'); return false; } if ($this->is_valid_image_file($uploaded_file)) { list($img_width, $img_height) = $this->get_image_size($uploaded_file); } if (!empty($img_width)) { if ($this->options['max_width'] && $img_width > $this->options['max_width']) { $file->error = $this->get_error_message('max_width'); return false; } if ($this->options['max_height'] && $img_height > $this->options['max_height']) { $file->error = $this->get_error_message('max_height'); return false; } if ($this->options['min_width'] && $img_width < $this->options['min_width']) { $file->error = $this->get_error_message('min_width'); return false; } if ($this->options['min_height'] && $img_height < $this->options['min_height']) { $file->error = $this->get_error_message('min_height'); return false; } } return true; } protected function upcount_name_callback($matches) { $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1; $ext = isset($matches[2]) ? $matches[2] : ''; return ' ('.$index.')'.$ext; } protected function upcount_name($name) { return preg_replace_callback( '/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/', array($this, 'upcount_name_callback'), $name, 1 ); } protected function get_unique_filename($name, $type = null, $index = null, $content_range = null) { while(is_dir($this->get_upload_path($name))) { $name = $this->upcount_name($name); } // Keep an existing filename if this is part of a chunked upload: $uploaded_bytes = $this->fix_integer_overflow(intval($content_range[1])); while(is_file($this->get_upload_path($name))) { if ($uploaded_bytes === $this->get_file_size( $this->get_upload_path($name))) { break; } $name = $this->upcount_name($name); } return $name; } protected function trim_file_name($name, $type = null, $index = null, $content_range = null) { // Remove path information and dots around the filename, to prevent uploading // into different directories or replacing hidden system files. // Also remove control characters and spaces (\x00..\x20) around the filename: $name = trim(basename(stripslashes($name)), ".\x00..\x20"); // Use a timestamp for empty filenames: if (!$name) { $name = str_replace('.', '-', microtime(true)); } // Add missing file extension for known image types: if (strpos($name, '.') === false && preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) { $name .= '.'.$matches[1]; } return $name; } protected function get_file_name($name, $type = null, $index = null, $content_range = null) { return $this->get_unique_filename( $this->trim_file_name($name, $type, $index, $content_range), $type, $index, $content_range ); } protected function handle_form_data($file, $index) { // Handle form data, e.g. $_REQUEST['description'][$index] } protected function get_scaled_image_file_paths($file_name, $version) { $file_path = $this->get_upload_path($file_name); if (!empty($version)) { $version_dir = $this->get_upload_path(null, $version); if (!is_dir($version_dir)) { mkdir($version_dir, $this->options['mkdir_mode'], true); } $new_file_path = $version_dir.'/'.$file_name; } else { $new_file_path = $file_path; } return array($file_path, $new_file_path); } protected function gd_get_image_object($file_path, $func, $no_cache = false) { if (empty($this->image_objects[$file_path]) || $no_cache) { $this->gd_destroy_image_object($file_path); $this->image_objects[$file_path] = $func($file_path); } return $this->image_objects[$file_path]; } protected function gd_set_image_object($file_path, $image) { $this->image_objects[$file_path] = $image; } protected function gd_destroy_image_object($file_path) { $image = @$this->image_objects[$file_path]; return $image && imagedestroy($image); } protected function gd_create_scaled_image($file_name, $version, $options) { if (!function_exists('imagecreatetruecolor')) { error_log('Function not found: imagecreatetruecolor'); return false; } list($file_path, $new_file_path) = $this->get_scaled_image_file_paths($file_name, $version); $type = strtolower(substr(strrchr($file_name, '.'), 1)); switch ($type) { case 'jpg': case 'jpeg': $src_func = 'imagecreatefromjpeg'; $write_func = 'imagejpeg'; $image_quality = isset($options['jpeg_quality']) ? $options['jpeg_quality'] : 75; break; case 'gif': $src_func = 'imagecreatefromgif'; $write_func = 'imagegif'; $image_quality = null; break; case 'png': $src_func = 'imagecreatefrompng'; $write_func = 'imagepng'; $image_quality = isset($options['png_quality']) ? $options['png_quality'] : 9; break; default: return false; } $src_img = $this->gd_get_image_object( $file_path, $src_func, !empty($options['no_cache']) ); $img_width = imagesx($src_img); $img_height = imagesy($src_img); $max_width = $options['max_width']; $max_height = $options['max_height']; $scale = min( $max_width / $img_width, $max_height / $img_height ); if ($scale >= 1) { if ($file_path !== $new_file_path) { return copy($file_path, $new_file_path); } return true; } if (empty($options['crop'])) { $new_width = $img_width * $scale; $new_height = $img_height * $scale; $dst_x = 0; $dst_y = 0; $new_img = imagecreatetruecolor($new_width, $new_height); } else { if (($img_width / $img_height) >= ($max_width / $max_height)) { $new_width = $img_width / ($img_height / $max_height); $new_height = $max_height; } else { $new_width = $max_width; $new_height = $img_height / ($img_width / $max_width); } $dst_x = 0 - ($new_width - $max_width) / 2; $dst_y = 0 - ($new_height - $max_height) / 2; $new_img = imagecreatetruecolor($max_width, $max_height); } // Handle transparency in GIF and PNG images: switch ($type) { case 'gif': case 'png': imagecolortransparent($new_img, imagecolorallocate($new_img, 0, 0, 0)); case 'png': imagealphablending($new_img, false); imagesavealpha($new_img, true); break; } $success = imagecopyresampled( $new_img, $src_img, $dst_x, $dst_y, 0, 0, $new_width, $new_height, $img_width, $img_height ) && $write_func($new_img, $new_file_path, $image_quality); $this->gd_set_image_object($file_path, $new_img); // Free up memory (imagedestroy does not delete files): imagedestroy($src_img); return $success; } protected function gd_imageflip($image, $mode) { if (function_exists('imageflip')) { return imageflip($image, $mode); } $new_width = $src_width = imagesx($image); $new_height = $src_height = imagesy($image); $new_img = imagecreatetruecolor($new_width, $new_height); $src_x = 0; $src_y = 0; switch ($mode) { case '1': // flip on the horizontal axis $src_y = $new_height - 1; $src_height = -$new_height; break; case '2': // flip on the vertical axis $src_x = $new_width - 1; $src_width = -$new_width; break; case '3': // flip on both axes $src_y = $new_height - 1; $src_height = -$new_height; $src_x = $new_width - 1; $src_width = -$new_width; break; default: return $image; } imagecopyresampled( $new_img, $image, 0, 0, $src_x, $src_y, $new_width, $new_height, $src_width, $src_height ); return $new_img; } protected function gd_orient_image($file_path) { if (!function_exists('exif_read_data')) { return false; } $exif = @exif_read_data($file_path); if ($exif === false) { return false; } $orientation = intval(@$exif['Orientation']); if ($orientation < 2 || $orientation > 8) { return false; } $src_img = $this->gd_get_image_object($file_path, 'imagecreatefromjpeg'); switch ($orientation) { case 2: $new_img = $this->gd_imageflip( $src_img, defined('IMG_FLIP_VERTICAL') ? IMG_FLIP_VERTICAL : 2 ); break; case 3: $new_img = imagerotate($src_img, 180, 0); break; case 4: $new_img = $this->gd_imageflip( $src_img, defined('IMG_FLIP_HORIZONTAL') ? IMG_FLIP_HORIZONTAL : 1 ); break; case 5: $tmp_img = $this->gd_imageflip( $src_img, defined('IMG_FLIP_HORIZONTAL') ? IMG_FLIP_HORIZONTAL : 1 ); $new_img = imagerotate($tmp_img, 270, 0); break; case 6: $new_img = imagerotate($src_img, 270, 0); break; case 7: $tmp_img = $this->gd_imageflip( $src_img, defined('IMG_FLIP_VERTICAL') ? IMG_FLIP_VERTICAL : 2 ); $new_img = imagerotate($tmp_img, 270, 0); break; case 8: $new_img = imagerotate($src_img, 90, 0); break; default: return false; } $this->gd_set_image_object($file_path, $new_img); // Free up memory (imagedestroy does not delete files): @imagedestroy($tmp_img); imagedestroy($src_img); return imagejpeg($new_img, $file_path); } protected function imagick_get_image_object($file_path, $no_cache = false) { if (empty($this->image_objects[$file_path]) || $no_cache) { $this->imagick_destroy_image_object($file_path); $this->image_objects[$file_path] = new Imagick($file_path); } return $this->image_objects[$file_path]; } protected function imagick_destroy_image_object($file_path) { $image = @$this->image_objects[$file_path]; return $image && $image->destroy(); } protected function imagick_create_scaled_image($file_name, $version, $options) { list($file_path, $new_file_path) = $this->get_scaled_image_file_paths($file_name, $version); $new_width = $max_width = $options['max_width']; $new_height = $max_height = $options['max_height']; $image = $this->imagick_get_image_object( $file_path, !empty($options['no_cache']) ); // Handle animated GIFs: $images = $image->coalesceImages(); foreach ($images as $frame) { $image = $frame; break; } $img_width = $image->getImageWidth(); $img_height = $image->getImageHeight(); if (min($max_width / $img_width, $max_height / $img_height) >= 1) { // Image is smaller than the constraints if ($file_path !== $new_file_path) { return copy($file_path, $new_file_path); } return true; } $crop = !empty($options['crop']); if ($crop) { $x = 0; $y = 0; if (($img_width / $img_height) >= ($max_width / $max_height)) { $new_width = 0; // Enables proportional scaling based on max_height $x = ($img_width / ($img_height / $max_height) - $max_width) / 2; } else { $new_height = 0; // Enables proportional scaling based on max_width $y = ($img_height / ($img_width / $max_width) - $max_height) / 2; } } $success = $image->resizeImage( $new_width, $new_height, isset($options['filter']) ? $options['filter'] : imagick::FILTER_LANCZOS, isset($options['blur']) ? $options['blur'] : 1, $new_width && $new_height // fit image into constraints if not to be cropped ); if ($success && $crop) { $success = $image->cropImage( $max_width, $max_height, $x, $y ); if ($success) { $success = $image->setImagePage($max_width, $max_height, 0, 0); } } $type = strtolower(substr(strrchr($file_name, '.'), 1)); switch ($type) { case 'jpg': case 'jpeg': if (!empty($options['jpeg_quality'])) { $image->setImageCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality($options['jpeg_quality']); } break; } if (!empty($options['strip'])) { $image->stripImage(); } return $success && $image->writeImage($new_file_path); } protected function imagick_orient_image($file_path) { $image = $this->imagick_get_image_object($file_path); $orientation = $image->getImageOrientation(); $background = new ImagickPixel('none'); switch ($orientation) { case imagick::ORIENTATION_TOPRIGHT: // 2 $image->flopImage(); // horizontal flop around y-axis break; case imagick::ORIENTATION_BOTTOMRIGHT: // 3 $image->rotateImage($background, 180); break; case imagick::ORIENTATION_BOTTOMLEFT: // 4 $image->flipImage(); // vertical flip around x-axis break; case imagick::ORIENTATION_LEFTTOP: // 5 $image->flopImage(); // horizontal flop around y-axis $image->rotateImage($background, 270); break; case imagick::ORIENTATION_RIGHTTOP: // 6 $image->rotateImage($background, 90); break; case imagick::ORIENTATION_RIGHTBOTTOM: // 7 $image->flipImage(); // vertical flip around x-axis $image->rotateImage($background, 270); break; case imagick::ORIENTATION_LEFTBOTTOM: // 8 $image->rotateImage($background, 270); break; default: return false; } $image->setImageOrientation(imagick::ORIENTATION_TOPLEFT); // 1 return $image->writeImage($file_path); } protected function get_image_size($file_path) { if ($this->options['image_library'] && extension_loaded('imagick')) { $image = $this->imagick_get_image_object($file_path); return array($image->getImageWidth(), $image->getImageHeight()); } if (!function_exists('getimagesize')) { error_log('Function not found: getimagesize'); return false; } return getimagesize($file_path); } protected function create_scaled_image($file_name, $version, $options) { if ($this->options['image_library'] && extension_loaded('imagick')) { return $this->imagick_create_scaled_image($file_name, $version, $options); } return $this->gd_create_scaled_image($file_name, $version, $options); } protected function orient_image($file_path) { if ($this->options['image_library'] && extension_loaded('imagick')) { return $this->imagick_orient_image($file_path); } return $this->gd_orient_image($file_path); } protected function destroy_image_object($file_path) { if ($this->options['image_library'] && extension_loaded('imagick')) { return $this->imagick_destroy_image_object($file_path); } } protected function is_valid_image_file($file_path) { if (!preg_match($this->options['image_file_types'], $file_path)) { return false; } if (function_exists('exif_imagetype')) { return @exif_imagetype($file_path); } if (!function_exists('getimagesize')) { error_log('Function not found: getimagesize'); return false; } $image_info = @getimagesize($file_path); return !empty($image_info[0]); } protected function handle_image_file($file_path, $file) { if ($this->options['orient_image']) { $this->orient_image($file_path); } $failed_versions = array(); foreach($this->options['image_versions'] as $version => $options) { if ($this->create_scaled_image($file->name, $version, $options)) { if (!empty($version)) { $file->{$version.'Url'} = $this->get_download_url( $file->name, $version ); } else { $file->size = $this->get_file_size($file_path, true); } } else { $failed_versions[] = $version; } } switch (count($failed_versions)) { case 0: break; case 1: $file->error = 'Failed to create scaled version: ' .$failed_versions[0]; break; default: $file->error = 'Failed to create scaled versions: ' .implode($failed_versions,', '); } // Free memory: $this->destroy_image_object($file_path); } protected function handle_file_upload($uploaded_file, $name, $size, $type, $error, $index = null, $content_range = null) { $file = new stdClass(); $file->name = $this->get_file_name($name, $type, $index, $content_range); $file->size = $this->fix_integer_overflow(intval($size)); $file->type = $type; if ($this->validate($uploaded_file, $file, $error, $index)) { $this->handle_form_data($file, $index); $upload_dir = $this->get_upload_path(); if (!is_dir($upload_dir)) { mkdir($upload_dir, $this->options['mkdir_mode'], true); } $file_path = $this->get_upload_path($file->name); $append_file = $content_range && is_file($file_path) && $file->size > $this->get_file_size($file_path); if ($uploaded_file && is_uploaded_file($uploaded_file)) { // multipart/formdata uploads (POST method uploads) if ($append_file) { file_put_contents( $file_path, fopen($uploaded_file, 'r'), FILE_APPEND ); } else { move_uploaded_file($uploaded_file, $file_path); } } else { // Non-multipart uploads (PUT method support) file_put_contents( $file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0 ); } $file_size = $this->get_file_size($file_path, $append_file); if ($file_size === $file->size) { $file->url = $this->get_download_url($file->name); if ($this->is_valid_image_file($file_path)) { $this->handle_image_file($file_path, $file); } } else { $file->size = $file_size; if (!$content_range && $this->options['discard_aborted_uploads']) { unlink($file_path); $file->error = 'abort'; } } $this->set_additional_file_properties($file); } return $file; } protected function readfile($file_path) { $file_size = $this->get_file_size($file_path); $chunk_size = $this->options['readfile_chunk_size']; if ($chunk_size && $file_size > $chunk_size) { $handle = fopen($file_path, 'rb'); while (!feof($handle)) { echo fread($handle, $chunk_size); ob_flush(); flush(); } fclose($handle); return $file_size; } return readfile($file_path); } protected function body($str) { echo $str; } protected function header($str) { header($str); } protected function get_server_var($id) { return isset($_SERVER[$id]) ? $_SERVER[$id] : ''; } protected function generate_response($content, $print_response = true) { if ($print_response) { $json = json_encode($content); $redirect = isset($_REQUEST['redirect']) ? stripslashes($_REQUEST['redirect']) : null; if ($redirect) { $this->header('Location: '.sprintf($redirect, rawurlencode($json))); return; } $this->head(); if ($this->get_server_var('HTTP_CONTENT_RANGE')) { $files = isset($content[$this->options['param_name']]) ? $content[$this->options['param_name']] : null; if ($files && is_array($files) && is_object($files[0]) && $files[0]->size) { $this->header('Range: 0-'.( $this->fix_integer_overflow(intval($files[0]->size)) - 1 )); } } $this->body($json); } return $content; } protected function get_version_param() { return isset($_GET['version']) ? basename(stripslashes($_GET['version'])) : null; } protected function get_singular_param_name() { return substr($this->options['param_name'], 0, -1); } protected function get_file_name_param() { $name = $this->get_singular_param_name(); return isset($_GET[$name]) ? basename(stripslashes($_GET[$name])) : null; } protected function get_file_names_params() { $params = isset($_GET[$this->options['param_name']]) ? $_GET[$this->options['param_name']] : array(); foreach ($params as $key => $value) { $params[$key] = basename(stripslashes($value)); } return $params; } protected function get_file_type($file_path) { switch (strtolower(pathinfo($file_path, PATHINFO_EXTENSION))) { case 'jpeg': case 'jpg': return 'image/jpeg'; case 'png': return 'image/png'; case 'gif': return 'image/gif'; default: return ''; } } protected function download() { switch ($this->options['download_via_php']) { case 1: $redirect_header = null; break; case 2: $redirect_header = 'X-Sendfile'; break; case 3: $redirect_header = 'X-Accel-Redirect'; break; default: return $this->header('HTTP/1.1 403 Forbidden'); } $file_name = $this->get_file_name_param(); if (!$this->is_valid_file_object($file_name)) { return $this->header('HTTP/1.1 404 Not Found'); } if ($redirect_header) { return $this->header( $redirect_header.': '.$this->get_download_url( $file_name, $this->get_version_param(), true ) ); } $file_path = $this->get_upload_path($file_name, $this->get_version_param()); // Prevent browsers from MIME-sniffing the content-type: $this->header('X-Content-Type-Options: nosniff'); if (!preg_match($this->options['inline_file_types'], $file_name)) { $this->header('Content-Type: application/octet-stream'); $this->header('Content-Disposition: attachment; filename="'.$file_name.'"'); } else { $this->header('Content-Type: '.$this->get_file_type($file_path)); $this->header('Content-Disposition: inline; filename="'.$file_name.'"'); } $this->header('Content-Length: '.$this->get_file_size($file_path)); $this->header('Last-Modified: '.gmdate('D, d M Y H:i:s T', filemtime($file_path))); $this->readfile($file_path); } protected function send_content_type_header() { $this->header('Vary: Accept'); if (strpos($this->get_server_var('HTTP_ACCEPT'), 'application/json') !== false) { $this->header('Content-type: application/json'); } else { $this->header('Content-type: text/plain'); } } protected function send_access_control_headers() { $this->header('Access-Control-Allow-Origin: '.$this->options['access_control_allow_origin']); $this->header('Access-Control-Allow-Credentials: ' .($this->options['access_control_allow_credentials'] ? 'true' : 'false')); $this->header('Access-Control-Allow-Methods: ' .implode(', ', $this->options['access_control_allow_methods'])); $this->header('Access-Control-Allow-Headers: ' .implode(', ', $this->options['access_control_allow_headers'])); } public function head() { $this->header('Pragma: no-cache'); $this->header('Cache-Control: no-store, no-cache, must-revalidate'); $this->header('Content-Disposition: inline; filename="files.json"'); // Prevent Internet Explorer from MIME-sniffing the content-type: $this->header('X-Content-Type-Options: nosniff'); if ($this->options['access_control_allow_origin']) { $this->send_access_control_headers(); } $this->send_content_type_header(); } public function get($print_response = true) { if ($print_response && isset($_GET['download'])) { return $this->download(); } $file_name = $this->get_file_name_param(); if ($file_name) { $response = array( $this->get_singular_param_name() => $this->get_file_object($file_name) ); } else { $response = array( $this->options['param_name'] => $this->get_file_objects() ); } return $this->generate_response($response, $print_response); } public function post($print_response = true) { if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') { return $this->delete($print_response); } $upload = isset($_FILES[$this->options['param_name']]) ? $_FILES[$this->options['param_name']] : null; // Parse the Content-Disposition header, if available: $file_name = $this->get_server_var('HTTP_CONTENT_DISPOSITION') ? rawurldecode(preg_replace( '/(^[^"]+")|("$)/', '', $this->get_server_var('HTTP_CONTENT_DISPOSITION') )) : null; // Parse the Content-Range header, which has the following form: // Content-Range: bytes 0-524287/2000000 $content_range = $this->get_server_var('HTTP_CONTENT_RANGE') ? preg_split('/[^0-9]+/', $this->get_server_var('HTTP_CONTENT_RANGE')) : null; $size = $content_range ? $content_range[3] : null; $files = array(); if ($upload && is_array($upload['tmp_name'])) { // param_name is an array identifier like "files[]", // $_FILES is a multi-dimensional array: foreach ($upload['tmp_name'] as $index => $value) { $files[] = $this->handle_file_upload( $upload['tmp_name'][$index], $file_name ? $file_name : $upload['name'][$index], $size ? $size : $upload['size'][$index], $upload['type'][$index], $upload['error'][$index], $index, $content_range ); } } else { // param_name is a single object identifier like "file", // $_FILES is a one-dimensional array: $files[] = $this->handle_file_upload( isset($upload['tmp_name']) ? $upload['tmp_name'] : null, $file_name ? $file_name : (isset($upload['name']) ? $upload['name'] : null), $size ? $size : (isset($upload['size']) ? $upload['size'] : $this->get_server_var('CONTENT_LENGTH')), isset($upload['type']) ? $upload['type'] : $this->get_server_var('CONTENT_TYPE'), isset($upload['error']) ? $upload['error'] : null, null, $content_range ); } return $this->generate_response( array($this->options['param_name'] => $files), $print_response ); } public function delete($print_response = true) { $file_names = $this->get_file_names_params(); if (empty($file_names)) { $file_names = array($this->get_file_name_param()); } $response = array(); foreach($file_names as $file_name) { $file_path = $this->get_upload_path($file_name); $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path); if ($success) { foreach($this->options['image_versions'] as $version => $options) { if (!empty($version)) { $file = $this->get_upload_path($file_name, $version); if (is_file($file)) { unlink($file); } } } } $response[$file_name] = $success; } return $this->generate_response($response, $print_response); } } ================================================ FILE: public/packages/jquery-file-upload-8.9.0/server/php/files/.gitignore ================================================ * !.gitignore !.htaccess ================================================ FILE: public/packages/jquery-file-upload-8.9.0/server/php/files/.htaccess ================================================ # The following directives force the content-type application/octet-stream # and force browsers to display a download dialog for non-image files. # This prevents the execution of script files in the context of the website: ForceType application/octet-stream Header set Content-Disposition attachment ForceType none Header unset Content-Disposition # The following directive prevents browsers from MIME-sniffing the content-type. # This is an important complement to the ForceType directive above: Header set X-Content-Type-Options nosniff # Uncomment the following lines to prevent unauthorized download of files: #AuthName "Authorization required" #AuthType Basic #require valid-user ================================================ FILE: public/packages/jquery-file-upload-8.9.0/server/php/index.php ================================================ jQuery File Upload Plugin Test

            jQuery File Upload Plugin Test

              Add files...
               
              ================================================ FILE: public/packages/jquery-file-upload-8.9.0/test/test.js ================================================ /* * jQuery File Upload Plugin Test 8.8.5 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, unparam: true */ /*global $, QUnit, window, document, expect, module, test, asyncTest, start, ok, strictEqual, notStrictEqual */ $(function () { 'use strict'; QUnit.done = function () { // Delete all uploaded files: var url = $('#fileupload').prop('action'); $.getJSON(url, function (result) { $.each(result.files, function (index, file) { $.ajax({ url: url + '?file=' + encodeURIComponent(file.name), type: 'DELETE' }); }); }); }; var lifecycle = { setup: function () { // Set the .fileupload method to the basic widget method: $.widget('blueimp.fileupload', window.testBasicWidget, {}); }, teardown: function () { // Remove all remaining event listeners: $(document).unbind(); } }, lifecycleUI = { setup: function () { // Set the .fileupload method to the UI widget method: $.widget('blueimp.fileupload', window.testUIWidget, {}); }, teardown: function () { // Remove all remaining event listeners: $(document).unbind(); } }; module('Initialization', lifecycle); test('Widget initialization', function () { var fu = $('#fileupload').fileupload(); ok(fu.data('blueimp-fileupload') || fu.data('fileupload')); }); test('Data attribute options', function () { $('#fileupload').attr('data-url', 'http://example.org'); $('#fileupload').fileupload(); strictEqual( $('#fileupload').fileupload('option', 'url'), 'http://example.org' ); }); test('File input initialization', function () { var fu = $('#fileupload').fileupload(); ok( fu.fileupload('option', 'fileInput').length, 'File input field inside of the widget' ); ok( fu.fileupload('option', 'fileInput').length, 'Widget element as file input field' ); }); test('Drop zone initialization', function () { ok($('#fileupload').fileupload() .fileupload('option', 'dropZone').length); }); test('Paste zone initialization', function () { ok($('#fileupload').fileupload() .fileupload('option', 'pasteZone').length); }); test('Event listeners initialization', function () { expect( $.support.xhrFormDataFileUpload ? 4 : 1 ); var eo = { originalEvent: { dataTransfer: {files: [{}], types: ['Files']}, clipboardData: {items: [{}]} } }, fu = $('#fileupload').fileupload({ dragover: function () { ok(true, 'Triggers dragover callback'); return false; }, drop: function () { ok(true, 'Triggers drop callback'); return false; }, paste: function () { ok(true, 'Triggers paste callback'); return false; }, change: function () { ok(true, 'Triggers change callback'); return false; } }), fileInput = fu.fileupload('option', 'fileInput'), dropZone = fu.fileupload('option', 'dropZone'), pasteZone = fu.fileupload('option', 'pasteZone'); fileInput.trigger($.Event('change', eo)); dropZone.trigger($.Event('dragover', eo)); dropZone.trigger($.Event('drop', eo)); pasteZone.trigger($.Event('paste', eo)); }); module('API', lifecycle); test('destroy', function () { expect(4); var eo = { originalEvent: { dataTransfer: {files: [{}], types: ['Files']}, clipboardData: {items: [{}]} } }, options = { dragover: function () { ok(true, 'Triggers dragover callback'); return false; }, drop: function () { ok(true, 'Triggers drop callback'); return false; }, paste: function () { ok(true, 'Triggers paste callback'); return false; }, change: function () { ok(true, 'Triggers change callback'); return false; } }, fu = $('#fileupload').fileupload(options), fileInput = fu.fileupload('option', 'fileInput'), dropZone = fu.fileupload('option', 'dropZone'), pasteZone = fu.fileupload('option', 'pasteZone'); dropZone.bind('dragover', options.dragover); dropZone.bind('drop', options.drop); pasteZone.bind('paste', options.paste); fileInput.bind('change', options.change); fu.fileupload('destroy'); fileInput.trigger($.Event('change', eo)); dropZone.trigger($.Event('dragover', eo)); dropZone.trigger($.Event('drop', eo)); pasteZone.trigger($.Event('paste', eo)); }); test('disable/enable', function () { expect( $.support.xhrFormDataFileUpload ? 4 : 1 ); var eo = { originalEvent: { dataTransfer: {files: [{}], types: ['Files']}, clipboardData: {items: [{}]} } }, fu = $('#fileupload').fileupload({ dragover: function () { ok(true, 'Triggers dragover callback'); return false; }, drop: function () { ok(true, 'Triggers drop callback'); return false; }, paste: function () { ok(true, 'Triggers paste callback'); return false; }, change: function () { ok(true, 'Triggers change callback'); return false; } }), fileInput = fu.fileupload('option', 'fileInput'), dropZone = fu.fileupload('option', 'dropZone'), pasteZone = fu.fileupload('option', 'pasteZone'); fu.fileupload('disable'); fileInput.trigger($.Event('change', eo)); dropZone.trigger($.Event('dragover', eo)); dropZone.trigger($.Event('drop', eo)); pasteZone.trigger($.Event('paste', eo)); fu.fileupload('enable'); fileInput.trigger($.Event('change', eo)); dropZone.trigger($.Event('dragover', eo)); dropZone.trigger($.Event('drop', eo)); pasteZone.trigger($.Event('paste', eo)); }); test('option', function () { expect( $.support.xhrFormDataFileUpload ? 10 : 7 ); var eo = { originalEvent: { dataTransfer: {files: [{}], types: ['Files']}, clipboardData: {items: [{}]} } }, fu = $('#fileupload').fileupload({ dragover: function () { ok(true, 'Triggers dragover callback'); return false; }, drop: function () { ok(true, 'Triggers drop callback'); return false; }, paste: function () { ok(true, 'Triggers paste callback'); return false; }, change: function () { ok(true, 'Triggers change callback'); return false; } }), fileInput = fu.fileupload('option', 'fileInput'), dropZone = fu.fileupload('option', 'dropZone'), pasteZone = fu.fileupload('option', 'pasteZone'); fu.fileupload('option', 'fileInput', null); fu.fileupload('option', 'dropZone', null); fu.fileupload('option', 'pasteZone', null); fileInput.trigger($.Event('change', eo)); dropZone.trigger($.Event('dragover', eo)); dropZone.trigger($.Event('drop', eo)); pasteZone.trigger($.Event('paste', eo)); fu.fileupload('option', 'dropZone', 'body'); strictEqual( fu.fileupload('option', 'dropZone')[0], document.body, 'Allow a query string as parameter for the dropZone option' ); fu.fileupload('option', 'dropZone', document); strictEqual( fu.fileupload('option', 'dropZone')[0], document, 'Allow a document element as parameter for the dropZone option' ); fu.fileupload('option', 'pasteZone', 'body'); strictEqual( fu.fileupload('option', 'pasteZone')[0], document.body, 'Allow a query string as parameter for the pasteZone option' ); fu.fileupload('option', 'pasteZone', document); strictEqual( fu.fileupload('option', 'pasteZone')[0], document, 'Allow a document element as parameter for the pasteZone option' ); fu.fileupload('option', 'fileInput', ':file'); strictEqual( fu.fileupload('option', 'fileInput')[0], $(':file')[0], 'Allow a query string as parameter for the fileInput option' ); fu.fileupload('option', 'fileInput', $(':file')[0]); strictEqual( fu.fileupload('option', 'fileInput')[0], $(':file')[0], 'Allow a document element as parameter for the fileInput option' ); fu.fileupload('option', 'fileInput', fileInput); fu.fileupload('option', 'dropZone', dropZone); fu.fileupload('option', 'pasteZone', pasteZone); fileInput.trigger($.Event('change', eo)); dropZone.trigger($.Event('dragover', eo)); dropZone.trigger($.Event('drop', eo)); pasteZone.trigger($.Event('paste', eo)); }); asyncTest('add', function () { expect(2); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ add: function (e, data) { strictEqual( data.files[0].name, param.files[0].name, 'Triggers add callback' ); } }).fileupload('add', param).fileupload( 'option', 'add', function (e, data) { data.submit().complete(function () { ok(true, 'data.submit() Returns a jqXHR object'); start(); }); } ).fileupload('add', param); }); asyncTest('send', function () { expect(3); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ send: function (e, data) { strictEqual( data.files[0].name, 'test', 'Triggers send callback' ); } }).fileupload('send', param).fail(function () { ok(true, 'Allows to abort the request'); }).complete(function () { ok(true, 'Returns a jqXHR object'); start(); }).abort(); }); module('Callbacks', lifecycle); asyncTest('add', function () { expect(1); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ add: function (e, data) { ok(true, 'Triggers add callback'); start(); } }).fileupload('add', param); }); asyncTest('submit', function () { expect(1); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ submit: function (e, data) { ok(true, 'Triggers submit callback'); start(); return false; } }).fileupload('add', param); }); asyncTest('send', function () { expect(1); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ send: function (e, data) { ok(true, 'Triggers send callback'); start(); return false; } }).fileupload('send', param); }); asyncTest('done', function () { expect(1); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ done: function (e, data) { ok(true, 'Triggers done callback'); start(); } }).fileupload('send', param); }); asyncTest('fail', function () { expect(1); var param = {files: [{name: 'test'}]}, fu = $('#fileupload').fileupload({ url: '404', fail: function (e, data) { ok(true, 'Triggers fail callback'); start(); } }); (fu.data('blueimp-fileupload') || fu.data('fileupload')) ._isXHRUpload = function () { return true; }; fu.fileupload('send', param); }); asyncTest('always', function () { expect(2); var param = {files: [{name: 'test'}]}, counter = 0, fu = $('#fileupload').fileupload({ always: function (e, data) { ok(true, 'Triggers always callback'); if (counter === 1) { start(); } else { counter += 1; } } }); (fu.data('blueimp-fileupload') || fu.data('fileupload')) ._isXHRUpload = function () { return true; }; fu.fileupload('add', param).fileupload( 'option', 'url', '404' ).fileupload('add', param); }); asyncTest('progress', function () { expect(1); var param = {files: [{name: 'test'}]}, counter = 0; $('#fileupload').fileupload({ forceIframeTransport: true, progress: function (e, data) { ok(true, 'Triggers progress callback'); if (counter === 0) { start(); } else { counter += 1; } } }).fileupload('send', param); }); asyncTest('progressall', function () { expect(1); var param = {files: [{name: 'test'}]}, counter = 0; $('#fileupload').fileupload({ forceIframeTransport: true, progressall: function (e, data) { ok(true, 'Triggers progressall callback'); if (counter === 0) { start(); } else { counter += 1; } } }).fileupload('send', param); }); asyncTest('start', function () { expect(1); var param = {files: [{name: '1'}, {name: '2'}]}, active = 0; $('#fileupload').fileupload({ send: function (e, data) { active += 1; }, start: function (e, data) { ok(!active, 'Triggers start callback before uploads'); start(); } }).fileupload('send', param); }); asyncTest('stop', function () { expect(1); var param = {files: [{name: '1'}, {name: '2'}]}, active = 0; $('#fileupload').fileupload({ send: function (e, data) { active += 1; }, always: function (e, data) { active -= 1; }, stop: function (e, data) { ok(!active, 'Triggers stop callback after uploads'); start(); } }).fileupload('send', param); }); test('change', function () { var fu = $('#fileupload').fileupload(), fuo = fu.data('blueimp-fileupload') || fu.data('fileupload'), fileInput = fu.fileupload('option', 'fileInput'); expect(2); fu.fileupload({ change: function (e, data) { ok(true, 'Triggers change callback'); strictEqual( data.files.length, 0, 'Returns empty files list' ); }, add: $.noop }); fuo._onChange({ data: {fileupload: fuo}, target: fileInput[0] }); }); test('paste', function () { var fu = $('#fileupload').fileupload(), fuo = fu.data('blueimp-fileupload') || fu.data('fileupload'); expect(1); fu.fileupload({ paste: function (e, data) { ok(true, 'Triggers paste callback'); }, add: $.noop }); fuo._onPaste({ data: {fileupload: fuo}, originalEvent: { dataTransfer: {files: [{}]}, clipboardData: {items: [{}]} }, preventDefault: $.noop }); }); test('drop', function () { var fu = $('#fileupload').fileupload(), fuo = fu.data('blueimp-fileupload') || fu.data('fileupload'); expect(1); fu.fileupload({ drop: function (e, data) { ok(true, 'Triggers drop callback'); }, add: $.noop }); fuo._onDrop({ data: {fileupload: fuo}, originalEvent: { dataTransfer: {files: [{}]}, clipboardData: {items: [{}]} }, preventDefault: $.noop }); }); test('dragover', function () { var fu = $('#fileupload').fileupload(), fuo = fu.data('blueimp-fileupload') || fu.data('fileupload'); expect(1); fu.fileupload({ dragover: function (e, data) { ok(true, 'Triggers dragover callback'); }, add: $.noop }); fuo._onDragOver({ data: {fileupload: fuo}, originalEvent: {dataTransfer: {types: ['Files']}}, preventDefault: $.noop }); }); module('Options', lifecycle); test('paramName', function () { expect(1); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ paramName: null, send: function (e, data) { strictEqual( data.paramName[0], data.fileInput.prop('name'), 'Takes paramName from file input field if not set' ); return false; } }).fileupload('send', param); }); test('url', function () { expect(1); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ url: null, send: function (e, data) { strictEqual( data.url, $(data.fileInput.prop('form')).prop('action'), 'Takes url from form action if not set' ); return false; } }).fileupload('send', param); }); test('type', function () { expect(2); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ type: null, send: function (e, data) { strictEqual( data.type, 'POST', 'Request type is "POST" if not set to "PUT"' ); return false; } }).fileupload('send', param); $('#fileupload').fileupload({ type: 'PUT', send: function (e, data) { strictEqual( data.type, 'PUT', 'Request type is "PUT" if set to "PUT"' ); return false; } }).fileupload('send', param); }); test('replaceFileInput', function () { var fu = $('#fileupload').fileupload(), fuo = fu.data('blueimp-fileupload') || fu.data('fileupload'), fileInput = fu.fileupload('option', 'fileInput'), fileInputElement = fileInput[0]; expect(2); fu.fileupload({ replaceFileInput: false, change: function (e, data) { strictEqual( fu.fileupload('option', 'fileInput')[0], fileInputElement, 'Keeps file input with replaceFileInput: false' ); }, add: $.noop }); fuo._onChange({ data: {fileupload: fuo}, target: fileInput[0] }); fu.fileupload({ replaceFileInput: true, change: function (e, data) { notStrictEqual( fu.fileupload('option', 'fileInput')[0], fileInputElement, 'Replaces file input with replaceFileInput: true' ); }, add: $.noop }); fuo._onChange({ data: {fileupload: fuo}, target: fileInput[0] }); }); asyncTest('forceIframeTransport', function () { expect(1); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ forceIframeTransport: true, done: function (e, data) { strictEqual( data.dataType.substr(0, 6), 'iframe', 'Iframe Transport is used' ); start(); } }).fileupload('send', param); }); test('singleFileUploads', function () { expect(3); var fu = $('#fileupload').fileupload(), param = {files: [{name: '1'}, {name: '2'}]}, index = 1; (fu.data('blueimp-fileupload') || fu.data('fileupload')) ._isXHRUpload = function () { return true; }; $('#fileupload').fileupload({ singleFileUploads: true, add: function (e, data) { ok(true, 'Triggers callback number ' + index.toString()); index += 1; } }).fileupload('add', param).fileupload( 'option', 'singleFileUploads', false ).fileupload('add', param); }); test('limitMultiFileUploads', function () { expect(3); var fu = $('#fileupload').fileupload(), param = {files: [ {name: '1'}, {name: '2'}, {name: '3'}, {name: '4'}, {name: '5'} ]}, index = 1; (fu.data('blueimp-fileupload') || fu.data('fileupload')) ._isXHRUpload = function () { return true; }; $('#fileupload').fileupload({ singleFileUploads: false, limitMultiFileUploads: 2, add: function (e, data) { ok(true, 'Triggers callback number ' + index.toString()); index += 1; } }).fileupload('add', param); }); asyncTest('sequentialUploads', function () { expect(6); var param = {files: [ {name: '1'}, {name: '2'}, {name: '3'}, {name: '4'}, {name: '5'}, {name: '6'} ]}, addIndex = 0, sendIndex = 0, loadIndex = 0, fu = $('#fileupload').fileupload({ sequentialUploads: true, add: function (e, data) { addIndex += 1; if (addIndex === 4) { data.submit().abort(); } else { data.submit(); } }, send: function (e, data) { sendIndex += 1; }, done: function (e, data) { loadIndex += 1; strictEqual(sendIndex, loadIndex, 'upload in order'); }, fail: function (e, data) { strictEqual(data.errorThrown, 'abort', 'upload aborted'); }, stop: function (e) { start(); } }); (fu.data('blueimp-fileupload') || fu.data('fileupload')) ._isXHRUpload = function () { return true; }; fu.fileupload('add', param); }); asyncTest('limitConcurrentUploads', function () { expect(12); var param = {files: [ {name: '1'}, {name: '2'}, {name: '3'}, {name: '4'}, {name: '5'}, {name: '6'}, {name: '7'}, {name: '8'}, {name: '9'}, {name: '10'}, {name: '11'}, {name: '12'} ]}, addIndex = 0, sendIndex = 0, loadIndex = 0, fu = $('#fileupload').fileupload({ limitConcurrentUploads: 3, add: function (e, data) { addIndex += 1; if (addIndex === 4) { data.submit().abort(); } else { data.submit(); } }, send: function (e, data) { sendIndex += 1; }, done: function (e, data) { loadIndex += 1; ok(sendIndex - loadIndex < 3); }, fail: function (e, data) { strictEqual(data.errorThrown, 'abort', 'upload aborted'); }, stop: function (e) { start(); } }); (fu.data('blueimp-fileupload') || fu.data('fileupload')) ._isXHRUpload = function () { return true; }; fu.fileupload('add', param); }); if ($.support.xhrFileUpload) { asyncTest('multipart', function () { expect(2); var param = {files: [{ name: 'test.png', size: 123, type: 'image/png' }]}, fu = $('#fileupload').fileupload({ multipart: false, always: function (e, data) { strictEqual( data.contentType, param.files[0].type, 'non-multipart upload sets file type as contentType' ); strictEqual( data.headers['Content-Disposition'], 'attachment; filename="' + param.files[0].name + '"', 'non-multipart upload sets Content-Disposition header' ); start(); } }); fu.fileupload('send', param); }); } module('UI Initialization', lifecycleUI); test('Widget initialization', function () { var fu = $('#fileupload').fileupload(); ok(fu.data('blueimp-fileupload') || fu.data('fileupload')); ok( $('#fileupload').fileupload('option', 'uploadTemplate').length, 'Initialized upload template' ); ok( $('#fileupload').fileupload('option', 'downloadTemplate').length, 'Initialized download template' ); }); test('Buttonbar event listeners', function () { var buttonbar = $('#fileupload .fileupload-buttonbar'), files = [{name: 'test'}]; expect(4); $('#fileupload').fileupload({ send: function (e, data) { ok(true, 'Started file upload via global start button'); }, fail: function (e, data) { ok(true, 'Canceled file upload via global cancel button'); data.context.remove(); }, destroy: function (e, data) { ok(true, 'Delete action called via global delete button'); } }); $('#fileupload').fileupload('add', {files: files}); buttonbar.find('.cancel').click(); $('#fileupload').fileupload('add', {files: files}); buttonbar.find('.start').click(); buttonbar.find('.cancel').click(); files[0].deleteUrl = 'http://example.org/banana.jpg'; ($('#fileupload').data('blueimp-fileupload') || $('#fileupload').data('fileupload')) ._renderDownload(files) .appendTo($('#fileupload .files')).show() .find('.toggle').click(); buttonbar.find('.delete').click(); }); module('UI API', lifecycleUI); test('destroy', function () { var buttonbar = $('#fileupload .fileupload-buttonbar'), files = [{name: 'test'}]; expect(1); $('#fileupload').fileupload({ send: function (e, data) { ok(true, 'This test should not run'); return false; } }) .fileupload('add', {files: files}) .fileupload('destroy'); buttonbar.find('.start').click(function () { ok(true, 'Clicked global start button'); return false; }).click(); }); test('disable/enable', function () { var buttonbar = $('#fileupload .fileupload-buttonbar'); $('#fileupload').fileupload(); $('#fileupload').fileupload('disable'); strictEqual( buttonbar.find('input[type=file], button').not(':disabled').length, 0, 'Disables the buttonbar buttons' ); $('#fileupload').fileupload('enable'); strictEqual( buttonbar.find('input[type=file], button').not(':disabled').length, 4, 'Enables the buttonbar buttons' ); }); module('UI Callbacks', lifecycleUI); test('destroy', function () { expect(3); $('#fileupload').fileupload({ destroy: function (e, data) { ok(true, 'Triggers destroy callback'); strictEqual( data.url, 'test', 'Passes over deletion url parameter' ); strictEqual( data.type, 'DELETE', 'Passes over deletion request type parameter' ); } }); ($('#fileupload').data('blueimp-fileupload') || $('#fileupload').data('fileupload')) ._renderDownload([{ name: 'test', deleteUrl: 'test', deleteType: 'DELETE' }]) .appendTo($('#fileupload .files')) .show() .find('.toggle').click(); $('#fileupload .fileupload-buttonbar .delete').click(); }); asyncTest('added', function () { expect(1); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ added: function (e, data) { start(); strictEqual( data.files[0].name, param.files[0].name, 'Triggers added callback' ); }, send: function () { return false; } }).fileupload('add', param); }); asyncTest('started', function () { expect(1); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ started: function (e) { start(); ok('Triggers started callback'); return false; }, sent: function (e, data) { return false; } }).fileupload('send', param); }); asyncTest('sent', function () { expect(1); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ sent: function (e, data) { start(); strictEqual( data.files[0].name, param.files[0].name, 'Triggers sent callback' ); return false; } }).fileupload('send', param); }); asyncTest('completed', function () { expect(1); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ completed: function (e, data) { start(); ok('Triggers completed callback'); return false; } }).fileupload('send', param); }); asyncTest('failed', function () { expect(1); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ failed: function (e, data) { start(); ok('Triggers failed callback'); return false; } }).fileupload('send', param).abort(); }); asyncTest('stopped', function () { expect(1); var param = {files: [{name: 'test'}]}; $('#fileupload').fileupload({ stopped: function (e, data) { start(); ok('Triggers stopped callback'); return false; } }).fileupload('send', param); }); asyncTest('destroyed', function () { expect(1); $('#fileupload').fileupload({ dataType: 'html', destroyed: function (e, data) { start(); ok(true, 'Triggers destroyed callback'); } }); ($('#fileupload').data('blueimp-fileupload') || $('#fileupload').data('fileupload')) ._renderDownload([{ name: 'test', deleteUrl: '.', deleteType: 'GET' }]) .appendTo($('#fileupload .files')) .show() .find('.toggle').click(); $('#fileupload .fileupload-buttonbar .delete').click(); }); module('UI Options', lifecycleUI); test('autoUpload', function () { expect(1); $('#fileupload') .fileupload({ autoUpload: true, send: function (e, data) { ok(true, 'Started file upload automatically'); return false; } }) .fileupload('add', {files: [{name: 'test'}]}) .fileupload('option', 'autoUpload', false) .fileupload('add', {files: [{name: 'test'}]}); }); test('maxNumberOfFiles', function () { expect(3); var addIndex = 0, sendIndex = 0; $('#fileupload') .fileupload({ autoUpload: true, maxNumberOfFiles: 3, singleFileUploads: false, send: function (e, data) { strictEqual( sendIndex += 1, addIndex ); }, progress: $.noop, progressall: $.noop, done: $.noop, stop: $.noop }) .fileupload('add', {files: [{name: (addIndex += 1)}]}) .fileupload('add', {files: [{name: (addIndex += 1)}]}) .fileupload('add', {files: [{name: (addIndex += 1)}]}) .fileupload('add', {files: [{name: 'test'}]}); }); test('maxFileSize', function () { expect(2); var addIndex = 0, sendIndex = 0; $('#fileupload') .fileupload({ autoUpload: true, maxFileSize: 1000, send: function (e, data) { strictEqual( sendIndex += 1, addIndex ); return false; } }) .fileupload('add', {files: [{ name: (addIndex += 1) }]}) .fileupload('add', {files: [{ name: (addIndex += 1), size: 999 }]}) .fileupload('add', {files: [{ name: 'test', size: 1001 }]}) .fileupload({ send: function (e, data) { ok( !$.blueimp.fileupload.prototype.options .send.call(this, e, data) ); return false; } }); }); test('minFileSize', function () { expect(2); var addIndex = 0, sendIndex = 0; $('#fileupload') .fileupload({ autoUpload: true, minFileSize: 1000, send: function (e, data) { strictEqual( sendIndex += 1, addIndex ); return false; } }) .fileupload('add', {files: [{ name: (addIndex += 1) }]}) .fileupload('add', {files: [{ name: (addIndex += 1), size: 1001 }]}) .fileupload('add', {files: [{ name: 'test', size: 999 }]}) .fileupload({ send: function (e, data) { ok( !$.blueimp.fileupload.prototype.options .send.call(this, e, data) ); return false; } }); }); test('acceptFileTypes', function () { expect(2); var addIndex = 0, sendIndex = 0; $('#fileupload') .fileupload({ autoUpload: true, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, disableImageMetaDataLoad: true, send: function (e, data) { strictEqual( sendIndex += 1, addIndex ); return false; } }) .fileupload('add', {files: [{ name: (addIndex += 1) + '.jpg' }]}) .fileupload('add', {files: [{ name: (addIndex += 1), type: 'image/jpeg' }]}) .fileupload('add', {files: [{ name: 'test.txt', type: 'text/plain' }]}) .fileupload({ send: function (e, data) { ok( !$.blueimp.fileupload.prototype.options .send.call(this, e, data) ); return false; } }); }); test('acceptFileTypes as HTML5 data attribute', function () { expect(2); var regExp = /(\.|\/)(gif|jpe?g|png)$/i; $('#fileupload') .attr('data-accept-file-types', regExp.toString()) .fileupload(); strictEqual( $.type($('#fileupload').fileupload('option', 'acceptFileTypes')), $.type(regExp) ); strictEqual( $('#fileupload').fileupload('option', 'acceptFileTypes').toString(), regExp.toString() ); }); }); ================================================ FILE: public/robots.txt ================================================ User-agent: * Disallow: ================================================ FILE: public/sitemap.xml ================================================ http://laravelsnippets.com/ always http://laravelsnippets.com/snippets always http://laravelsnippets.com/auth/login?next=snippets%2Fcreate always http://laravelsnippets.com/auth/login always http://laravelsnippets.com/snippets/go-back always http://laravelsnippets.com/profile/john-borisov always http://laravelsnippets.com/snippets/handle-date-formats-on-model always http://laravelsnippets.com/profile/pedro-maia always http://laravelsnippets.com/snippets/quickly-commit-changes-to-git always http://laravelsnippets.com/profile/mike-erickson always http://laravelsnippets.com/snippets/managing-timestamps always http://laravelsnippets.com/snippets/gradually-migrating-passwords-from-md5-to-laravels-hash always http://laravelsnippets.com/profile/antonio-carlos-ribeiro always http://laravelsnippets.com/snippets/get-all-columns-names-from-a-eloquent-model always http://laravelsnippets.com/snippets/crud-controller always http://laravelsnippets.com/profile/zenry-the-bear always http://laravelsnippets.com/snippets/bootstrap-3-form-macros always http://laravelsnippets.com/profile/john-kevin-basco always http://laravelsnippets.com/tags/authentication always http://laravelsnippets.com/tags/eloquent always http://laravelsnippets.com/tags/version-3.x always http://laravelsnippets.com/tags/version-4.x always http://laravelsnippets.com/tags/database always http://laravelsnippets.com/tags/macros always http://laravelsnippets.com/tags/blade always http://laravelsnippets.com/tags/requests always http://laravelsnippets.com/tags/forms always http://laravelsnippets.com/tags/filters always http://laravelsnippets.com/tags/caching always http://laravelsnippets.com/tags/mail always http://laravelsnippets.com/snippets/passing-route-parameters-to-any-view always http://laravelsnippets.com/profile/blessing-osakue always http://laravelsnippets.com/snippets/using-mail-in-laravel-and-the-python-smtp-debugging-server always http://laravelsnippets.com/snippets/hitting-the-database-while-testing-a-package-developed-in-workbench always http://laravelsnippets.com/snippets?page=2 always http://laravelsnippets.com/auth/register always http://laravelsnippets.com/profile/john-borisov/snippets always http://laravelsnippets.com/profile/pedro-maia/snippets always http://laravelsnippets.com/profile/mike-erickson/snippets always http://laravelsnippets.com/profile/antonio-carlos-ribeiro/snippets always http://laravelsnippets.com/profile/zenry-the-bear/snippets always http://laravelsnippets.com/profile/john-kevin-basco/snippets always http://laravelsnippets.com/snippets/sentry-route-filters always http://laravelsnippets.com/snippets/get-the-full-name-of-a-user-instance-using-eloquent-accessors always http://laravelsnippets.com/snippets/display-php-loaded-image-with-browser-cache-support always http://laravelsnippets.com/profile/philo-hermans always http://laravelsnippets.com/snippets/blade-forms always http://laravelsnippets.com/tags/version-4.x?page=2 always http://laravelsnippets.com/snippets/changing-angularjs-templating-brackets-in-order-to-be-mixed-with-blade-templating always http://laravelsnippets.com/profile/israel-ortuno always http://laravelsnippets.com/snippets/blade-template-skeleton always http://laravelsnippets.com/snippets/passing-the-original-clients-ip-from-haproxy-to-laravel always http://laravelsnippets.com/snippets/force-ssl-request-on-production always http://laravelsnippets.com/profile/zaher-g always http://laravelsnippets.com/profile/blessing-osakue/snippets always http://laravelsnippets.com/snippets?page=1 always http://laravelsnippets.com/profile/philo-hermans/snippets always http://laravelsnippets.com/tags/version-4.x?page=1 always http://laravelsnippets.com/profile/israel-ortuno/snippets always http://laravelsnippets.com/profile/zaher-g/snippets always ================================================ FILE: readme.md ================================================ ## LaravelSnippets.com website Live site - http://laravelsnippets.com/ Twitter - https://twitter.com/laravelsnippets Facebook Page - https://www.facebook.com/LaravelSnippets Don't forget to star this repository :) And feel free to fork it. ### Core Developers - John Kevin M. Basco - https://twitter.com/johnkevinmbasco - Christopher Pitt - https://twitter.com/followchrisp - Ionut Tanasa - https://twitter.com/ionutz2k - David Knight - https://twitter.com/davidnknight ### How to contribute? #### Bug fixes - Just fork the repository, apply your bug fix and send a pull request on the **development** branch. #### Features - File an issue on this repo with a title that looks like this: [Proposal] Admin Dashboard. - Once the proposal is approved you can go ahead and implement your proposal and send a pull request. You can also contribute features by visiting the issues page on the repository, you'll see issues tagged with "request", if you want to implement it, just leave a comment that you will implement it and just send a pull request. ### Contributors #### A huge thanks to these developers who contributed to the development of the site: - Martin Dilling-Hansen [@dillinghansen](https://twitter.com/dillinghansen) - Sercan Çakır [/mayoz](https://github.com/mayoz) - Nico Romero Peñaredondo - Davide Bellini [@billmn](https://twitter.com/billmn) ### Requirements 1. PHP 5.4 2. Redis ### Local Installation See [wiki page](https://github.com/basco-johnkevin/laravelsnippets/wiki/Local-Installation) ### Running the tests 1. Create a test database and configure ```config/testing/database.php``` 2. Migrate and Seed database for testing ```php artisan migrate --seed --env=testing``` 3. Run ```php vendor/bin/phpunit``` in the console ================================================ FILE: server.php ================================================ "${apt_get} update" } # Apache exec { "install apache": command => "${apt_get} install -y apache2", require => Exec["update apt"] } exec { "enable rewrite module": command => "${a2enmod} rewrite", require => Exec["install apache"] } file { "/etc/apache2/sites-available/000-default.conf": ensure => file, content => " DocumentRoot /var/www/public ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SetEnv APPLICATION_ENVIRONMENT local AllowOverride All " } exec { "restart apache": command => "/etc/init.d/apache2 restart", require => [ File["/etc/apache2/sites-available/000-default.conf"], Exec["install php"] ] } # MySQL package { "mysql-server": ensure => present } service { "mysql": ensure => running, require => Package["mysql-server"] } exec { "set root password": command => "${mysqladmin} -uroot password vagrant", require => Service["mysql"] } exec { "create user": command => "${echo} \"CREATE USER 'dev'@'localhost' IDENTIFIED BY 'dev';\" | ${mysql} -uroot -pvagrant", unless => "${mysql} -udev -pdev", require => Exec["set root password"] } exec { "create database": command => "${echo} \"CREATE DATABASE dev; GRANT ALL ON dev.* TO 'dev'@'localhost';\" | ${mysql} -uroot -pvagrant", unless => "${mysql} -udev -pdev dev", require => Exec["create user"] } # PHP exec { "install python software properties": command => "${apt_get} install -y python-software-properties", require => Exec["update apt"] } exec { "add php repository": command => "${add_apt_repository} -y ppa:ondrej/php5", require => Exec["install python software properties"] } exec { "update apt for php": command => "${apt_get} update -y", require => Exec["add php repository"] } exec { "install php": command => "${apt_get} install -y libapache2-mod-php5 php5-cli php5-common php5-mysql php5-gd php5-fpm php5-cgi php-pear php5-memcache php5-memcached php-apc php-soap php-xml-serializer php-xml-parser php5-geoip php5-mcrypt php5-curl php5-json php5-sqlite php5-redis", require => Exec["update apt for php"] } # Redis exec { "install redis": command => "${apt_get} install -y redis-server", require => Exec["update apt"] } # Laravel exec { "migrate laravel": command => "${php} /var/www/artisan migrate --seed --env=local", require => [ Exec["install php"], Exec["create database"], Exec["restart apache"] ] } ================================================ FILE: vagrantfile ================================================ # -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.box = "precise32" config.vm.box_url = "http://files.vagrantup.com/precise32.box" config.vm.network :forwarded_port, guest: 80, host: 8080 config.vm.synced_folder "./", "/var/www", :owner => "www-data", :group => "www-data", :fmode => "777" config.vm.provider :virtualbox do |vb| vb.customize ["modifyvm", :id, "--memory", "1024"] end config.vm.provision :puppet do |puppet| puppet.manifests_path = "." puppet.manifest_file = "vagrant.pp" end end