commit 5fcd5dc646e7b669ca28125c37d6b6c00caf5553 Author: smshine Date: Sat Feb 7 09:46:32 2026 +0800 first commit diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..6ce13f5 --- /dev/null +++ b/README.txt @@ -0,0 +1,83 @@ +# PROGRAMMING ACTIVITY + +## Database Dictionary + +### programming + +This is the main table for the programming activity. + +* id: ID of programming activity +* course: ID of the course which contains programming +* name: name of the programming task +* description: the description of the task +* descformat: the format of the description +* grade: the max grade of the programming task +* timeopen: The time(stamp) after which students can see the description of + programming task +* timeclose: The time(stamp) before which students should submit programs. +* timelimit: In how many seconds should the program finish. +* memlimit: The maximum memory (KB) the program can use. +* allowlate: If true, students are allowed to submit programs. +* attempts: If not zero, the maximum times can a student post his/her program. +* generator: A python program which can generate testcase. (NOT USED) +* validator: A python program which check if the result of the program + submitted by students correct. + +### programming_submits + +In this table, the program written by students are saved. + +* id: ID of the submit. +* programmingid: ID of the programming task the submit belong to. +* userid: The owner of the submit. +* timemodified: The time(stamp) when the program is submitted. +* language: The langugae the program is written in. +* code: The program code. +* status: Processing status of the judging program. + 0. new, not processed. + 1. compiling, the program is in the compile queue of one of the judge program + 2. compile ok, the program is compiled with our error. + 3. running, the program is in the test queue of one of the judge program + 10. finish, the program is tested, maybe wrong or right. + 11. compile fail, the program is failed in compile. +* compilemessage: The compile message generate by the compiler. + +### programming_tests + +The testcase of each of the programming task. + +* id: ID of the submit +* programmingid: ID of the programming task the teskcase for +* input: The input of the testcase +* output: The output of the testcase +* timelimit: The maximum time in seconds the program can use. This value always + overwrite the timelimit in programming table. If this value is zero, the + program won't be interrupted until the maximum setting in the judge program + exceeded. +* memlimit: The maximum memory in KB the program can use. This value always + overwrite the memlimit in programming table. If this value is zero, the + program won't be interrupted until the maximum setting in the judge program + execced. (NOT USED) +* pub: Is this testcase public(should be show to students) + +### programming_test_results + +This table stores test result of each of the submit in every testcase. + +* id: ID of the test result +* submitid: the submit this test result belong to +* testid: ID of the correspond testcase of the test result +* passed: Is the program passed the test +* output: The output of the program +* timeused: How many seconds did the program used in the test. + +### programming_testers + +This table is used by judge program. Several judge program can be runned in +parallel mode, and the ID of the judge program and ID of the processing submit +is stored in this table. When the first judge program runs, it create this +table and insert -1 and 1 to the table. When the second judge program runs, it +will insert -1 and 2 to the table. + +* submitid: ID of the submit +* testerid: ID of the tester program diff --git a/backup/moodle1/lib.php b/backup/moodle1/lib.php new file mode 100644 index 0000000..52a6ece --- /dev/null +++ b/backup/moodle1/lib.php @@ -0,0 +1,150 @@ +. + +/** + * Provides support for the conversion of moodle1 backup to the moodle2 format + * Based off of a template @ http://docs.moodle.org/dev/Backup_1.9_conversion_for_developers + * + * @package mod + * @subpackage assignment + * @copyright 2011 Aparup Banerjee + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +/** + * Assignment conversion handler + */ +class moodle1_mod_programming_handler extends moodle1_mod_handler { + + + public function get_paths() { + return array( + new convert_path( + 'programming', '/MOODLE_BACKUP/COURSE/MODULES/MOD/PROGRAMMING', + array( + 'renamefields' => array( + 'description' => 'intro', + 'descformat' => 'introformat', + ) + ) + ), + new convert_path( + 'programming_langlimits', '/MOODLE_BACKUP/COURSE/MODULES/MOD/PROGRAMMING/LANGLIMITS'), + new convert_path( + 'programming_langlimit', '/MOODLE_BACKUP/COURSE/MODULES/MOD/PROGRAMMING/LANGLIMITS/LANGLIMIT'), + new convert_path( + 'programming_presetcodes', '/MOODLE_BACKUP/COURSE/MODULES/MOD/PROGRAMMING/PRESETCODES'), + new convert_path( + 'programming_presetcode', '/MOODLE_BACKUP/COURSE/MODULES/MOD/PROGRAMMING/PRESETCODES/PRESETCODE'), + new convert_path( + 'programming_datafiles', '/MOODLE_BACKUP/COURSE/MODULES/MOD/PROGRAMMING/DATAFILES'), + new convert_path( + 'programming_datafile', '/MOODLE_BACKUP/COURSE/MODULES/MOD/PROGRAMMING/DATAFILES/DATAFILE'), + new convert_path( + 'programming_testcases', '/MOODLE_BACKUP/COURSE/MODULES/MOD/PROGRAMMING/TESTCASES'), + new convert_path( + 'programming_testcase', '/MOODLE_BACKUP/COURSE/MODULES/MOD/PROGRAMMING/TESTCASES/TESTCASE'), + new convert_path( + 'programming_submits', '/MOODLE_BACKUP/COURSE/MODULES/MOD/PROGRAMMING/SUBMITS'), + new convert_path( + 'programming_submit', '/MOODLE_BACKUP/COURSE/MODULES/MOD/PROGRAMMING/SUBMITS/SUBMIT'), + // new convert_path('','') + ); + } + public function process_programming($data) { + + // get the course module id and context id + $instanceid = $data['id']; + $cminfo = $this->get_cminfo($instanceid); + $this->moduleid = $cminfo['id']; + $contextid = $this->converter->get_contextid(CONTEXT_MODULE, $this->moduleid); + + // get a fresh new file manager for this instance + $this->fileman = $this->converter->get_file_manager($contextid, 'mod_programming'); + + // convert course files embedded into the intro + $this->fileman->filearea = 'intro'; + $this->fileman->itemid = 0; + $data['intro'] = moodle1_converter::migrate_referenced_files($data['intro'], $this->fileman); + + // start writing choice.xml + $this->open_xml_writer("activities/programming_{$this->moduleid}/programming.xml"); + $this->xmlwriter->begin_tag('activity', array('id' => $instanceid, 'moduleid' => $this->moduleid, + 'modulename' => 'programming', 'contextid' => $contextid)); + $this->xmlwriter->begin_tag('programming', array('id' => $instanceid)); + + foreach ($data as $field => $value) { + if ($field <> 'id') { + $this->xmlwriter->full_tag($field, $value); + } + } + return $data; + } + public function on_programming_langlimits_start() { + $this->xmlwriter->begin_tag('langlimits'); + } + public function on_programming_langlimits_end() { + $this->xmlwriter->end_tag('langlimits'); + } + public function on_programming_presetcodes_start() { + $this->xmlwriter->begin_tag('presetcodes'); + } + public function on_programming_presetcodes_end() { + $this->xmlwriter->end_tag('presetcodes'); + } + public function on_programming_datafiles_start() { + $this->xmlwriter->begin_tag('datafiles'); + } + public function on_programming_datafiles_end() { + $this->xmlwriter->end_tag('datafiles'); + } + public function on_programming_testcases_start() { + $this->xmlwriter->begin_tag('testcases'); + } + public function on_programming_testcases_end() { + $this->xmlwriter->end_tag('testcases'); + } + public function on_programming_submits_start() { + $this->xmlwriter->begin_tag('submits'); + } + public function on_programming_submits_end() { + $this->xmlwriter->end_tag('submits'); + } + + public function on_programming_end() { + $this->xmlwriter->end_tag('programming'); + $this->xmlwriter->end_tag('activity'); + $this->close_xml_writer(); + } + public function process_programming_testcase($data) { + $this->write_xml('testcase', $data, array('/testcase/id')); + } + public function process_programming_datafile($data) { + $this->write_xml('datafile', $data, array('/datafile/id')); + } + public function process_programming_presetcode($data) { + $this->write_xml('presetcode', $data, array('/presetcode/id')); + } + public function process_programming_langlimit($data) { + $this->write_xml('langlimit', $data, array('/langlimit/id')); + } + public function process_programming_submit($data) { + $this->write_xml('submit', $data, array('/submit/id')); + } +} diff --git a/backup/moodle2/backup_base64_element.class.php b/backup/moodle2/backup_base64_element.class.php new file mode 100644 index 0000000..b3e6b05 --- /dev/null +++ b/backup/moodle2/backup_base64_element.class.php @@ -0,0 +1,9 @@ +. + +/** + * @package moodlecore + * @subpackage backup-moodle2 + * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +require_once($CFG->dirroot . '/mod/programming/backup/moodle2/backup_programming_stepslib.php'); // Because it exists (must) + +/** + * programming backup task that provides all the settings and steps to perform one + * complete backup of the activity + */ +class backup_programming_activity_task extends backup_activity_task { + + /** + * Define (add) particular settings this activity can have + */ + protected function define_my_settings() { + // No particular settings for this activity + } + + /** + * Define (add) particular steps this activity can have + */ + protected function define_my_steps() { + // Choice only has one structure step + $this->add_step(new backup_programming_activity_structure_step('programming_structure', 'programming.xml')); + } + + /** + * Code the transformations to perform in the activity in + * order to get transportable (encoded) links + */ + static public function encode_content_links($content) { + global $CFG; + + $base = preg_quote($CFG->wwwroot,"/"); + + // Link to the list of programmings + $search="/(".$base."\/mod\/programming\/index.php\?id\=)([0-9]+)/"; + $content= preg_replace($search, '$@PROGRAMMINGINDEX*$2@$', $content); + + // Link to programming view by moduleid + $search="/(".$base."\/mod\/programming\/view.php\?id\=)([0-9]+)/"; + $content= preg_replace($search, '$@PROGRAMMINGVIEWBYID*$2@$', $content); + + return $content; + } +} diff --git a/backup/moodle2/backup_programming_stepslib.php b/backup/moodle2/backup_programming_stepslib.php new file mode 100644 index 0000000..b9c26c2 --- /dev/null +++ b/backup/moodle2/backup_programming_stepslib.php @@ -0,0 +1,90 @@ +get_setting_value('userinfo'); + + // Define each element separated + $programming = new backup_nested_element('programming', array('id'), array( + 'name', 'intro', 'introformat', 'grade', + 'globalid', 'timeopen', 'timeclose', 'timelimit', 'memlimit', + 'nproc', 'timediscount', 'discount', 'allowlate', 'attempts', + 'keeplatestonly', 'inputfile', 'outputfile', 'presetcode', + 'generator', 'validator', 'generatortype', 'validatortype', + 'validatorlang', 'showmode', 'timemodified')); + + $languages = new backup_nested_element('langlimits'); + $language = new backup_nested_element('langlimit', array('id'), array('languageid')); + + $testcases = new backup_nested_element('testcases'); + $testcase = new backup_nested_element('testcase', array('id'), array('seq', + new backup_base64_element('input'), new backup_base64_element('gzinput'), + new backup_base64_element('output'), new backup_base64_element('gzoutput'), + 'cmdargs', 'timelimit', 'memlimit', 'nproc', 'pub', 'weight', 'memo', + 'timemodified')); + + $datafiles = new backup_nested_element('datafiles'); + $datafile = new backup_nested_element('datafile', array('id'), array( + 'seq', 'filename', 'isbinary', 'datasize', new backup_base64_element('data'), + 'checkdatasize', new backup_base64_element('checkdata'), 'memo', 'timemodified')); + + $presetcodes = new backup_nested_element('presetcodes'); + $presetcode = new backup_nested_element('presetcode', array('id'), array( + 'languageid', 'name', 'sequence', 'presetcode', 'presetcodeforcheck')); + + $submits = new backup_nested_element('submits'); + $submit = new backup_nested_element('submit', array('id'), array( + 'userid', 'timemodified', 'language', 'code', + 'codelines', 'codesize', 'status', 'compilemessage', + 'timeused', 'memused', 'judgeresult', 'passed')); + + $programming->add_child($languages); + $languages->add_child($language); + + $programming->add_child($testcases); + $testcases->add_child($testcase); + + $programming->add_child($datafiles); + $datafiles->add_child($datafile); + + $programming->add_child($presetcodes); + $presetcodes->add_child($presetcode); + + $programming->add_child($submits); + $submits->add_child($submit); + + // Define sources + $programming->set_source_table('programming', array('id' => backup::VAR_ACTIVITYID)); + $language->set_source_table('programming_langlimit', array('programmingid' => backup::VAR_PARENTID)); + $testcase->set_source_table('programming_tests', array('programmingid' => backup::VAR_PARENTID)); + $datafile->set_source_table('programming_datafile', array('programmingid' => backup::VAR_PARENTID)); + $presetcode->set_source_table('programming_presetcode', array('programmingid' => backup::VAR_PARENTID)); + + // All the rest of elements only happen if we are including user info + if ($userinfo) { + $submit->set_source_table('programming_submits', array('programmingid' => backup::VAR_PARENTID)); + } + + // Define id annotations + $programming->annotate_ids('scale', 'grade'); + $submit->annotate_ids('user', 'userid'); + + // Define file annotations + $programming->annotate_files('mod_programming', 'intro', null); // This file area hasn't itemid + + // Return the root element (programming), wrapped into standard activity structure + return $this->prepare_activity_structure($programming); + } +} diff --git a/backup/moodle2/restore_programming_activity_task.class.php b/backup/moodle2/restore_programming_activity_task.class.php new file mode 100644 index 0000000..d0561f5 --- /dev/null +++ b/backup/moodle2/restore_programming_activity_task.class.php @@ -0,0 +1,112 @@ +. + +/** + * @package moodlecore + * @subpackage backup-moodle2 + * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +require_once($CFG->dirroot . '/mod/programming/backup/moodle2/restore_programming_stepslib.php'); // Because it exists (must) + +/** + * programming restore task that provides all the settings and steps to perform one + * complete restore of the activity + */ +class restore_programming_activity_task extends restore_activity_task { + + /** + * Define (add) particular settings this activity can have + */ + protected function define_my_settings() { + // No particular settings for this activity + } + + /** + * Define (add) particular steps this activity can have + */ + protected function define_my_steps() { + // Choice only has one structure step + $this->add_step(new restore_programming_activity_structure_step('programming_structure', 'programming.xml')); + } + + /** + * Define the contents in the activity that must be + * processed by the link decoder + */ + static public function define_decode_contents() { + $contents = array(); + + $contents[] = new restore_decode_content('programming', array('intro'), 'programming'); + + return $contents; + } + + /** + * Define the decoding rules for links belonging + * to the activity to be executed by the link decoder + */ + static public function define_decode_rules() { + $rules = array(); + + $rules[] = new restore_decode_rule('PROGRAMMINGVIEWBYID', '/mod/programming/view.php?id=$1', 'course_module'); + $rules[] = new restore_decode_rule('PROGRAMMINGINDEX', '/mod/programming/index.php?id=$1', 'course'); + + return $rules; + + } + + /** + * Define the restore log rules that will be applied + * by the {@link restore_logs_processor} when restoring + * programming logs. It must return one array + * of {@link restore_log_rule} objects + */ + static public function define_restore_log_rules() { + $rules = array(); + + $rules[] = new restore_log_rule('programming', 'add', 'view.php?id={course_module}', '{programming}'); + $rules[] = new restore_log_rule('programming', 'update', 'view.php?id={course_module}', '{programming}'); + $rules[] = new restore_log_rule('programming', 'view', 'view.php?id={course_module}', '{programming}'); + $rules[] = new restore_log_rule('programming', 'upload', 'view.php?a={programming}', '{programming}'); + $rules[] = new restore_log_rule('programming', 'view submission', 'submissions.php.php?id={course_module}', '{programming}'); + $rules[] = new restore_log_rule('programming', 'update grades', 'submissions.php.php?id={course_module}&user={user}', '{user}'); + + return $rules; + } + + /** + * Define the restore log rules that will be applied + * by the {@link restore_logs_processor} when restoring + * course logs. It must return one array + * of {@link restore_log_rule} objects + * + * Note this rules are applied when restoring course logs + * by the restore final task, but are defined here at + * activity level. All them are rules not linked to any module instance (cmid = 0) + */ + static public function define_restore_log_rules_for_course() { + $rules = array(); + + $rules[] = new restore_log_rule('programming', 'view all', 'index.php?id={course}', null); + + return $rules; + } +} diff --git a/backup/moodle2/restore_programming_stepslib.php b/backup/moodle2/restore_programming_stepslib.php new file mode 100644 index 0000000..2ed1ea5 --- /dev/null +++ b/backup/moodle2/restore_programming_stepslib.php @@ -0,0 +1,146 @@ +. + +/** + * @package moodlecore + * @subpackage backup-moodle2 + * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +/** + * Define all the restore steps that will be used by the restore_programming_activity_task + */ + +/** + * Structure step to restore one programming activity + */ +class restore_programming_activity_structure_step extends restore_activity_structure_step { + + protected function define_structure() { + + $paths = array(); + $userinfo = $this->get_setting_value('userinfo'); + + $programming = new restore_path_element('programming', '/activity/programming'); + $paths[] = $programming; + $paths[] = new restore_path_element('programming_langlimit', '/activity/programming/langlimits/langlimit'); + $paths[] = new restore_path_element('programming_presetcode', '/activity/programming/presetcodes/presetcode'); + $paths[] = new restore_path_element('programming_datefile', '/activity/programming/datefiles/datefile'); + $paths[] = new restore_path_element('programming_testcase', '/activity/programming/testcases/testcase'); + + + if ($userinfo) { + $paths[] = new restore_path_element('programming_submit', '/activity/programming/submits/submit'); + } + + // Return the paths wrapped into standard activity structure + return $this->prepare_activity_structure($paths); + } + + protected function process_programming($data) { + global $DB; + + $data = (object)$data; + $oldid = $data->id; + $data->course = $this->get_courseid(); + + $data->timeopen = $this->apply_date_offset($data->timeopen); + $data->timeclose = $this->apply_date_offset($data->timeclose); + $data->timemodified = $this->apply_date_offset($data->timemodified); + // insert the programming record + $newitemid = $DB->insert_record('programming', $data); + // immediately after inserting "activity" record, call this + $this->apply_activity_instance($newitemid); + } + + protected function process_programming_submit($data) { + global $DB; + + $data = (object)$data; + $oldid = $data->id; + + $data->programmingid = $this->get_new_parentid('programming'); + + $data->userid = $this->get_mappingid('user', $data->userid); + + $newitemid = $DB->insert_record('programming_submits', $data); + $this->set_mapping('programming_submit', $oldid, $newitemid, true); // Going to have files + // $this->set_mapping(restore_gradingform_plugin::itemid_mapping('submission'), $oldid, $newitemid); + } + + protected function process_programming_langlimit($data) { + global $DB; + + $data = (object)$data; + $oldid = $data->id; + + $data->programmingid = $this->get_new_parentid('programming'); + + $newitemid = $DB->insert_record('programming_langlimit', $data); + $this->set_mapping('programming_langlimit', $oldid, $newitemid); + } + + protected function process_programming_presetcode($data) { + global $DB; + + $data = (object)$data; + $oldid = $data->id; + + $data->programmingid = $this->get_new_parentid('programming'); + + $newitemid = $DB->insert_record('programming_presetcode', $data); + $this->set_mapping('programming_presetcode', $oldid, $newitemid); + } + + protected function process_programming_datefile($data) { + global $DB; + + $data = (object)$data; + $oldid = $data->id; + + $data->programmingid = $this->get_new_parentid('programming'); + $data->data = base64_decode($data->data); + $data->checkdata = base64_decode($data->checkdata); + + $newitemid = $DB->insert_record('programming_datefile', $data); + $this->set_mapping('programming_datefile', $oldid, $newitemid); + } + + protected function process_programming_testcase($data) { + global $DB; + + $data = (object)$data; + $oldid = $data->id; + + $data->programmingid = $this->get_new_parentid('programming'); + + $data->input = base64_decode($data->input); + $data->gzinput = base64_decode($data->gzinput); + $data->output = base64_decode($data->output); + $data->gzoutput = base64_decode($data->gzoutput); + + $newitemid = $DB->insert_record('programming_tests', $data); + $this->set_mapping('programming_testcase', $oldid, $newitemid); + } + + protected function after_execute() { + // Add programming related files, no need to match by itemname (just internally handled context) + $this->add_related_files('mod_programming', 'intro', null); + // Add programming submission files, matching by programming_submission itemname + } +} diff --git a/codemirror/.travis.yml b/codemirror/.travis.yml new file mode 100644 index 0000000..baa0031 --- /dev/null +++ b/codemirror/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - 0.8 diff --git a/codemirror/CONTRIBUTING.md b/codemirror/CONTRIBUTING.md new file mode 100644 index 0000000..afc1837 --- /dev/null +++ b/codemirror/CONTRIBUTING.md @@ -0,0 +1,70 @@ +# How to contribute + +- [Getting help](#getting-help-) +- [Submitting bug reports](#submitting-bug-reports-) +- [Contributing code](#contributing-code-) + +## Getting help [^](#how-to-contribute) + +Community discussion, questions, and informal bug reporting is done on the +[CodeMirror Google group](http://groups.google.com/group/codemirror). + +## Submitting bug reports [^](#how-to-contribute) + +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 [^](#how-to-contribute) + +- 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`). +- 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 (`test/lint/lint.js`) which is run after each + commit complains about unused variables and functions. Prefix their + names with an underscore to muffle it. diff --git a/codemirror/LICENSE b/codemirror/LICENSE new file mode 100644 index 0000000..3916e96 --- /dev/null +++ b/codemirror/LICENSE @@ -0,0 +1,23 @@ +Copyright (C) 2012 by Marijn Haverbeke + +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. + +Please note that some subdirectories of the CodeMirror distribution +include their own LICENSE files, and are released under different +licences. diff --git a/codemirror/README.md b/codemirror/README.md new file mode 100644 index 0000000..976584e --- /dev/null +++ b/codemirror/README.md @@ -0,0 +1,9 @@ +# CodeMirror [![Build Status](https://secure.travis-ci.org/marijnh/CodeMirror.png?branch=master)](http://travis-ci.org/marijnh/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) diff --git a/codemirror/bin/compress b/codemirror/bin/compress new file mode 100644 index 0000000..de86ca1 --- /dev/null +++ b/codemirror/bin/compress @@ -0,0 +1,90 @@ +#!/usr/bin/env node + +// Compression helper for CodeMirror +// +// Example: +// +// bin/compress codemirror runmode javascript xml +// +// Will take lib/codemirror.js, lib/util/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 = 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]; + args = parts.slice(1); + } 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("mode/"); + +if (!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, {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); +} diff --git a/codemirror/demo/activeline.html b/codemirror/demo/activeline.html new file mode 100644 index 0000000..457d69c --- /dev/null +++ b/codemirror/demo/activeline.html @@ -0,0 +1,76 @@ + + + + + CodeMirror: Active Line Demo + + + + + + + + +

CodeMirror: Active Line Demo

+ +
+ + + +

Styling the current cursor line.

+ + + diff --git a/codemirror/demo/btree.html b/codemirror/demo/btree.html new file mode 100644 index 0000000..c23a7de --- /dev/null +++ b/codemirror/demo/btree.html @@ -0,0 +1,87 @@ + + + + + CodeMirror: B-Tree visualization + + + + + + + +

CodeMirror: B-Tree visualization

+ +

Shows a visual representation of the b-tree that CodeMirror + uses to store its document. See + the corresponding + blog post for a description of this format. The gray blocks + under each leaf show the lines it holds (with their width + representing the line height). Add and remove content to see how + the nodes are split and merged to keep the tree balanced.

+ +
+
+
+
+
+
+ + + +

+ + + diff --git a/codemirror/demo/changemode.html b/codemirror/demo/changemode.html new file mode 100644 index 0000000..364c5cd --- /dev/null +++ b/codemirror/demo/changemode.html @@ -0,0 +1,50 @@ + + + + + CodeMirror: Mode-Changing Demo + + + + + + + + + +

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

+ + + + diff --git a/codemirror/demo/closetag.html b/codemirror/demo/closetag.html new file mode 100644 index 0000000..c33d108 --- /dev/null +++ b/codemirror/demo/closetag.html @@ -0,0 +1,37 @@ + + + + + CodeMirror: Close-Tag Demo + + + + + + + + + + + + +

Close-Tag Demo

+
    +
  • Type an html tag. When you type '>' or '/', the tag will auto-close/complete. Block-level tags will indent.
  • +
  • There are options for disabling tag closing or customizing the list of tags to indent.
  • +
  • Works with "text/html" (based on htmlmixed.js or xml.js) mode.
  • +
  • View source for key binding details.
  • +
+ +
+ + + + diff --git a/codemirror/demo/complete.html b/codemirror/demo/complete.html new file mode 100644 index 0000000..13569ed --- /dev/null +++ b/codemirror/demo/complete.html @@ -0,0 +1,70 @@ + + + + + CodeMirror: Autocomplete Demo + + + + + + + + + +

CodeMirror: Autocomplete demo

+ +
+ +

Press ctrl-space to activate autocompletion. See +the code (here +and here) to figure out +how it works.

+ + + + diff --git a/codemirror/demo/emacs.html b/codemirror/demo/emacs.html new file mode 100644 index 0000000..b37a46b --- /dev/null +++ b/codemirror/demo/emacs.html @@ -0,0 +1,60 @@ + + + + + CodeMirror: Emacs bindings demo + + + + + + + + + +

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

+ + + + + diff --git a/codemirror/demo/folding.html b/codemirror/demo/folding.html new file mode 100644 index 0000000..89120cb --- /dev/null +++ b/codemirror/demo/folding.html @@ -0,0 +1,67 @@ + + + + + CodeMirror: Code Folding Demo + + + + + + + + + + +

CodeMirror: Code Folding Demo

+ +

Demonstration of code folding using the code + in foldcode.js. + Press ctrl-q or click on the gutter to fold a block, again + to unfold.

+
+
JavaScript:
+
HTML:
+
+ + + diff --git a/codemirror/demo/formatting.html b/codemirror/demo/formatting.html new file mode 100644 index 0000000..b9e800d --- /dev/null +++ b/codemirror/demo/formatting.html @@ -0,0 +1,81 @@ + + + + + CodeMirror: Formatting Demo + + + + + + + + + + + + +

CodeMirror: Formatting demo

+ +
+ +

Select a piece of code and click one of the links below to apply automatic formatting to the selected text or comment/uncomment the selected text. Note that the formatting behavior depends on the current block's mode. + + + + + + +
+ + Autoformat Selected + + + + Comment Selected + + + + Uncomment Selected + +
+

+ + + + diff --git a/codemirror/demo/fullscreen.html b/codemirror/demo/fullscreen.html new file mode 100644 index 0000000..2709ebb --- /dev/null +++ b/codemirror/demo/fullscreen.html @@ -0,0 +1,147 @@ + + + + + CodeMirror: Full Screen Editing + + + + + + + + + +

CodeMirror: Full Screen Editing

+ +
+ + +

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

+ + diff --git a/codemirror/demo/loadmode.html b/codemirror/demo/loadmode.html new file mode 100644 index 0000000..20f86cf --- /dev/null +++ b/codemirror/demo/loadmode.html @@ -0,0 +1,71 @@ + + + + + CodeMirror: Lazy Mode Loading Demo + + + + + + + + + + + +
+ + + + + diff --git a/codemirror/demo/marker.html b/codemirror/demo/marker.html new file mode 100644 index 0000000..f0981e4 --- /dev/null +++ b/codemirror/demo/marker.html @@ -0,0 +1,59 @@ + + + + + CodeMirror: Breakpoint Demo + + + + + + + + +

CodeMirror: Breakpoint demo

+ +
+ +

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

+ + + + + diff --git a/codemirror/demo/matchhighlighter.html b/codemirror/demo/matchhighlighter.html new file mode 100644 index 0000000..c8a4bdf --- /dev/null +++ b/codemirror/demo/matchhighlighter.html @@ -0,0 +1,36 @@ + + + + + CodeMirror: Match Highlighter Demo + + + + + + + + + +

CodeMirror: Match Highlighter Demo

+ +
+ + + +

Highlight matches of selected text on select

+ + + diff --git a/codemirror/demo/multiplex.html b/codemirror/demo/multiplex.html new file mode 100644 index 0000000..25fffd3 --- /dev/null +++ b/codemirror/demo/multiplex.html @@ -0,0 +1,60 @@ + + + + + CodeMirror: Multiplexing Parser Demo + + + + + + + + + +

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

+ + + diff --git a/codemirror/demo/mustache.html b/codemirror/demo/mustache.html new file mode 100644 index 0000000..c2ce331 --- /dev/null +++ b/codemirror/demo/mustache.html @@ -0,0 +1,59 @@ + + + + + CodeMirror: Overlay Parser Demo + + + + + + + + + +

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

+ + + diff --git a/codemirror/demo/preview.html b/codemirror/demo/preview.html new file mode 100644 index 0000000..f70cdb0 --- /dev/null +++ b/codemirror/demo/preview.html @@ -0,0 +1,76 @@ + + + + + CodeMirror: HTML5 preview + + + + + + + + + + +

CodeMirror: HTML5 preview

+ + + + + diff --git a/codemirror/demo/resize.html b/codemirror/demo/resize.html new file mode 100644 index 0000000..ddd4e56 --- /dev/null +++ b/codemirror/demo/resize.html @@ -0,0 +1,46 @@ + + + + + CodeMirror: Autoresize Demo + + + + + + + + +

CodeMirror: Autoresize demo

+ +
+ +

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

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

CodeMirror: Mode Runner Demo

+ +
+ +

+
+    
+
+    

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

+ +
+
text (string)
+
The document to run through the highlighter.
+
mode (mode spec)
+
The mode to use (must be loaded as normal).
+
output (function or DOM node)
+
If this is a function, it will be called for each token with + two arguments, the token's text and the token's style class (may + be null for unstyled tokens). If it is a DOM node, + the tokens will be converted to span elements as in + an editor, and inserted into the node + (through innerHTML).
+
+ + + diff --git a/codemirror/demo/search.html b/codemirror/demo/search.html new file mode 100644 index 0000000..219c805 --- /dev/null +++ b/codemirror/demo/search.html @@ -0,0 +1,85 @@ + + + + + CodeMirror: Search/Replace Demo + + + + + + + + + + + + +

CodeMirror: Search/Replace Demo

+ +
+ + + +

Demonstration of primitive search/replace functionality. The + keybindings (which can be overridden by custom keymaps) are:

+
+
Ctrl-F / Cmd-F
Start searching
+
Ctrl-G / Cmd-G
Find next
+
Shift-Ctrl-G / Shift-Cmd-G
Find previous
+
Shift-Ctrl-F / Cmd-Option-F
Replace
+
Shift-Ctrl-R / Shift-Cmd-Option-F
Replace all
+
+

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

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

CodeMirror: Theme demo

+ +
+ +

Select a theme: +

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

CodeMirror: Variable Height Demo

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

CodeMirror: Vim bindings demo

+ +
+ +
+ +

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

+ + + + + diff --git a/codemirror/demo/visibletabs.html b/codemirror/demo/visibletabs.html new file mode 100644 index 0000000..2c6a342 --- /dev/null +++ b/codemirror/demo/visibletabs.html @@ -0,0 +1,55 @@ + + + + + CodeMirror: Visible tabs demo + + + + + + + + + + +

CodeMirror: Visible tabs demo

+ +
+ +

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

CodeMirror: Inline Widget Demo

+ +
+ +

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

+ + diff --git a/codemirror/demo/xmlcomplete.html b/codemirror/demo/xmlcomplete.html new file mode 100644 index 0000000..f7cca8a --- /dev/null +++ b/codemirror/demo/xmlcomplete.html @@ -0,0 +1,74 @@ + + + + + CodeMirror: XML Autocomplete Demo + + + + + + + + + + + +

CodeMirror: XML Autocomplete demo

+ +
+ +

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

+ + + + diff --git a/codemirror/doc/baboon.png b/codemirror/doc/baboon.png new file mode 100644 index 0000000..55d97f7 Binary files /dev/null and b/codemirror/doc/baboon.png differ diff --git a/codemirror/doc/baboon_vector.svg b/codemirror/doc/baboon_vector.svg new file mode 100644 index 0000000..dc1667a --- /dev/null +++ b/codemirror/doc/baboon_vector.svg @@ -0,0 +1,153 @@ + + + +image/svg+xml \ No newline at end of file diff --git a/codemirror/doc/compress.html b/codemirror/doc/compress.html new file mode 100644 index 0000000..94df0c5 --- /dev/null +++ b/codemirror/doc/compress.html @@ -0,0 +1,174 @@ + + + + + CodeMirror: Compression Helper + + + + + +

{ } CodeMirror

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

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

+ +
+ +

Version:

+ +

+ +

+ with UglifyJS +

+ +

Custom code to add to the compressed file:

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

{ } CodeMirror

+ +
+ +
+/* (Re-) Implementing A Syntax-
+   Highlighting Editor in JavaScript */
+
+
+ +
+ +

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

+ +

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

+ +

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

+ +

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

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

+ +

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

+ +

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

+ +

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

+ +

General Approach

+ +

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

+ +

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

+ +

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

+ +

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

+ +

Input

+ +

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

+ +

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

+ +

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

+ +

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

+ +

Selection

+ +

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

+ +

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

+ +

But not something that the browser selection APIs expose.

+ +

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

+ +

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

+ +

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

+ +

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

+ +

Intelligent Updating

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

Parsers can be Simple

+ +

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

+ +

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

+ +

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

+ +

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

+ +

What Gives?

+ +

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

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

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

+ +

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

+ +

Content Representation

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

Keymaps

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +
+ +
 
+ + diff --git a/codemirror/doc/manual.html b/codemirror/doc/manual.html new file mode 100644 index 0000000..e7568a1 --- /dev/null +++ b/codemirror/doc/manual.html @@ -0,0 +1,1493 @@ + + + + + CodeMirror: User Manual + + + + + + + + + + + + + + +

{ } CodeMirror

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

Overview

+ +

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

+ +

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

+ +

Basic Usage

+ +

The easiest way to use CodeMirror is to simply load the script + and style sheet found under lib/ in the distribution, + plus a mode script from one of the mode/ directories. + (See the compression helper for an + easy way to combine scripts.) For example:

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

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

+ +
var myCodeMirror = CodeMirror(document.body);
+ +

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

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

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

+ +

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

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

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

+ +
var myCodeMirror = CodeMirror.fromTextArea(myTextArea);
+ +

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

+ +

Configuration

+ +

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

+ +

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

+ +

These are the supported options:

+ +
+
value (string)
+
The starting value of the editor.
+ +
mode (string or object)
+
The mode to use. When not given, this will default to the + first mode that was loaded. It may be a string, which either + simply names the mode or is + a MIME type + associated with the mode. Alternatively, it may be an object + containing configuration options for the mode, with + a name property that names the mode (for + example {name: "javascript", json: true}). The demo + pages for each mode contain information about what configuration + parameters the mode supports. You can ask CodeMirror which modes + and MIME types have been defined by inspecting + the CodeMirror.modes + and CodeMirror.mimeModes objects. The first maps + mode names to their constructors, and the second maps MIME types + to mode specs.
+ +
theme (string)
+
The theme to style the editor with. You must make sure the + CSS file defining the corresponding .cm-s-[name] + styles is loaded (see + the theme directory in the + distribution). The default is "default", for which + colors are included in codemirror.css. It is + possible to use multiple theming classes at once—for + example "foo bar" will assign both + the cm-s-foo and the cm-s-bar classes + to the editor.
+ +
indentUnit (integer)
+
How many spaces a block (whatever that means in the edited + language) should be indented. The default is 2.
+ +
smartIndent (boolean)
+
Whether to use the context-sensitive indentation that the + mode provides (or just indent the same as the line before). + Defaults to true.
+ +
tabSize (integer)
+
The width of a tab character. Defaults to 4.
+ +
indentWithTabs (boolean)
+
Whether, when indenting, the first N*tabSize + spaces should be replaced by N tabs. Default is false.
+ +
electricChars (boolean)
+
Configures whether the editor should re-indent the current + line when a character is typed that might change its proper + indentation (only works if the mode supports indentation). + Default is true.
+ +
rtlMoveVisually (boolean)
+
Determines whether horizontal cursor movement through + right-to-left (Arabic, Hebrew) text is visual (pressing the left + arrow moves the cursor left) or logical (pressing the left arrow + moves to the next lower index in the string, which is visually + right in right-to-left text). The default is false + on Windows, and true on other platforms.
+ +
keyMap (string)
+
Configures the keymap to use. The default + is "default", which is the only keymap defined + in codemirror.js itself. Extra keymaps are found in + the keymap directory. See + the section on keymaps for more + information.
+ +
extraKeys (object)
+
Can be used to specify extra keybindings for the editor, + alongside the ones defined + by keyMap. Should be + either null, or a valid keymap value.
+ +
lineWrapping (boolean)
+
Whether CodeMirror should scroll or wrap for long lines. + Defaults to false (scroll).
+ +
lineNumbers (boolean)
+
Whether to show line numbers to the left of the editor.
+ +
firstLineNumber (integer)
+
At which number to start counting lines. Default is 1.
+ +
lineNumberFormatter (function)
+
A function used to format line numbers. The function is + passed the line number, and should return a string that will be + shown in the gutter.
+ +
gutters (array)
+
Can be used to add extra gutters (beyond or instead of the + line number gutter). Should be an array of CSS class names, each + of which defines a width (and optionally a + background), and which will be used to draw the background of + the gutters. May include + the CodeMirror-linenumbers class, in order to + explicitly set the position of the line number gutter (it will + default to be to the right of all other gutters). These class + names are the keys passed + to setGutterMarker.
+ +
readOnly (boolean)
+
This disables editing of the editor content by the user. If + the special value "nocursor" is given (instead of + simply true), focusing of the editor is also + disallowed.
+ +
showCursorWhenSelecting (boolean)
+
Whether the cursor should be drawn when a selection is + active. Defaults to false.
+ +
undoDepth (integer)
+
The maximum number of undo levels that the editor stores. + Defaults to 40.
+ +
tabindex (integer)
+
The tab + index to assign to the editor. If not given, no tab index + will be assigned.
+ +
autofocus (boolean)
+
Can be used to make CodeMirror focus itself on + initialization. Defaults to off. + When fromTextArea is + used, and no explicit value is given for this option, it will be + set to true when either the source textarea is focused, or it + has an autofocus attribute and no other element is + focused.
+
+ +

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

+ +
+
dragDrop (boolean)
+
Controls whether drag-and-drop is enabled. On by default.
+ +
onDragEvent (function)
+
When given, this will be called when the editor is handling + a dragenter, dragover, + or drop event. It will be passed the editor instance + and the event object as arguments. The callback can choose to + handle the event itself, in which case it should + return true to indicate that CodeMirror should not + do anything further.
+ +
onKeyEvent (function)
+
This provides a rather low-level hook into CodeMirror's key + handling. If provided, this function will be called on + every keydown, keyup, + and keypress event that CodeMirror captures. It + will be passed two arguments, the editor instance and the key + event. This key event is pretty much the raw key event, except + that a stop() method is always added to it. You + could feed it to, for example, jQuery.Event to + further normalize it.
This function can inspect the key + event, and handle it if it wants to. It may return true to tell + CodeMirror to ignore the event. Be wary that, on some browsers, + stopping a keydown does not stop + the keypress from firing, whereas on others it + does. If you respond to an event, you should probably inspect + its type property and only do something when it + is keydown (or keypress for actions + that need character data).
+ +
cursorBlinkRate (number)
+
Half-period in milliseconds used for cursor blinking. The default blink + rate is 530ms.
+ +
cursorHeight (number)
+
Determines the height of the cursor. Default is 1, meaning + it spans the whole height of the line. For some fonts (and by + some tastes) a smaller height (for example 0.85), + which causes the cursor to not reach all the way to the bottom + of the line, looks better
+ +
workTime, workDelay (number)
+
Highlighting is done by a pseudo background-thread that will + work for workTime milliseconds, and then use + timeout to sleep for workDelay milliseconds. The + defaults are 200 and 300, you can change these options to make + the highlighting more or less aggressive.
+ +
pollInterval (number)
+
Indicates how quickly CodeMirror should poll its input + textarea for changes (when focused). Most input is captured by + events, but some things, like IME input on some browsers, don't + generate events that allow CodeMirror to properly detect it. + Thus, it polls. Default is 100 milliseconds.
+ +
flattenSpans (boolean)
+
By default, CodeMirror will combine adjacent tokens into a + single span if they have the same class. This will result in a + simpler DOM tree, and thus perform better. With some kinds of + styling (such as rounded corners), this will change the way the + document looks. You can set this option to false to disable this + behavior.
+ +
viewportMargin (integer)
+
Specifies the amount of lines that are rendered above and + below the part of the document that's currently scrolled into + view. This affects the amount of updates needed when scrolling, + and the amount of work that such an update does. You should + usually leave it at its default, 100. Can be set + to Infinity to make sure the whole document is + always rendered, and thus the browser's text search works on it. + This will have bad effects on performance of big + documents.
+
+ +

Events

+ +

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

+ +
+
"change" (instance, changeObj)
+
Fires every time the content of the editor is changed. + The changeObj is a {from, to, text, + next} object containing information about the changes + that occurred as second argument. from + and to are the positions (in the pre-change + coordinate system) where the change started and ended (for + example, it might be {ch:0, line:18} if the + position is at the beginning of line #19). text is + an array of strings representing the text that replaced the + changed range (split by line). If multiple changes happened + during a single operation, the object will have + a next property pointing to another change object + (which may point to another, etc).
+ +
"cursorActivity" (instance)
+
Will be fired when the cursor or selection moves, or any + change is made to the editor content.
+ +
"viewportChange" (instance, from, to)
+
Fires whenever the view port of + the editor changes (due to scrolling, editing, or any other + factor). The from and to arguments + give the new start and end of the viewport.
+ +
"gutterClick" (instance, line, gutter, clickEvent)
+
Fires when the editor gutter (the line-number area) is + clicked. Will pass the editor instance as first argument, the + (zero-based) number of the line that was clicked as second + argument, the CSS class of the gutter that was clicked as third + argument, and the raw mousedown event object as + fourth argument.
+ +
"focus", "blur" (instance)
+
These fire whenever the editor is focused or unfocused.
+ +
"scroll" (instance)
+
Fires when the editor is scrolled.
+ +
"update" (instance)
+
Will be fired whenever CodeMirror updates its DOM display.
+
+ +

It is also possible to register events + on other objects. Line handles (as returned by, for + example, getLineHandle) + can be listened on with CodeMirror.on(handle, "delete", + myFunc). They support the following events:

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

Marked range handles, as returned + by markText, emit the + following event:

+ +
+
"clear" ()
+
Fired when the range is cleared, either through cursor + movement in combination + with clearOnEnter + or through a call to its clear() method. Will only + be fired once per handle. Note that deleting the range through + text editing does not fire this event, because an undo + action might bring the range back into existence.
+
+ +

Keymaps

+ +

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

+ +

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

+ +

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

+ +

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

+ +

The values of properties in keymaps can be either functions of + a single argument (the CodeMirror instance), strings, or + false. Such strings refer to properties of the + CodeMirror.commands object, which defines a number of + common commands that are used by the default keybindings, and maps + them to functions. If the property is set to false, + CodeMirror leaves handling of the key up to the browser. A key + handler function may throw CodeMirror.Pass to indicate + that it has decided not to handle the key, and other handlers (or + the default behavior) should be given a turn.

+ +

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

+ +

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

+ +

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

+ +

Customized Styling

+ +

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

+ +

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

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

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

+ +

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

+ +

Programming API

+ +

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

+ +

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

+ +
+
getValue() → string
+
Get the current editor content. You can pass it an optional + argument to specify the string to be used to separate lines + (defaults to "\n").
+
setValue(string)
+
Set the editor content.
+ +
lineCount() → number
+
Get the number of lines in the editor.
+ +
getRange(from, to) → string +
Get the text between the given points in the editor, which + should be {line, ch} objects. An optional third + argument can be given to indicate the line separator string to + use (defaults to "\n").
+
replaceRange(string, from, to)
+
Replace the part of the document between from + and to with the given string. from + and to must be {line, ch} + objects. to can be left off to simply insert the + string at position from.
+ +
getSelection() → string
+
Get the currently selected code.
+
replaceSelection(string)
+
Replace the selection with the given string.
+ +
getCursor(start) → object
+
start is a boolean indicating whether the start + or the end of the selection must be retrieved. If it is not + given, the current cursor pos, i.e. the side of the selection + that would move if you pressed an arrow key, is chosen. + Alternatively, you can pass one of the + strings "start", "end", "head" + (same as not passing anything), or "anchor" (the + opposite). A {line, ch} object will be + returned.
+
somethingSelected() → boolean
+
Return true if any text is selected.
+
setCursor(pos)
+
Set the cursor position. You can either pass a + single {line, ch} object, or the line and the + character as two separate parameters.
+
setSelection(anchor, head)
+
Set the selection range. anchor + and head should be {line, ch} + objects. head defaults to anchor when + not givne.
+ +
getLine(n) → string
+
Get the content of line n.
+
setLine(n, text)
+
Set the content of line n.
+
removeLine(n)
+
Remove the given line from the document.
+ +
setSize(width, height)
+
Programatically set the size of the editor (overriding the + applicable CSS + rules). width and height height + can be either numbers (interpreted as pixels) or CSS units + ("100%", for example). You can + pass null for either of them to indicate that that + dimension should not be changed.
+
focus()
+
Give the editor focus.
+
scrollTo(x, y)
+
Scroll the editor to a given (pixel) position. Both + arguments may be left as null + or undefined to have no effect.
+
getScrollInfo()
+
Get an {left, top, width, height, clientWidth, + clientHeight} object that represents the current scroll + position, the size of the scrollable area, and the size of the + visible area (minus scrollbars).
+
scrollIntoView(pos)
+
Scrolls the given element into view. pos may be + either a {line, ch} position, referring to a given + character, null, to refer to the cursor, or + a {left, top, right, bottom} object, in + editor-local coordinates.
+ +
setOption(option, value)
+
Change the configuration of the editor. option + should the name of an option, + and value should be a valid value for that + option.
+
getOption(option) → value
+
Retrieves the current value of the given option for this + editor instance.
+
getMode() → object
+
Gets the mode object for the editor. Note that this is + distinct from getOption("mode"), which gives you + the mode specification, rather than the resolved, instantiated + mode object.
+ +
addKeyMap(map)
+
Attach an additional keymap to the editor. This is mostly + useful for add-ons that need to register some key handlers + without trampling on + the extraKeys + option. Maps added in this way have a lower precedence + than extraKeys, a higher precedence than the + base keyMap, and + between them, the maps added earlier have a higher precedence + than those added later.
+
removeKeyMap(map)
+
Disable a keymap added + with addKeyMap. Either + pass in the keymap object itself, or a string, which will be + compared against the name property of the active + keymaps.
+ +
addOverlay(mode, options)
+
Enable a highlighting overlay. This is a stateless mini-mode + that can be used to add extra highlighting. For example, + the search add-on uses it to + highlight the term that's currently being + searched. mode can be a mode + spec or a mode object (an object with + a token method). + The option parameter is optional. If given it + should be an object. Currently, only the opaque + option is recognized. This defaults to off, but can be given to + allow the overlay styling, when not null, to + override the styling of the base mode entirely, instead of the + two being applied together.
+
removeOverlay(mode)
+
Pass this the exact argument passed for + the mode parameter + to addOverlay to remove + an overlay again.
+ +
on(type, func)
+
Register an event handler for the given event type (a + string) on the editor instance. There is also + a CodeMirror.on(object, type, func) version + that allows registering of events on any object.
+
off(type, func)
+
Remove an event handler on the editor instance. An + equivalent CodeMirror.off(object, type, + func) also exists.
+ +
cursorCoords(where, mode) → object
+
Returns an {left, top, bottom} object + containing the coordinates of the cursor position. + If mode is "local", they will be + relative to the top-left corner of the editable document. If it + is "page" or not given, they are relative to the + top-left corner of the page. where can be a boolean + indicating whether you want the start (true) or the + end (false) of the selection, or, if a {line, + ch} object is given, it specifies the precise position at + which you want to measure.
+
charCoords(pos, mode) → object
+
Returns the position and dimensions of an arbitrary + character. pos should be a {line, ch} + object. This differs from cursorCoords in that + it'll give the size of the whole character, rather than just the + position that the cursor would have when it would sit at that + position.
+
coordsChar(object) → pos
+
Given an {left, top} object (in page coordinates), + returns the {line, ch} position that corresponds to + it.
+
defaultTextHeight() → number
+
Returns the line height of the default font for the editor.
+ +
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.
+
isClean() → boolean
+
Returns whether the document is currently clean (not + modified since initialization or the last call + to markClean).
+ +
undo()
+
Undo one edit (if any undo events are stored).
+
redo()
+
Redo one undone edit.
+
historySize() → object
+
Returns an object with {undo, redo} properties, + both of which hold integers, indicating the amount of stored + undo and redo operations.
+
clearHistory()
+
Clears the editor's undo history.
+
getHistory() → object
+
Get a (JSON-serializeable) representation of the undo history.
+
setHistory(object)
+
Replace the editor's undo history with the one provided, + which must be a value as returned + by getHistory. Note that + this will have entirely undefined results if the editor content + isn't also the same as it was when getHistory was + called.
+ +
indentLine(line, dir)
+
Adjust the indentation of the given line. The second + argument (which defaults to "smart") may be one of: +
+
"prev"
+
Base indentation on the indentation of the previous line.
+
"smart"
+
Use the mode's smart indentation if available, behave + like "prev" otherwise.
+
"add"
+
Increase the indentation of the line by + one indent unit.
+
"subtract"
+
Reduce the indentation of the line.
+
+ +
getTokenAt(pos) → object
+
Retrieves information about the token the current mode found + before the given position (a {line, ch} object). The + returned object has the following properties: +
+
start
The character (on the given line) at which the token starts.
+
end
The character at which the token ends.
+
string
The token's string.
+
type
The token type the mode assigned + to the token, such as "keyword" + or "comment" (may also be null).
+
state
The mode's state at the end of this token.
+
+ +
markText(from, to, options) → object
+
Can be used to mark a range of text with a specific CSS + class name. from and to should + be {line, ch} objects. The options + parameter is optional. When given, it should be an object that + may contain the following configuration options: +
+
className (string)
+
Assigns a CSS class to the marked stretch of text.
+
inclusiveLeft (boolean)
Determines whether + text inserted on the left of the marker will end up inside + or outside of it.
+
inclusiveRight (boolean)
Like inclusiveLeft, + but for the right side.
+
atomic (boolean)
+
Atomic ranges act as a single unit when cursor movement is + concerned—i.e. it is impossible to place the cursor inside of + them. In atomic ranges, inclusiveLeft + and inclusiveRight have a different meaning—they + will prevent the cursor from being placed respectively + directly before and directly after the range.
+
collapsed (boolean)
+
Collapsed ranges do not show up in the display. Setting a + range to be collapsed will automatically make it atomic.
+
clearOnEnter (boolean)
+
When enabled, will cause the mark to clear itself whenever + the cursor enters its range. This is mostly useful for + text-replacement widgets that need to 'snap open' when the + user tries to edit them. A + the "clear" event + fired on the range handle can be used to be notified when this + happens.
+
replacedWith (dom node)
+
Use a given node to display this range. Implies both + collapsed and atomic.
+
readOnly +
A read-only span can, as long as it is not cleared, not be + modified except by + calling setValue to reset + the whole document. Note: adding a read-only span + currently clears the undo history of the editor, because + existing undo events being partially nullified by read-only + spans would corrupt the history (in the current + implementation).
+
startStyle
Can be used to specify + an extra CSS class to be applied to the leftmost span that + is part of the marker.
+
endStyle
Equivalent + to startStyle, but for the rightmost span.
+
+ The method will return an object with two methods, + clear(), which removes the mark, + and find(), which returns a {from, to} + (both document positions), indicating the current position of + the marked range, or undefined if the marker is no + longer in the document.
+ +
setBookmark(pos, widget) → object
+
Inserts a bookmark, a handle that follows the text around it + as it is being edited, at the given position. A bookmark has two + methods find() and clear(). The first + returns the current position of the bookmark, if it is still in + the document, and the second explicitly removes the bookmark. + The widget argument is optional, and can be used to display a + DOM node at the current location of the bookmark (analogous to + the replacedWith + option to markText).
+ +
findMarksAt(pos) → array
+
Returns an array of all the bookmarks and marked ranges + present at the given position.
+ +
setGutterMarker(line, gutterID, value) → lineHandle
+
Sets the gutter marker for the given gutter (identified by + its CSS class, see + the gutters option) + to the given value. Value can be either null, to + clear the marker, or a DOM element, to set it. The DOM element + will be shown in the specified gutter next to the specified + line.
+ +
clearGutter(gutterID)
+
Remove all gutter markers in + the gutter with the given ID.
+ +
addLineClass(line, where, class) → lineHandle
+
Set a CSS class name for the given line. line + can be a number or a line handle. where determines + to which element this class should be applied, can can be one + of "text" (the text element, which lies in front of + the selection), "background" (a background element + that will be behind the selection), or "wrap" (the + wrapper node that wraps all of the line's elements, including + gutter elements). class should be the name of the + class to apply.
+ +
removeLineClass(line, where, class) → lineHandle
+
Remove a CSS class from a line. line can be a + line handle or number. where should be one + of "text", "background", + or "wrap" + (see addLineClass). class + can be left off to remove all classes for the specified node, or + be a string to remove only a specific class.
+ +
lineInfo(line) → object
+
Returns the line number, text content, and marker status of + the given line, which can be either a number or a line handle. + The returned object has the structure {line, handle, text, + gutterMarkers, textClass, bgClass, wrapClass, widgets}, + where gutterMarkers is an object mapping gutter IDs + to marker elements, and widgets is an array + of line widgets attached to this + line, and the various class properties refer to classes added + with addLineClass.
+ +
getLineHandle(num) → lineHandle
+
Fetches the line handle for the given line number.
+ +
getLineNumber(handle) → integer
+
Given a line handle, returns the current position of that + line (or null when it is no longer in the + document).
+ +
getViewport() → object
+
Returns a {from, to} object indicating the + start (inclusive) and end (exclusive) of the currently displayed + 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.
+ +
addWidget(pos, node, scrollIntoView)
+
Puts node, which should be an absolutely + positioned DOM node, into the editor, positioned right below the + given {line, ch} position. + When scrollIntoView is true, the editor will ensure + that the entire node is visible (if possible). To remove the + widget again, simply use DOM methods (move it somewhere else, or + call removeChild on its parent).
+ +
addLineWidget(line, node, options) → object
+
Adds a line widget, an element shown below a line, spanning + the whole of the editor's width, and moving the lines below it + downwards. line should be either an integer or a + line handle, and node should be a DOM node, which + will be displayed below the given line. options, + when given, should be an object that configures the behavior of + the widget. The following options are supported (all default to + false): +
+
coverGutter (boolean)
+
Whether the widget should cover the gutter.
+
noHScroll (boolean)
+
Whether the widget should stay fixed in the face of + horizontal scrolling.
+
above (boolean)
+
Causes the widget to be placed above instead of below + the text of the line.
+
+ 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 it + can be passed to removeLineWidget to remove the + widget.
+ +
removeLineWidget(widget)
+
Removes the given line widget.
+ +
posFromIndex(index) → object
+
Calculates and returns a {line, ch} object for a + zero-based index who's value is relative to the start of the + editor's text. If the index is out of range of the text then + the returned object is clipped to start or end of the text + respectively.
+
indexFromPos(object) → number
+
The reverse of posFromIndex.
+
+ +

The following are more low-level methods:

+ +
+
operation(func) → result
+
CodeMirror internally buffers changes and only updates its + DOM structure after it has finished performing some operation. + If you need to perform a lot of operations on a CodeMirror + instance, you can call this method with a function argument. It + will call the function, buffering up all changes, and only doing + the expensive update after the function returns. This can be a + lot faster. The return value from this method will be the return + value of your function.
+ +
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.
+ +
extendSelection(pos, pos2)
+
Similar + to setSelection, but + will, if shift is held or + the extending flag is set, move the + head of the selection while leaving the anchor at its current + place. pos2 is optional, and can be passed to + ensure a region (for example a word or paragraph) will end up + selected (in addition to whatever lies between that region and + the current anchor).
+
setExtending(bool)
+
Sets or clears the 'extending' flag, which acts similar to + the shift key, in that it will cause cursor movement and calls + to extendSelection + to leave the selection anchor in place.
+ +
getInputField() → textarea
+
Returns the hidden textarea used to read input.
+
getWrapperElement() → node
+
Returns the DOM node that represents the editor, and + controls its size. Remove this from your tree to delete an + editor instance.
+
getScrollerElement() → node
+
Returns the DOM node that is responsible for the scrolling + of the editor.
+
getGutterElement() → node
+
Fetches the DOM node that contains the editor gutters.
+ +
getStateAfter(line) → state
+
Returns the mode's parser state, if any, at the end of the + given line number. If no line number is given, the state at the + end of the document is returned. This can be useful for storing + parsing errors in the state, or getting other kinds of + contextual information for a line.
+
+ +

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

+ +

The CodeMirror.fromTextArea + method provides another way to initialize an editor. It takes a + textarea DOM node as first argument and an optional configuration + object as second. It will replace the textarea with a CodeMirror + instance, and wire up the form of that textarea (if any) to make + sure the editor contents are put into the textarea when the form + is submitted. A CodeMirror instance created this way has three + additional methods:

+ +
+
save()
+
Copy the content of the editor into the textarea.
+ +
toTextArea()
+
Remove the editor, and restore the original textarea (with + the editor's current content).
+ +
getTextArea() → textarea
+
Returns the textarea that the instance was based on.
+
+ +

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

+ +

Similarly, CodeMirror.defineOption(name, + default, updateFunc) can be used to define new options for + CodeMirror. The updateFunc will be called with the + editor instance and the new value when an editor is initialized, + and whenever the option is modified + through setOption.

+ +

If your extention just needs to run some + code whenever a CodeMirror instance is initialized, + use CodeMirror.defineInitHook. Give it a function as + its only argument, and from then on, that function will be called + (with the instance as argument) whenever a new CodeMirror instance + is initialized.

+ +

Add-ons

+ +

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

+ +
+
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 lib/util/dialog.css.
+
searchcursor.js
+
Adds the getSearchCursor(query, start, caseFold) → + cursor method to CodeMirror instances, which can be used + to implement search/replace functionality. query + can be a regular expression or a string (only strings will match + across lines—if they contain newlines). start + provides the starting position of the search. It can be + a {line, ch} object, or can be left off to default + to the start of the document. caseFold is only + relevant when matching a string. It will cause the search to be + case-insensitive. A search cursor has the following methods: +
+
findNext(), findPrevious() → boolean
+
Search forward or backward from the current position. + The return value indicates whether a match was found. If + matching a regular expression, the return value will be the + array returned by the match method, in case you + want to extract matched groups.
+
from(), to() → object
+
These are only valid when the last call + to findNext or findPrevious did + not return false. They will return {line, ch} + objects pointing at the start and end of the match.
+
replace(text)
+
Replaces the currently found match with the given text + and adjusts the cursor position to reflect the + replacement.
+
+ + +
Implements the search commands. CodeMirror has keys bound to + these by default, but will not do anything with them unless an + implementation is provided. Depends + on searchcursor.js, and will make use + of openDialog when + available to make prompting for search queries less ugly.
+
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.
+
foldcode.js
+
Helps with code folding. + See the demo for an example. + Call CodeMirror.newFoldFunction with a range-finder + helper function to create a function that will, when applied to + a CodeMirror instance and a line number, attempt to fold or + unfold the block starting at the given line. A range-finder is a + language-specific function that also takes an instance and a + line number, and returns an range to be folded, or null if + no block is started on that line. This file + provides CodeMirror.braceRangeFinder, which finds + blocks in brace languages (JavaScript, C, Java, + etc), CodeMirror.indentRangeFinder, for languages + where indentation determines block structure (Python, Haskell), + and CodeMirror.tagRangeFinder, for XML-style + languages.
+
runmode.js
+
Can be used to run a CodeMirror mode over text without + actually opening an editor instance. + See the demo for an + example.
+
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.
+
multiplex.js
+
Mode combinator that can be used to easily 'multiplex' + between several modes. + Defines CodeMirror.multiplexingMode which, when + given as first argument a mode object, and as other arguments + any number of {open, close, mode [, delimStyle]} + objects, will return a mode object that starts parsing using the + mode passed as first argument, but will switch to another mode + as soon as it encounters a string that occurs in one of + the open fields of the passed objects. When in a + sub-mode, it will go back to the top mode again when + the close string is encountered. + Pass "\n" for open or close + if you want to switch on a blank line. + When delimStyle is specified, it will be the token + style returned for the delimiter tokens. The outer mode will not + see the content between the delimiters. + See this demo for an + example.
+
simple-hint.js
+
Provides a framework for showing autocompletion hints. + Defines CodeMirror.simpleHint, which takes a + CodeMirror instance and a hinting function, and pops up a widget + that allows the user to select a completion. Hinting functions + are function that take an editor instance, and return + a {list, from, to} object, where list + is an array of strings (the completions), and from + and to give the start and end of the token that is + being completed. Depends + on lib/util/simple-hint.css.
+
javascript-hint.js
+
Defines CodeMirror.javascriptHint + and CodeMirror.coffeescriptHint, which are simple + hinting functions for the JavaScript and CoffeeScript + modes.
+
match-highlighter.js
+
Adds a matchHighlight method to CodeMirror + instances that can be called (typically from + a cursorActivity + handler) to highlight all instances of a currently selected word + with the a classname given as a first argument to the method. + Depends on + the searchcursor + add-on. Demo here.
+
formatting.js
+
Adds commentRange, autoIndentRange, + and autoFormatRange methods that, respectively, + comment (or uncomment), indent, or format (add line breaks) a + range of code. Demo here.
+
closetag.js
+
Provides utility functions for adding automatic tag closing + to XML modes. See + the demo.
+
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.
+
continuecomment.js
+
Adds a command + called newlineAndIndentContinueComment that you can + bind Enter to in order to have the editor prefix + new lines inside C-like block comments with an asterisk.
+
+ +

Writing CodeMirror Modes

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

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

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

+ +

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

+ +

If you want your mode to provide smart indentation + (through the indentLine + method and the indentAuto + and newlineAndIndent commands, which keys can be + bound to), 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.

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +
+ +
 
+ + + + + diff --git a/codemirror/doc/oldrelease.html b/codemirror/doc/oldrelease.html new file mode 100644 index 0000000..dafe738 --- /dev/null +++ b/codemirror/doc/oldrelease.html @@ -0,0 +1,421 @@ + + + + + CodeMirror + + + + + + +

{ } CodeMirror

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

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

28-03-2011: Version 1.0:

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

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

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

+ + diff --git a/codemirror/doc/realworld.html b/codemirror/doc/realworld.html new file mode 100644 index 0000000..80bfe58 --- /dev/null +++ b/codemirror/doc/realworld.html @@ -0,0 +1,83 @@ + + + + + CodeMirror: Real-world uses + + + + + +

{ } CodeMirror

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

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

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

{ } CodeMirror

+ +
+ +
+/* Reporting bugs
+   effectively */
+
+
+ +
+ +

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

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

{ } CodeMirror

+ +
+ +
+/* Upgrading to
+   v2.2 */
+
+
+ +
+ +

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

+ +

No more default.css

+ +

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

Different key customization

+ +

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

+ +

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

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

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

+ +

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

+ +
  extraKeys: {"Home": "goLineStart"}
+ +

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

+ +
  extraKeys: {"Enter": false}
+ +

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

+ +

Tabs

+ +

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

+ +

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

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

{ } CodeMirror

+ +
+ +
+/* Upgrading to
+   version 3 */
+
+
+ +
+ +

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

+ +

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

+ +

DOM structure

+ +

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

+ +

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

+ +

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

+ +

See the styling section of the +manual for more information.

+ +

Gutter model

+ +

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

+ +

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

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

Event handling

+ +

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

+ +

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

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

markText method arguments

+ +

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

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

Line folding

+ +

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

+ +

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

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

Line CSS classes

+ +

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

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

Position properties

+ +

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

+ +

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

+ +

Bracket matching no longer in core

+ +

The matchBrackets +option is no longer defined in the core editor. +Load lib/util/matchbrackets.js to enable it.

+ +

Mode management

+ +

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

+ +

New features

+ +

Some more reasons to upgrade to version 3.

+ +
    +
  • Bi-directional text support. CodeMirror will now mostly do the + right thing when editing Arabic or Hebrew text.
  • +
  • Arbitrary line heights. Using fonts with different heights + inside the editor (whether off by one pixel or fifty) is now + supported and handled gracefully.
  • +
  • In-line widgets. See the demo + and the docs.
  • +
  • Defining custom options + with CodeMirror.defineOption.
  • +
+ +
+ + + + diff --git a/codemirror/index.html b/codemirror/index.html new file mode 100644 index 0000000..3347d21 --- /dev/null +++ b/codemirror/index.html @@ -0,0 +1,455 @@ + + + + + CodeMirror + + + + + + +

{ } CodeMirror

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

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

+ +

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

+ +
+ +

Usage demos:

+ + + +

Real-world uses:

+ + + +
+ +

Getting the code

+ +

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

+ +

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

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

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

+ +

Documentation

+ +

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

+ +

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

+ +

Support and bug reports

+ +

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

+ +

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

+ +

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

+ +

Supported browsers

+ +

The following desktop browsers are able to run CodeMirror:

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

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

+ +

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

+ +

Commercial support

+ +

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

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

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

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

Support CodeMirror

+ + + + + +

Reading material

+ + + +

Releases

+ +

20-12-2012: Version 2.37:

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

10-12-2012: Version 3.0:

+ +

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

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

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

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

20-11-2012: Version 2.36:

+ + + +

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

+ + + +

22-10-2012: Version 2.35:

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

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

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

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

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

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:

+ + + +

Older releases...

+ +
+ +
 
+ +
+ + +
+ + + diff --git a/codemirror/keymap/emacs.js b/codemirror/keymap/emacs.js new file mode 100644 index 0000000..fab3ab9 --- /dev/null +++ b/codemirror/keymap/emacs.js @@ -0,0 +1,30 @@ +// TODO number prefixes +(function() { + // Really primitive kill-ring implementation. + var killRing = []; + function addToRing(str) { + killRing.push(str); + if (killRing.length > 50) killRing.shift(); + } + function getFromRing() { return killRing[killRing.length - 1] || ""; } + function popFromRing() { if (killRing.length > 1) killRing.pop(); return getFromRing(); } + + CodeMirror.keyMap.emacs = { + "Ctrl-X": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-X");}, + "Ctrl-W": function(cm) {addToRing(cm.getSelection()); cm.replaceSelection("");}, + "Ctrl-Alt-W": function(cm) {addToRing(cm.getSelection()); cm.replaceSelection("");}, + "Alt-W": function(cm) {addToRing(cm.getSelection());}, + "Ctrl-Y": function(cm) {cm.replaceSelection(getFromRing());}, + "Alt-Y": function(cm) {cm.replaceSelection(popFromRing());}, + "Ctrl-/": "undo", "Shift-Ctrl--": "undo", "Shift-Alt-,": "goDocStart", "Shift-Alt-.": "goDocEnd", + "Ctrl-S": "findNext", "Ctrl-R": "findPrev", "Ctrl-G": "clearSearch", "Shift-Alt-5": "replace", + "Ctrl-Z": "undo", "Cmd-Z": "undo", "Alt-/": "autocomplete", "Alt-V": "goPageUp", + "Ctrl-J": "newlineAndIndent", "Enter": false, "Tab": "indentAuto", + fallthrough: ["basic", "emacsy"] + }; + + CodeMirror.keyMap["emacs-Ctrl-X"] = { + "Ctrl-S": "save", "Ctrl-W": "save", "S": "saveAll", "F": "open", "U": "undo", "K": "close", + auto: "emacs", nofallthrough: true + }; +})(); diff --git a/codemirror/keymap/vim.js b/codemirror/keymap/vim.js new file mode 100644 index 0000000..6095a33 --- /dev/null +++ b/codemirror/keymap/vim.js @@ -0,0 +1,2427 @@ +/** + * Supported keybindings: + * + * Motion: + * h, j, k, l + * 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 + * J + * u, Ctrl-r + * m + * r + * + * Modes: + * ESC - leave insert mode, visual mode, and clear input state. + * Ctrl-[, Ctrl-c - same as ESC. + * + * Registers: unamed, -, a-z, A-Z, 0-9 + * (Does not respect the special case for number registers when delete + * operator is made with these commands: %, (, ), , /, ?, n, N, {, } ) + * TODO: Implement the remaining registers. + * Marks: a-z, A-Z, and 0-9 + * TODO: Implement the remaining special marks. They have more complex + * behavior. + * + * Code structure: + * 1. Default keymap + * 2. Variable declarations and short basic helpers + * 3. Instance (External API) implementation + * 4. Internal state tracking objects (input state, counter) implementation + * and instanstiation + * 5. Key handler (the main command dispatcher) implementation + * 6. Motion, operator, and action implementations + * 7. Helper functions for the key handler, motions, operators, and actions + * 8. Set up Vim to work as a keymap for CodeMirror. + */ + +(function() { + 'use strict'; + + var defaultKeymap = [ + // Key to key mapping. This goes first to make it possible to override + // existing mappings. + { keys: ['Left'], type: 'keyToKey', toKeys: ['h'] }, + { keys: ['Right'], type: 'keyToKey', toKeys: ['l'] }, + { keys: ['Up'], type: 'keyToKey', toKeys: ['k'] }, + { keys: ['Down'], type: 'keyToKey', toKeys: ['j'] }, + { keys: ['Space'], type: 'keyToKey', toKeys: ['l'] }, + { keys: ['Backspace'], type: 'keyToKey', toKeys: ['h'] }, + { keys: ['Ctrl-Space'], type: 'keyToKey', toKeys: ['W'] }, + { keys: ['Ctrl-Backspace'], type: 'keyToKey', toKeys: ['B'] }, + { keys: ['Shift-Space'], type: 'keyToKey', toKeys: ['w'] }, + { keys: ['Shift-Backspace'], type: 'keyToKey', toKeys: ['b'] }, + { keys: ['Ctrl-n'], type: 'keyToKey', toKeys: ['j'] }, + { keys: ['Ctrl-p'], type: 'keyToKey', toKeys: ['k'] }, + { keys: ['Ctrl-['], type: 'keyToKey', toKeys: ['Esc'] }, + { keys: ['Ctrl-c'], type: 'keyToKey', toKeys: ['Esc'] }, + { keys: ['s'], type: 'keyToKey', toKeys: ['c', 'l'] }, + { keys: ['S'], type: 'keyToKey', toKeys: ['c', 'c'] }, + { keys: ['Home'], type: 'keyToKey', toKeys: ['0'] }, + { keys: ['End'], type: 'keyToKey', toKeys: ['$'] }, + { keys: ['PageUp'], type: 'keyToKey', toKeys: ['Ctrl-b'] }, + { keys: ['PageDown'], type: 'keyToKey', toKeys: ['Ctrl-f'] }, + // Motions + { keys: ['h'], type: 'motion', + motion: 'moveByCharacters', + motionArgs: { forward: false }}, + { keys: ['l'], type: 'motion', + motion: 'moveByCharacters', + motionArgs: { forward: true }}, + { keys: ['j'], type: 'motion', + motion: 'moveByLines', + motionArgs: { forward: true, linewise: true }}, + { keys: ['k'], type: 'motion', + motion: 'moveByLines', + motionArgs: { forward: false, linewise: true }}, + { keys: ['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: ['Ctrl-f'], type: 'motion', + motion: 'moveByPage', motionArgs: { forward: true }}, + { keys: ['Ctrl-b'], type: 'motion', + motion: 'moveByPage', motionArgs: { forward: false }}, + { keys: ['g', 'g'], type: 'motion', + motion: 'moveToLineOrEdgeOfDocument', + motionArgs: { forward: false, explicitRepeat: true, linewise: true }}, + { keys: ['G'], type: 'motion', + motion: 'moveToLineOrEdgeOfDocument', + motionArgs: { forward: true, explicitRepeat: true, linewise: true }}, + { keys: ['0'], type: 'motion', motion: 'moveToStartOfLine' }, + { keys: ['^'], type: 'motion', + motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: ['$'], type: 'motion', + motion: 'moveToEol', + motionArgs: { inclusive: true }}, + { keys: ['%'], type: 'motion', + motion: 'moveToMatchedSymbol', + motionArgs: { inclusive: true }}, + { keys: ['f', 'character'], type: 'motion', + motion: 'moveToCharacter', + motionArgs: { forward: true , inclusive: true }}, + { keys: ['F', 'character'], type: 'motion', + motion: 'moveToCharacter', + motionArgs: { forward: false }}, + { keys: ['t', 'character'], type: 'motion', + motion: 'moveTillCharacter', + motionArgs: { forward: true, inclusive: true }}, + { keys: ['T', 'character'], type: 'motion', + motion: 'moveTillCharacter', + motionArgs: { forward: false }}, + { keys: ['\'', 'character'], type: 'motion', motion: 'goToMark' }, + { keys: ['`', 'character'], type: 'motion', motion: 'goToMark' }, + { keys: ['|'], type: 'motion', + motion: 'moveToColumn', + motionArgs: { }}, + // Operators + { keys: ['d'], type: 'operator', operator: 'delete' }, + { keys: ['y'], type: 'operator', operator: 'yank' }, + { keys: ['c'], type: 'operator', operator: 'change', + operatorArgs: { enterInsertMode: true } }, + { keys: ['>'], type: 'operator', operator: 'indent', + operatorArgs: { indentRight: true }}, + { keys: ['<'], type: 'operator', operator: 'indent', + operatorArgs: { indentRight: false }}, + { keys: ['g', '~'], type: 'operator', operator: 'swapcase' }, + { keys: ['n'], type: 'motion', motion: 'findNext' }, + { keys: ['N'], type: 'motion', motion: 'findPrev' }, + // Operator-Motion dual commands + { keys: ['x'], type: 'operatorMotion', operator: 'delete', + motion: 'moveByCharacters', motionArgs: { forward: true }, + operatorMotionArgs: { visualLine: false }}, + { keys: ['X'], type: 'operatorMotion', operator: 'delete', + motion: 'moveByCharacters', motionArgs: { forward: false }, + operatorMotionArgs: { visualLine: true }}, + { keys: ['D'], type: 'operatorMotion', operator: 'delete', + motion: 'moveToEol', motionArgs: { inclusive: true }, + operatorMotionArgs: { visualLine: true }}, + { keys: ['Y'], type: 'operatorMotion', operator: 'yank', + motion: 'moveToEol', motionArgs: { inclusive: true }, + operatorMotionArgs: { visualLine: true }}, + { keys: ['C'], type: 'operatorMotion', + operator: 'change', operatorArgs: { enterInsertMode: true }, + motion: 'moveToEol', motionArgs: { inclusive: true }, + operatorMotionArgs: { visualLine: true }}, + { keys: ['~'], type: 'operatorMotion', operator: 'swapcase', + motion: 'moveByCharacters', motionArgs: { forward: true }}, + // Actions + { keys: ['a'], type: 'action', action: 'enterInsertMode', + actionArgs: { insertAt: 'charAfter' }}, + { keys: ['A'], type: 'action', action: 'enterInsertMode', + actionArgs: { insertAt: 'eol' }}, + { keys: ['i'], type: 'action', action: 'enterInsertMode' }, + { keys: ['I'], type: 'action', action: 'enterInsertMode', + motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: ['o'], type: 'action', action: 'newLineAndEnterInsertMode', + actionArgs: { after: true }}, + { keys: ['O'], type: 'action', action: 'newLineAndEnterInsertMode', + actionArgs: { after: false }}, + { keys: ['v'], type: 'action', action: 'toggleVisualMode' }, + { keys: ['V'], type: 'action', action: 'toggleVisualMode', + actionArgs: { linewise: true }}, + { keys: ['J'], type: 'action', action: 'joinLines' }, + { keys: ['p'], type: 'action', action: 'paste', + actionArgs: { after: true }}, + { keys: ['P'], type: 'action', action: 'paste', + actionArgs: { after: false }}, + { keys: ['r', 'character'], type: 'action', action: 'replace' }, + { keys: ['u'], type: 'action', action: 'undo' }, + { keys: ['Ctrl-r'], type: 'action', action: 'redo' }, + { keys: ['m', 'character'], type: 'action', action: 'setMark' }, + { keys: ['\"', 'character'], type: 'action', action: 'setRegister' }, + { keys: [',', '/'], type: 'action', action: 'clearSearchHighlight' }, + // Text object motions + { keys: ['a', 'character'], type: 'motion', + motion: 'textObjectManipulation' }, + { keys: ['i', 'character'], type: 'motion', + motion: 'textObjectManipulation', + motionArgs: { textObjectInner: true }}, + // Search + { keys: ['/'], type: 'search', + searchArgs: { forward: true, querySrc: 'prompt' }}, + { keys: ['?'], type: 'search', + searchArgs: { forward: false, querySrc: 'prompt' }}, + { keys: ['*'], type: 'search', + searchArgs: { forward: true, querySrc: 'wordUnderCursor' }}, + { keys: ['#'], type: 'search', + searchArgs: { forward: false, querySrc: 'wordUnderCursor' }}, + // Ex command + { keys: [':'], type: 'ex' } + ]; + + var Vim = function() { + var alphabetRegex = /[A-Za-z]/; + var numberRegex = /[\d]/; + var whiteSpaceRegex = /\s/; + var wordRegexp = [(/\w/), (/[^\w\s]/)], bigWordRegexp = [(/\S/)]; + function makeKeyRange(start, size) { + var keys = []; + for (var i = start; i < start + size; i++) { + keys.push(String.fromCharCode(i)); + } + return keys; + } + var upperCaseAlphabet = makeKeyRange(65, 26); + var lowerCaseAlphabet = makeKeyRange(97, 26); + var numbers = makeKeyRange(48, 10); + var SPECIAL_SYMBOLS = '~`!@#$%^&*()_-+=[{}]\\|/?.,<>:;\"\''; + var specialSymbols = SPECIAL_SYMBOLS.split(''); + var specialKeys = ['Left', 'Right', 'Up', 'Down', 'Space', 'Backspace', + 'Esc', 'Home', 'End', 'PageUp', 'PageDown']; + var validMarks = upperCaseAlphabet.concat(lowerCaseAlphabet).concat( + numbers).concat(['<', '>']); + var validRegisters = upperCaseAlphabet.concat(lowerCaseAlphabet).concat( + numbers).concat('-\"'.split('')); + + function isAlphabet(k) { + return alphabetRegex.test(k); + } + function isLine(cm, line) { + return line >= 0 && line < cm.lineCount(); + } + function isLowerCase(k) { + return (/^[a-z]$/).test(k); + } + function isMatchableSymbol(k) { + return '()[]{}'.indexOf(k) != -1; + } + function isNumber(k) { + return numberRegex.test(k); + } + function isUpperCase(k) { + return (/^[A-Z]$/).test(k); + } + function isAlphanumeric(k) { + return (/^[\w]$/).test(k); + } + function isWhiteSpace(k) { + return whiteSpaceRegex.test(k); + } + function isWhiteSpaceString(k) { + return (/^\s*$/).test(k); + } + function inRangeInclusive(x, start, end) { + return x >= start && x <= end; + } + function inArray(val, arr) { + for (var i = 0; i < arr.length; i++) { + if (arr[i] == val) { + return true; + } + } + return false; + } + + // Global Vim state. Call getVimGlobalState to get and initialize. + var vimGlobalState; + function getVimGlobalState() { + if (!vimGlobalState) { + vimGlobalState = { + // The current search query. + searchQuery: null, + // Whether we are searching backwards. + searchIsReversed: false, + registerController: new RegisterController({}) + }; + } + return vimGlobalState; + } + function getVimState(cm) { + if (!cm.vimState) { + // Store instance state in the CodeMirror object. + cm.vimState = { + inputState: new InputState(), + // When using jk for navigation, if you move from a longer line to a + // shorter line, the cursor may clip to the end of the shorter line. + // If j is pressed again and cursor goes to the next line, the + // cursor should go back to its horizontal position on the longer + // line if it can. This is to keep track of the horizontal position. + lastHPos: -1, + // The last motion command run. Cleared if a non-motion command gets + // executed in between. + lastMotion: null, + marks: {}, + visualMode: false, + // If we are in visual line mode. No effect if visualMode is false. + visualLine: false + }; + } + return cm.vimState; + } + + var vimApi= { + buildKeyMap: function() { + // TODO: Convert keymap into dictionary format for fast lookup. + }, + // Testing hook, though it might be useful to expose the register + // controller anyways. + getRegisterController: function() { + return getVimGlobalState().registerController; + }, + // Testing hook. + clearVimGlobalState_: function() { + vimGlobalState = null; + }, + map: function(lhs, rhs) { + // Add user defined key bindings. + exCommandDispatcher.map(lhs, rhs); + }, + // Initializes vim state variable on the CodeMirror object. Should only be + // called lazily by handleKey or for testing. + maybeInitState: function(cm) { + getVimState(cm); + }, + // This is the outermost function called by CodeMirror, after keys have + // been mapped to their Vim equivalents. + handleKey: function(cm, key) { + var command; + var vim = getVimState(cm); + if (key == 'Esc') { + // Clear input state and get back to normal mode. + vim.inputState.reset(); + if (vim.visualMode) { + exitVisualMode(cm, vim); + } + return; + } + if (vim.visualMode && + cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) { + // The selection was cleared. Exit visual mode. + exitVisualMode(cm, vim); + } + if (!vim.visualMode && + !cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) { + vim.visualMode = true; + vim.visualLine = false; + } + if (key != '0' || (key == '0' && vim.inputState.getRepeat() === 0)) { + // Have to special case 0 since it's both a motion and a number. + command = commandDispatcher.matchCommand(key, defaultKeymap, vim); + } + if (!command) { + if (isNumber(key)) { + // Increment count unless count is 0 and key is 0. + vim.inputState.pushRepeatDigit(key); + } + return; + } + if (command.type == 'keyToKey') { + // TODO: prevent infinite recursion. + for (var i = 0; i < command.toKeys.length; i++) { + this.handleKey(cm, command.toKeys[i]); + } + } else { + commandDispatcher.processCommand(cm, vim, command); + } + } + }; + + // Represents the current input state. + function InputState() { + this.reset(); + } + InputState.prototype.reset = function() { + this.prefixRepeat = []; + this.motionRepeat = []; + + this.operator = null; + this.operatorArgs = null; + this.motion = null; + this.motionArgs = null; + this.keyBuffer = []; // For matching multi-key commands. + this.registerName = null; // Defaults to the unamed register. + }; + InputState.prototype.pushRepeatDigit = function(n) { + if (!this.operator) { + this.prefixRepeat = this.prefixRepeat.concat(n); + } else { + this.motionRepeat = this.motionRepeat.concat(n); + } + }; + InputState.prototype.getRepeat = function() { + var repeat = 0; + if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) { + repeat = 1; + if (this.prefixRepeat.length > 0) { + repeat *= parseInt(this.prefixRepeat.join(''), 10); + } + if (this.motionRepeat.length > 0) { + repeat *= parseInt(this.motionRepeat.join(''), 10); + } + } + return repeat; + }; + + /* + * Register stores information about copy and paste registers. Besides + * text, a register must store whether it is linewise (i.e., when it is + * pasted, should it insert itself into a new line, or should the text be + * inserted at the cursor position.) + */ + function Register(text, linewise) { + this.clear(); + if (text) { + this.set(text, linewise); + } + } + Register.prototype = { + set: function(text, linewise) { + this.text = text; + this.linewise = !!linewise; + }, + append: function(text, linewise) { + // if this register has ever been set to linewise, use linewise. + if (linewise || this.linewise) { + this.text += '\n' + text; + this.linewise = true; + } else { + this.text += text; + } + }, + clear: function() { + this.text = ''; + this.linewise = false; + }, + toString: function() { return this.text; } + }; + + /* + * vim registers allow you to keep many independent copy and paste buffers. + * See http://usevim.com/2012/04/13/registers/ for an introduction. + * + * RegisterController keeps the state of all the registers. An initial + * state may be passed in. The unnamed register '"' will always be + * overridden. + */ + function RegisterController(registers) { + this.registers = registers; + this.unamedRegister = registers['\"'] = new Register(); + } + RegisterController.prototype = { + pushText: function(registerName, operator, text, linewise) { + // Lowercase and uppercase registers refer to the same register. + // Uppercase just means append. + var register = this.isValidRegister(registerName) ? + this.getRegister(registerName) : null; + // if no register/an invalid register was specified, things go to the + // default registers + if (!register) { + switch (operator) { + case 'yank': + // The 0 register contains the text from the most recent yank. + this.registers['0'] = new Register(text, linewise); + break; + case 'delete': + case 'change': + if (text.indexOf('\n') == -1) { + // Delete less than 1 line. Update the small delete register. + this.registers['-'] = new Register(text, linewise); + } else { + // Shift down the contents of the numbered registers and put the + // deleted text into register 1. + this.shiftNumericRegisters_(); + this.registers['1'] = new Register(text, linewise); + } + break; + } + // Make sure the unnamed register is set to what just happened + this.unamedRegister.set(text, linewise); + return; + } + + // If we've gotten to this point, we've actually specified a register + var append = isUpperCase(registerName); + if (append) { + register.append(text, linewise); + // The unamed register always has the same value as the last used + // register. + this.unamedRegister.append(text, linewise); + } else { + register.set(text, linewise); + this.unamedRegister.set(text, linewise); + } + }, + // Gets the register named @name. If one of @name doesn't already exist, + // create it. If @name is invalid, return the unamedRegister. + getRegister: function(name) { + if (!this.isValidRegister(name)) { + return this.unamedRegister; + } + name = name.toLowerCase(); + if (!this.registers[name]) { + this.registers[name] = new Register(); + } + return this.registers[name]; + }, + isValidRegister: function(name) { + return name && inArray(name, validRegisters); + }, + shiftNumericRegisters_: function() { + for (var i = 9; i >= 2; i--) { + this.registers[i] = this.getRegister('' + (i - 1)); + } + } + }; + + var commandDispatcher = { + matchCommand: function(key, keyMap, vim) { + var inputState = vim.inputState; + var keys = inputState.keyBuffer.concat(key); + for (var i = 0; i < keyMap.length; i++) { + var command = keyMap[i]; + if (matchKeysPartial(keys, command.keys)) { + if (keys.length < command.keys.length) { + // Matches part of a multi-key command. Buffer and wait for next + // stroke. + inputState.keyBuffer.push(key); + return null; + } else { + if (inputState.operator && command.type == 'action') { + // Ignore matched action commands after an operator. Operators + // only operate on motions. This check is really for text + // objects since aW, a[ etcs conflicts with a. + continue; + } + // Matches whole comand. Return the command. + if (command.keys[keys.length - 1] == 'character') { + inputState.selectedCharacter = keys[keys.length - 1]; + } + inputState.keyBuffer = []; + return command; + } + } + } + // Clear the buffer since there are no partial matches. + inputState.keyBuffer = []; + return null; + }, + processCommand: function(cm, vim, command) { + switch (command.type) { + case 'motion': + this.processMotion(cm, vim, command); + break; + case 'operator': + this.processOperator(cm, vim, command); + break; + case 'operatorMotion': + this.processOperatorMotion(cm, vim, command); + break; + case 'action': + this.processAction(cm, vim, command); + break; + case 'search': + this.processSearch(cm, vim, command); + break; + case 'ex': + case 'keyToEx': + this.processEx(cm, vim, command); + break; + default: + break; + } + }, + processMotion: function(cm, vim, command) { + vim.inputState.motion = command.motion; + vim.inputState.motionArgs = copyArgs(command.motionArgs); + this.evalInput(cm, vim); + }, + processOperator: function(cm, vim, command) { + var inputState = vim.inputState; + if (inputState.operator) { + if (inputState.operator == command.operator) { + // Typing an operator twice like 'dd' makes the operator operate + // linewise + inputState.motion = 'expandToLine'; + inputState.motionArgs = { linewise: true }; + this.evalInput(cm, vim); + return; + } else { + // 2 different operators in a row doesn't make sense. + inputState.reset(); + } + } + inputState.operator = command.operator; + inputState.operatorArgs = copyArgs(command.operatorArgs); + if (vim.visualMode) { + // Operating on a selection in visual mode. We don't need a motion. + this.evalInput(cm, vim); + } + }, + processOperatorMotion: function(cm, vim, command) { + var visualMode = vim.visualMode; + var operatorMotionArgs = copyArgs(command.operatorMotionArgs); + if (operatorMotionArgs) { + // Operator motions may have special behavior in visual mode. + if (visualMode && operatorMotionArgs.visualLine) { + vim.visualLine = true; + } + } + this.processOperator(cm, vim, command); + if (!visualMode) { + this.processMotion(cm, vim, command); + } + }, + processAction: function(cm, vim, command) { + var inputState = vim.inputState; + var repeat = inputState.getRepeat(); + var repeatIsExplicit = !!repeat; + var actionArgs = copyArgs(command.actionArgs) || {}; + if (inputState.selectedCharacter) { + actionArgs.selectedCharacter = inputState.selectedCharacter; + } + // Actions may or may not have motions and operators. Do these first. + if (command.operator) { + this.processOperator(cm, vim, command); + } + if (command.motion) { + this.processMotion(cm, vim, command); + } + if (command.motion || command.operator) { + this.evalInput(cm, vim); + } + actionArgs.repeat = repeat || 1; + actionArgs.repeatIsExplicit = repeatIsExplicit; + actionArgs.registerName = inputState.registerName; + inputState.reset(); + vim.lastMotion = null, + actions[command.action](cm, actionArgs, vim); + }, + processSearch: function(cm, vim, command) { + if (!cm.getSearchCursor) { + // Search depends on SearchCursor. + return; + } + var forward = command.searchArgs.forward; + getSearchState(cm).setReversed(!forward); + var promptPrefix = (forward) ? '/' : '?'; + function handleQuery(query, ignoreCase, smartCase) { + updateSearchQuery(cm, query, ignoreCase, smartCase); + commandDispatcher.processMotion(cm, vim, { + type: 'motion', + motion: 'findNext' + }); + } + function onPromptClose(query) { + handleQuery(query, true /** ignoreCase */, true /** smartCase */); + } + switch (command.searchArgs.querySrc) { + case 'prompt': + showPrompt(cm, onPromptClose, promptPrefix, searchPromptDesc); + break; + case 'wordUnderCursor': + var word = expandWordUnderCursor(cm, false /** inclusive */, + true /** forward */, false /** bigWord */, + true /** noSymbol */); + var isKeyword = true; + if (!word) { + word = expandWordUnderCursor(cm, false /** inclusive */, + true /** forward */, false /** bigWord */, + false /** noSymbol */); + isKeyword = false; + } + if (!word) { + return; + } + var query = cm.getLine(word.start.line).substring(word.start.ch, + word.end.ch + 1); + if (isKeyword) { + query = '\\b' + query + '\\b'; + } else { + query = escapeRegex(query); + } + cm.setCursor(word.start); + handleQuery(query, true /** ignoreCase */, false /** smartCase */); + break; + } + }, + processEx: function(cm, vim, command) { + function onPromptClose(input) { + exCommandDispatcher.processCommand(cm, input); + } + if (command.type == 'keyToEx') { + // Handle user defined Ex to Ex mappings + exCommandDispatcher.processCommand(cm, command.exArgs.input); + } else { + if (vim.visualMode) { + showPrompt(cm, onPromptClose, ':', undefined, '\'<,\'>'); + } else { + showPrompt(cm, onPromptClose, ':'); + } + } + }, + evalInput: function(cm, vim) { + // If the motion comand is set, execute both the operator and motion. + // Otherwise return. + var inputState = vim.inputState; + var motion = inputState.motion; + var motionArgs = inputState.motionArgs || {}; + var operator = inputState.operator; + var operatorArgs = inputState.operatorArgs || {}; + var registerName = inputState.registerName; + var selectionEnd = cm.getCursor('head'); + var selectionStart = cm.getCursor('anchor'); + // The difference between cur and selection cursors are that cur is + // being operated on and ignores that there is a selection. + var curStart = copyCursor(selectionEnd); + var curOriginal = copyCursor(curStart); + var curEnd; + var repeat; + if (motionArgs.repeat !== undefined) { + // If motionArgs specifies a repeat, that takes precedence over the + // input state's repeat. Used by Ex mode and can be user defined. + repeat = inputState.motionArgs.repeat; + } else { + repeat = inputState.getRepeat(); + } + if (repeat > 0 && motionArgs.explicitRepeat) { + motionArgs.repeatIsExplicit = true; + } else if (motionArgs.noRepeat || + (!motionArgs.explicitRepeat && repeat === 0)) { + repeat = 1; + motionArgs.repeatIsExplicit = false; + } + if (inputState.selectedCharacter) { + // If there is a character input, stick it in all of the arg arrays. + motionArgs.selectedCharacter = operatorArgs.selectedCharacter = + inputState.selectedCharacter; + } + motionArgs.repeat = repeat; + inputState.reset(); + if (motion) { + var motionResult = motions[motion](cm, motionArgs, vim); + vim.lastMotion = motions[motion]; + if (!motionResult) { + return; + } + if (motionResult instanceof Array) { + curStart = motionResult[0]; + curEnd = motionResult[1]; + } else { + curEnd = motionResult; + } + // TODO: Handle null returns from motion commands better. + if (!curEnd) { + curEnd = { ch: curStart.ch, line: curStart.line }; + } + if (vim.visualMode) { + // Check if the selection crossed over itself. Will need to shift + // the start point if that happened. + if (cursorIsBefore(selectionStart, selectionEnd) && + (cursorEqual(selectionStart, curEnd) || + cursorIsBefore(curEnd, selectionStart))) { + // The end of the selection has moved from after the start to + // before the start. We will shift the start right by 1. + selectionStart.ch += 1; + } else if (cursorIsBefore(selectionEnd, selectionStart) && + (cursorEqual(selectionStart, curEnd) || + cursorIsBefore(selectionStart, curEnd))) { + // The opposite happened. We will shift the start left by 1. + selectionStart.ch -= 1; + } + selectionEnd = curEnd; + if (vim.visualLine) { + if (cursorIsBefore(selectionStart, selectionEnd)) { + selectionStart.ch = 0; + selectionEnd.ch = lineLength(cm, selectionEnd.line); + } else { + selectionEnd.ch = 0; + selectionStart.ch = lineLength(cm, selectionStart.line); + } + } + // Need to set the cursor to clear the selection. Otherwise, + // CodeMirror can't figure out that we changed directions... + cm.setCursor(selectionStart); + cm.setSelection(selectionStart, selectionEnd); + updateMark(cm, vim, '<', + cursorIsBefore(selectionStart, selectionEnd) ? selectionStart + : selectionEnd); + updateMark(cm, vim, '>', + cursorIsBefore(selectionStart, selectionEnd) ? selectionEnd + : selectionStart); + } else if (!operator) { + curEnd = clipCursorToContent(cm, curEnd); + cm.setCursor(curEnd.line, curEnd.ch); + } + } + + if (operator) { + var inverted = false; + vim.lastMotion = null; + operatorArgs.repeat = repeat; // Indent in visual mode needs this. + if (vim.visualMode) { + curStart = selectionStart; + curEnd = selectionEnd; + motionArgs.inclusive = true; + } + // Swap start and end if motion was backward. + if (cursorIsBefore(curEnd, curStart)) { + var tmp = curStart; + curStart = curEnd; + curEnd = tmp; + inverted = true; + } + if (motionArgs.inclusive && !(vim.visualMode && inverted)) { + // Move the selection end one to the right to include the last + // character. + curEnd.ch++; + } + var linewise = motionArgs.linewise || + (vim.visualMode && vim.visualLine); + if (linewise) { + // Expand selection to entire line. + expandSelectionToLine(cm, curStart, curEnd); + } else if (motionArgs.forward) { + // Clip to trailing newlines only if we the motion goes forward. + clipToLine(cm, curStart, curEnd); + } + operatorArgs.registerName = registerName; + // Keep track of linewise as it affects how paste and change behave. + operatorArgs.linewise = linewise; + operators[operator](cm, operatorArgs, vim, curStart, + curEnd, curOriginal); + if (vim.visualMode) { + exitVisualMode(cm, vim); + } + if (operatorArgs.enterInsertMode) { + actions.enterInsertMode(cm); + } + } + } + }; + + /** + * typedef {Object{line:number,ch:number}} Cursor An object containing the + * position of the cursor. + */ + // All of the functions below return Cursor objects. + var motions = { + expandToLine: function(cm, motionArgs) { + // Expands forward to end of line, and then to next line if repeat is + // >1. Does not handle backward motion! + var cur = cm.getCursor(); + return { line: cur.line + motionArgs.repeat - 1, ch: Infinity }; + }, + findNext: function(cm, motionArgs, vim) { + return findNext(cm, false /** prev */, motionArgs.repeat); + }, + findPrev: function(cm, motionArgs, vim) { + return findNext(cm, true /** prev */, motionArgs.repeat); + }, + goToMark: function(cm, motionArgs, vim) { + var mark = vim.marks[motionArgs.selectedCharacter]; + if (mark) { + return mark.find(); + } + return null; + }, + moveByCharacters: function(cm, motionArgs) { + var cur = cm.getCursor(); + var repeat = motionArgs.repeat; + var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat; + return { line: cur.line, ch: ch }; + }, + moveByLines: function(cm, motionArgs, vim) { + var endCh = cm.getCursor().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.moveToColumn: + case this.moveToEol: + endCh = vim.lastHPos; + break; + default: + vim.lastHPos = endCh; + } + var cur = cm.getCursor(); + var repeat = motionArgs.repeat; + var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat; + if (line < 0 || line > cm.lineCount() - 1) { + return null; + } + return { line: line, ch: endCh }; + }, + 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; + }, + moveByWords: function(cm, motionArgs) { + return moveToWord(cm, motionArgs.repeat, !!motionArgs.forward, + !!motionArgs.wordEnd, !!motionArgs.bigWord); + }, + moveTillCharacter: function(cm, motionArgs) { + var repeat = motionArgs.repeat; + var curEnd = moveToCharacter(cm, repeat, motionArgs.forward, + motionArgs.selectedCharacter); + var increment = motionArgs.forward ? -1 : 1; + curEnd.ch += increment; + return curEnd; + }, + moveToCharacter: function(cm, motionArgs) { + var repeat = motionArgs.repeat; + return moveToCharacter(cm, repeat, motionArgs.forward, + motionArgs.selectedCharacter); + }, + moveToColumn: function(cm, motionArgs, vim) { + var repeat = motionArgs.repeat; + // repeat is equivalent to which column we want to move to! + vim.lastHPos = repeat - 1; + return moveToColumn(cm, repeat); + }, + moveToEol: function(cm, motionArgs, vim) { + var cur = cm.getCursor(); + vim.lastHPos = Infinity; + return { line: cur.line + motionArgs.repeat - 1, ch: Infinity }; + }, + moveToFirstNonWhiteSpaceCharacter: function(cm) { + // Go to the start of the line where the text begins, or the end for + // whitespace-only lines + var cursor = cm.getCursor(); + var line = cm.getLine(cursor.line); + return { line: cursor.line, + ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)) }; + }, + moveToMatchedSymbol: function(cm, motionArgs) { + var cursor = cm.getCursor(); + var symbol = cm.getLine(cursor.line).charAt(cursor.ch); + if (isMatchableSymbol(symbol)) { + return findMatchedSymbol(cm, cm.getCursor(), motionArgs.symbol); + } else { + return cursor; + } + }, + moveToStartOfLine: function(cm) { + var cursor = cm.getCursor(); + return { line: cursor.line, ch: 0 }; + }, + moveToLineOrEdgeOfDocument: function(cm, motionArgs) { + var lineNum = motionArgs.forward ? cm.lineCount() - 1 : 0; + if (motionArgs.repeatIsExplicit) { + lineNum = motionArgs.repeat - 1; + } + return { line: lineNum, + ch: findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)) }; + }, + textObjectManipulation: function(cm, motionArgs) { + var character = motionArgs.selectedCharacter; + // Inclusive is the difference between a and i + // TODO: Instead of using the additional text object map to perform text + // object operations, merge the map into the defaultKeyMap and use + // motionArgs to define behavior. Define separate entries for 'aw', + // 'iw', 'a[', 'i[', etc. + var inclusive = !motionArgs.textObjectInner; + if (!textObjects[character]) { + // No text object defined for this, don't move. + return null; + } + var tmp = textObjects[character](cm, inclusive); + var start = tmp.start; + var end = tmp.end; + return [start, end]; + } + }; + + var operators = { + change: function(cm, operatorArgs, vim, curStart, curEnd) { + getVimGlobalState().registerController.pushText( + operatorArgs.registerName, 'change', cm.getRange(curStart, curEnd), + operatorArgs.linewise); + if (operatorArgs.linewise) { + // Delete starting at the first nonwhitespace character of the first + // line, instead of from the start of the first line. This way we get + // an indent when we get into insert mode. This behavior isn't quite + // correct because we should treat this as a completely new line, and + // indent should be whatever codemirror thinks is the right indent. + // But cm.indentLine doesn't seem work on empty lines. + // TODO: Fix the above. + curStart.ch = + findFirstNonWhiteSpaceCharacter(cm.getLine(curStart.line)); + // Insert an additional newline so that insert mode can start there. + // curEnd should be on the first character of the new line. + cm.replaceRange('\n', curStart, curEnd); + } else { + cm.replaceRange('', curStart, curEnd); + } + cm.setCursor(curStart); + }, + // delete is a javascript keyword. + 'delete': function(cm, operatorArgs, vim, curStart, curEnd) { + getVimGlobalState().registerController.pushText( + operatorArgs.registerName, 'delete', cm.getRange(curStart, curEnd), + operatorArgs.linewise); + cm.replaceRange('', curStart, curEnd); + if (operatorArgs.linewise) { + cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm)); + } else { + cm.setCursor(curStart); + } + }, + indent: function(cm, operatorArgs, vim, curStart, curEnd) { + var startLine = curStart.line; + var endLine = curEnd.line; + // In visual mode, n> shifts the selection right n times, instead of + // shifting n lines right once. + var repeat = (vim.visualMode) ? operatorArgs.repeat : 1; + if (operatorArgs.linewise) { + // The only way to delete a newline is to delete until the start of + // the next line, so in linewise mode evalInput will include the next + // line. We don't want this in indent, so we go back a line. + endLine--; + } + for (var i = startLine; i <= endLine; i++) { + for (var j = 0; j < repeat; j++) { + cm.indentLine(i, operatorArgs.indentRight); + } + } + cm.setCursor(curStart); + cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm)); + }, + swapcase: function(cm, operatorArgs, vim, curStart, curEnd, curOriginal) { + var toSwap = cm.getRange(curStart, curEnd); + var swapped = ''; + for (var i = 0; i < toSwap.length; i++) { + var character = toSwap.charAt(i); + swapped += isUpperCase(character) ? character.toLowerCase() : + character.toUpperCase(); + } + cm.replaceRange(swapped, curStart, curEnd); + cm.setCursor(curOriginal); + }, + yank: function(cm, operatorArgs, vim, curStart, curEnd, curOriginal) { + getVimGlobalState().registerController.pushText( + operatorArgs.registerName, 'yank', + cm.getRange(curStart, curEnd), operatorArgs.linewise); + cm.setCursor(curOriginal); + } + }; + + var actions = { + clearSearchHighlight: clearSearchHighlight, + enterInsertMode: function(cm, actionArgs) { + var insertAt = (actionArgs) ? actionArgs.insertAt : null; + if (insertAt == 'eol') { + var cursor = cm.getCursor(); + cursor = { line: cursor.line, ch: lineLength(cm, cursor.line) }; + cm.setCursor(cursor); + } else if (insertAt == 'charAfter') { + cm.setCursor(offsetCursor(cm.getCursor(), 0, 1)); + } + cm.setOption('keyMap', 'vim-insert'); + }, + toggleVisualMode: function(cm, actionArgs, vim) { + var repeat = actionArgs.repeat; + var curStart = cm.getCursor(); + var curEnd; + // TODO: The repeat should actually select number of characters/lines + // equal to the repeat times the size of the previous visual + // operation. + if (!vim.visualMode) { + vim.visualMode = true; + vim.visualLine = !!actionArgs.linewise; + if (vim.visualLine) { + curStart.ch = 0; + curEnd = clipCursorToContent(cm, { + line: curStart.line + repeat - 1, + ch: lineLength(cm, curStart.line) + }, true /** includeLineBreak */); + } else { + curEnd = clipCursorToContent(cm, { + line: curStart.line, + ch: curStart.ch + repeat + }, true /** includeLineBreak */); + } + // Make the initial selection. + if (!actionArgs.repeatIsExplicit && !vim.visualLine) { + // This is a strange case. Here the implicit repeat is 1. The + // following commands lets the cursor hover over the 1 character + // selection. + cm.setCursor(curEnd); + cm.setSelection(curEnd, curStart); + } else { + cm.setSelection(curStart, curEnd); + } + } else { + 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 = cm.getCursor('anchor'); + curEnd = cm.getCursor('head'); + curStart.ch = cursorIsBefore(curStart, curEnd) ? 0 : + lineLength(cm, curStart.line); + curEnd.ch = cursorIsBefore(curStart, curEnd) ? + lineLength(cm, curEnd.line) : 0; + cm.setSelection(curStart, curEnd); + } else { + exitVisualMode(cm, vim); + } + } + updateMark(cm, vim, '<', cursorIsBefore(curStart, curEnd) ? curStart + : curEnd); + updateMark(cm, vim, '>', cursorIsBefore(curStart, curEnd) ? curEnd + : curStart); + }, + joinLines: function(cm, actionArgs, vim) { + var curStart, curEnd; + if (vim.visualMode) { + curStart = cm.getCursor('anchor'); + curEnd = cm.getCursor('head'); + curEnd.ch = lineLength(cm, curEnd.line) - 1; + } else { + // Repeat is the number of lines to join. Minimum 2 lines. + var repeat = Math.max(actionArgs.repeat, 2); + curStart = cm.getCursor(); + curEnd = clipCursorToContent(cm, { line: curStart.line + repeat - 1, + ch: Infinity }); + } + var finalCh = 0; + cm.operation(function() { + for (var i = curStart.line; i < curEnd.line; i++) { + finalCh = lineLength(cm, curStart.line); + var tmp = { line: curStart.line + 1, + ch: lineLength(cm, curStart.line + 1) }; + var text = cm.getRange(curStart, tmp); + text = text.replace(/\n\s*/g, ' '); + cm.replaceRange(text, curStart, tmp); + } + var curFinalPos = { line: curStart.line, ch: finalCh }; + cm.setCursor(curFinalPos); + }); + }, + newLineAndEnterInsertMode: function(cm, actionArgs) { + var insertAt = cm.getCursor(); + if (insertAt.line === 0 && !actionArgs.after) { + // Special case for inserting newline before start of document. + cm.replaceRange('\n', { line: 0, ch: 0 }); + cm.setCursor(0, 0); + } else { + insertAt.line = (actionArgs.after) ? insertAt.line : + insertAt.line - 1; + insertAt.ch = lineLength(cm, insertAt.line); + cm.setCursor(insertAt); + var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment || + CodeMirror.commands.newlineAndIndent; + newlineFn(cm); + } + this.enterInsertMode(cm); + }, + paste: function(cm, actionArgs, vim) { + var cur = cm.getCursor(); + var register = getVimGlobalState().registerController.getRegister( + actionArgs.registerName); + if (!register.text) { + return; + } + for (var text = '', i = 0; i < actionArgs.repeat; i++) { + text += register.text; + } + var linewise = register.linewise; + if (linewise) { + if (actionArgs.after) { + // Move the newline at the end to the start instead, and paste just + // before the newline character of the line we are on right now. + text = '\n' + text.slice(0, text.length - 1); + cur.ch = lineLength(cm, cur.line); + } else { + cur.ch = 0; + } + } else { + cur.ch += actionArgs.after ? 1 : 0; + } + cm.replaceRange(text, cur); + // Now fine tune the cursor to where we want it. + var curPosFinal; + var idx; + if (linewise && actionArgs.after) { + curPosFinal = { line: cur.line + 1, + ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)) }; + } else if (linewise && !actionArgs.after) { + curPosFinal = { line: cur.line, + ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)) }; + } else if (!linewise && actionArgs.after) { + idx = cm.indexFromPos(cur); + curPosFinal = cm.posFromIndex(idx + text.length - 1); + } else { + idx = cm.indexFromPos(cur); + curPosFinal = cm.posFromIndex(idx + text.length); + } + cm.setCursor(curPosFinal); + }, + undo: function(cm, actionArgs) { + repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)(); + }, + redo: function(cm, actionArgs) { + repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)(); + }, + setRegister: function(cm, actionArgs, vim) { + vim.inputState.registerName = actionArgs.selectedCharacter; + }, + setMark: function(cm, actionArgs, vim) { + var markName = actionArgs.selectedCharacter; + updateMark(cm, vim, markName, cm.getCursor()); + }, + replace: function(cm, actionArgs) { + var replaceWith = actionArgs.selectedCharacter; + var curStart = cm.getCursor(); + var line = cm.getLine(curStart.line); + var replaceTo = curStart.ch + actionArgs.repeat; + if (replaceTo > line.length) { + return; + } + var curEnd = { line: curStart.line, ch: replaceTo }; + var replaceWithStr = ''; + for (var i = 0; i < curEnd.ch - curStart.ch; i++) { + replaceWithStr += replaceWith; + } + cm.replaceRange(replaceWithStr, curStart, curEnd); + cm.setCursor(offsetCursor(curEnd, 0, -1)); + } + }; + + var textObjects = { + // TODO: lots of possible exceptions that can be thrown here. Try da( + // outside of a () block. + // TODO: implement text objects for the reverse like }. Should just be + // an additional mapping after moving to the defaultKeyMap. + 'w': function(cm, inclusive) { + return expandWordUnderCursor(cm, inclusive, true /** forward */, + false /** bigWord */); + }, + 'W': function(cm, inclusive) { + return expandWordUnderCursor(cm, inclusive, + true /** forward */, true /** bigWord */); + }, + '{': function(cm, inclusive) { + return selectCompanionObject(cm, '}', inclusive); + }, + '(': function(cm, inclusive) { + return selectCompanionObject(cm, ')', inclusive); + }, + '[': function(cm, inclusive) { + return selectCompanionObject(cm, ']', inclusive); + }, + '\'': function(cm, inclusive) { + return findBeginningAndEnd(cm, "'", inclusive); + }, + '\"': function(cm, inclusive) { + return findBeginningAndEnd(cm, '"', inclusive); + } + }; + + /* + * Below are miscellaneous utility functions used by vim.js + */ + + /** + * Clips cursor to ensure that: + * 0 <= cur.ch < lineLength + * AND + * 0 <= cur.line < lineCount + * If includeLineBreak is true, then allow cur.ch == lineLength. + */ + function clipCursorToContent(cm, cur, includeLineBreak) { + var line = Math.min(Math.max(0, cur.line), cm.lineCount() - 1); + var maxCh = lineLength(cm, line) - 1; + maxCh = (includeLineBreak) ? maxCh + 1 : maxCh; + var ch = Math.min(Math.max(0, cur.ch), maxCh); + return { line: line, ch: ch }; + } + // Merge arguments in place, for overriding arguments. + function mergeArgs(to, from) { + for (var prop in from) { + if (from.hasOwnProperty(prop)) { + to[prop] = from[prop]; + } + } + } + function copyArgs(args) { + var ret = {}; + for (var prop in args) { + if (args.hasOwnProperty(prop)) { + ret[prop] = args[prop]; + } + } + return ret; + } + function offsetCursor(cur, offsetLine, offsetCh) { + return { line: cur.line + offsetLine, ch: cur.ch + offsetCh }; + } + function arrayEq(a1, a2) { + if (a1.length != a2.length) { + return false; + } + for (var i = 0; i < a1.length; i++) { + if (a1[i] != a2[i]) { + return false; + } + } + return true; + } + function matchKeysPartial(pressed, mapped) { + for (var i = 0; i < pressed.length; i++) { + // 'character' means any character. For mark, register commads, etc. + if (pressed[i] != mapped[i] && mapped[i] != 'character') { + return false; + } + } + return true; + } + function arrayIsSubsetFromBeginning(small, big) { + for (var i = 0; i < small.length; i++) { + if (small[i] != big[i]) { + return false; + } + } + return true; + } + function repeatFn(cm, fn, repeat) { + return function() { + for (var i = 0; i < repeat; i++) { + fn(cm); + } + }; + } + function copyCursor(cur) { + return { line: cur.line, ch: cur.ch }; + } + function cursorEqual(cur1, cur2) { + return cur1.ch == cur2.ch && cur1.line == cur2.line; + } + function cursorIsBefore(cur1, cur2) { + if (cur1.line < cur2.line) { + return true; + } else if (cur1.line == cur2.line && cur1.ch < cur2.ch) { + return true; + } + return false; + } + function lineLength(cm, lineNum) { + return cm.getLine(lineNum).length; + } + function reverse(s){ + return s.split("").reverse().join(""); + } + function trim(s) { + if (s.trim) { + return s.trim(); + } else { + return s.replace(/^\s+|\s+$/g, ''); + } + } + function escapeRegex(s) { + return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, "\\$1"); + } + + function exitVisualMode(cm, vim) { + vim.visualMode = false; + vim.visualLine = false; + var selectionStart = cm.getCursor('anchor'); + var selectionEnd = cm.getCursor('head'); + if (!cursorEqual(selectionStart, selectionEnd)) { + // Clear the selection and set the cursor only if the selection has not + // already been cleared. Otherwise we risk moving the cursor somewhere + // it's not supposed to be. + cm.setCursor(clipCursorToContent(cm, selectionEnd)); + } + } + + // Remove any trailing newlines from the selection. For + // example, with the caret at the start of the last word on the line, + // 'dw' should word, but not the newline, while 'w' should advance the + // caret to the first character of the next line. + function clipToLine(cm, curStart, curEnd) { + var selection = cm.getRange(curStart, curEnd); + var lines = selection.split('\n'); + if (lines.length > 1 && isWhiteSpaceString(lines.pop())) { + curEnd.line--; + curEnd.ch = lineLength(cm, curEnd.line); + } + } + + // Expand the selection to line ends. + function expandSelectionToLine(cm, curStart, curEnd) { + curStart.ch = 0; + curEnd.ch = 0; + curEnd.line++; + } + + function findFirstNonWhiteSpaceCharacter(text) { + if (!text) { + return 0; + } + var firstNonWS = text.search(/\S/); + return firstNonWS == -1 ? text.length : firstNonWS; + } + + function expandWordUnderCursor(cm, inclusive, forward, bigWord, noSymbol) { + var cur = cm.getCursor(); + var line = cm.getLine(cur.line); + var idx = cur.ch; + + // Seek to first word or non-whitespace character, depending on if + // noSymbol is true. + var textAfterIdx = line.substring(idx); + var firstMatchedChar; + if (noSymbol) { + firstMatchedChar = textAfterIdx.search(/\w/); + } else { + firstMatchedChar = textAfterIdx.search(/\S/); + } + if (firstMatchedChar == -1) { + return null; + } + idx += firstMatchedChar; + textAfterIdx = line.substring(idx); + var textBeforeIdx = line.substring(0, idx); + + var matchRegex; + // Greedy matchers for the "word" we are trying to expand. + if (bigWord) { + matchRegex = /^\S+/; + } else { + if ((/\w/).test(line.charAt(idx))) { + matchRegex = /^\w+/; + } else { + matchRegex = /^[^\w\s]+/; + } + } + + var wordAfterRegex = matchRegex.exec(textAfterIdx); + var wordStart = idx; + var wordEnd = idx + wordAfterRegex[0].length - 1; + // TODO: Find a better way to do this. It will be slow on very long lines. + var wordBeforeRegex = matchRegex.exec(reverse(textBeforeIdx)); + if (wordBeforeRegex) { + wordStart -= wordBeforeRegex[0].length; + } + + if (inclusive) { + wordEnd++; + } + + return { start: { line: cur.line, ch: wordStart }, + end: { line: cur.line, ch: wordEnd }}; + } + + /* + * Returns the boundaries of the next word. If the cursor in the middle of + * the word, then returns the boundaries of the current word, starting at + * the cursor. If the cursor is at the start/end of a word, and we are going + * forward/backward, respectively, find the boundaries of the next word. + * + * @param {CodeMirror} cm CodeMirror object. + * @param {Cursor} cur The cursor position. + * @param {boolean} forward True to search forward. False to search + * backward. + * @param {boolean} bigWord True if punctuation count as part of the word. + * False if only [a-zA-Z0-9] characters count as part of the word. + * @return {Object{from:number, to:number, line: number}} The boundaries of + * the word, or null if there are no more words. + */ + // TODO: Treat empty lines (with no whitespace) as words. + function findWord(cm, cur, forward, bigWord) { + var lineNum = cur.line; + var pos = cur.ch; + var line = cm.getLine(lineNum); + var dir = forward ? 1 : -1; + var regexps = bigWord ? bigWordRegexp : wordRegexp; + + while (true) { + var stop = (dir > 0) ? line.length : -1; + var wordStart = stop, wordEnd = stop; + // Find bounds of next word. + while (pos != stop) { + var foundWord = false; + for (var i = 0; i < regexps.length && !foundWord; ++i) { + if (regexps[i].test(line.charAt(pos))) { + wordStart = pos; + // Advance to end of word. + while (pos != stop && regexps[i].test(line.charAt(pos))) { + pos += dir; + } + wordEnd = pos; + foundWord = wordStart != wordEnd; + if (wordStart == cur.ch && lineNum == cur.line && + wordEnd == wordStart + dir) { + // We started at the end of a word. Find the next one. + continue; + } else { + return { + from: Math.min(wordStart, wordEnd + 1), + to: Math.max(wordStart, wordEnd), + line: lineNum }; + } + } + } + if (!foundWord) { + pos += dir; + } + } + // Advance to next/prev line. + lineNum += dir; + if (!isLine(cm, lineNum)) { + return null; + } + line = cm.getLine(lineNum); + pos = (dir > 0) ? 0 : line.length; + } + // Should never get here. + throw 'The impossible happened.'; + } + + /** + * @param {CodeMirror} cm CodeMirror object. + * @param {int} repeat Number of words to move past. + * @param {boolean} forward True to search forward. False to search + * backward. + * @param {boolean} wordEnd True to move to end of word. False to move to + * beginning of word. + * @param {boolean} bigWord True if punctuation count as part of the word. + * False if only alphabet characters count as part of the word. + * @return {Cursor} The position the cursor should move to. + */ + function moveToWord(cm, repeat, forward, wordEnd, bigWord) { + var cur = cm.getCursor(); + for (var i = 0; i < repeat; i++) { + var startCh = cur.ch, startLine = cur.line, word; + var movedToNextWord = false; + while (!movedToNextWord) { + // Search and advance. + word = findWord(cm, cur, forward, bigWord); + movedToNextWord = true; + if (word) { + // Move to the word we just found. If by moving to the word we end + // up in the same spot, then move an extra character and search + // again. + cur.line = word.line; + if (forward && wordEnd) { + // 'e' + cur.ch = word.to - 1; + } else if (forward && !wordEnd) { + // 'w' + if (inRangeInclusive(cur.ch, word.from, word.to) && + word.line == startLine) { + // Still on the same word. Go to the next one. + movedToNextWord = false; + cur.ch = word.to - 1; + } else { + cur.ch = word.from; + } + } else if (!forward && wordEnd) { + // 'ge' + if (inRangeInclusive(cur.ch, word.from, word.to) && + word.line == startLine) { + // still on the same word. Go to the next one. + movedToNextWord = false; + cur.ch = word.from; + } else { + cur.ch = word.to; + } + } else if (!forward && !wordEnd) { + // 'b' + cur.ch = word.from; + } + } else { + // No more words to be found. Move to the end. + if (forward) { + return { line: cur.line, ch: lineLength(cm, cur.line) }; + } else { + return { line: cur.line, ch: 0 }; + } + } + } + } + return cur; + } + + function moveToCharacter(cm, repeat, forward, character) { + var cur = cm.getCursor(); + var start = cur.ch; + var idx; + for (var i = 0; i < repeat; i ++) { + var line = cm.getLine(cur.line); + idx = charIdxInLine(start, line, character, forward, true); + if (idx == -1) { + return cur; + } + start = idx; + } + return { line: cm.getCursor().line, ch: idx }; + } + + function moveToColumn(cm, repeat) { + // repeat is always >= 1, so repeat - 1 always corresponds + // to the column we want to go to. + var line = cm.getCursor().line; + return clipCursorToContent(cm, { line: line, ch: repeat - 1 }); + } + + function updateMark(cm, vim, markName, pos) { + if (!inArray(markName, validMarks)) { + return; + } + if (vim.marks[markName]) { + vim.marks[markName].clear(); + } + vim.marks[markName] = cm.setBookmark(pos); + } + + function charIdxInLine(start, line, character, forward, includeChar) { + // Search for char in line. + // motion_options: {forward, includeChar} + // If includeChar = true, include it too. + // If forward = true, search forward, else search backwards. + // If char is not found on this line, do nothing + var idx; + if (forward) { + idx = line.indexOf(character, start + 1); + if (idx != -1 && !includeChar) { + idx -= 1; + } + } else { + idx = line.lastIndexOf(character, start - 1); + if (idx != -1 && !includeChar) { + idx += 1; + } + } + return idx; + } + + function findMatchedSymbol(cm, cur, symb) { + var line = cur.line; + symb = symb ? symb : cm.getLine(line).charAt(cur.ch); + + // Are we at the opening or closing char + var forwards = inArray(symb, ['(', '[', '{']); + + var reverseSymb = ({ + '(': ')', ')': '(', + '[': ']', ']': '[', + '{': '}', '}': '{'})[symb]; + + // Couldn't find a matching symbol, abort + if (!reverseSymb) { + return cur; + } + + // set our increment to move forward (+1) or backwards (-1) + // depending on which bracket we're matching + var increment = ({'(': 1, '{': 1, '[': 1})[symb] || -1; + var depth = 1, nextCh = symb, index = cur.ch, lineText = cm.getLine(line); + // Simple search for closing paren--just count openings and closings till + // we find our match + // TODO: use info from CodeMirror to ignore closing brackets in comments + // and quotes, etc. + while (nextCh && depth > 0) { + index += increment; + nextCh = lineText.charAt(index); + if (!nextCh) { + line += increment; + index = 0; + lineText = cm.getLine(line) || ''; + nextCh = lineText.charAt(index); + } + if (nextCh === symb) { + depth++; + } else if (nextCh === reverseSymb) { + depth--; + } + } + + if (nextCh) { + return { line: line, ch: index }; + } + return cur; + } + + function selectCompanionObject(cm, revSymb, inclusive) { + var cur = cm.getCursor(); + + var end = findMatchedSymbol(cm, cur, revSymb); + var start = findMatchedSymbol(cm, end); + start.ch += inclusive ? 1 : 0; + end.ch += inclusive ? 0 : 1; + + return { start: start, end: end }; + } + + function regexLastIndexOf(string, pattern, startIndex) { + for (var i = !startIndex ? string.length : startIndex; + i >= 0; --i) { + if (pattern.test(string.charAt(i))) { + return i; + } + } + return -1; + } + + // Takes in a symbol and a cursor and tries to simulate text objects that + // have identical opening and closing symbols + // TODO support across multiple lines + function findBeginningAndEnd(cm, symb, inclusive) { + var cur = cm.getCursor(); + var line = cm.getLine(cur.line); + var chars = line.split(''); + var start, end, i, len; + var firstIndex = chars.indexOf(symb); + + // the decision tree is to always look backwards for the beginning first, + // but if the cursor is in front of the first instance of the symb, + // then move the cursor forward + if (cur.ch < firstIndex) { + cur.ch = firstIndex; + // Why is this line even here??? + // cm.setCursor(cur.line, firstIndex+1); + } + // otherwise if the cursor is currently on the closing symbol + else if (firstIndex < cur.ch && chars[cur.ch] == symb) { + end = cur.ch; // assign end to the current cursor + --cur.ch; // make sure to look backwards + } + + // if we're currently on the symbol, we've got a start + if (chars[cur.ch] == symb && !end) { + start = cur.ch + 1; // assign start to ahead of the cursor + } else { + // go backwards to find the start + for (i = cur.ch; i > -1 && !start; i--) { + if (chars[i] == symb) { + start = i + 1; + } + } + } + + // look forwards for the end symbol + if (start && !end) { + for (i = start, len = chars.length; i < len && !end; i++) { + if (chars[i] == symb) { + end = i; + } + } + } + + // nothing found + if (!start || !end) { + return { start: cur, end: cur }; + } + + // include the symbols + if (inclusive) { + --start; ++end; + } + + return { + start: { line: cur.line, ch: start }, + end: { line: cur.line, ch: end } + }; + } + + // Search functions + function SearchState() { + // Highlighted text that match the query. + this.marked = null; + } + SearchState.prototype = { + getQuery: function() { + return getVimGlobalState().query; + }, + setQuery: function(query) { + getVimGlobalState().query = query; + }, + getMarked: function() { + return this.marked; + }, + setMarked: function(marked) { + this.marked = marked; + }, + isReversed: function() { + return getVimGlobalState().isReversed; + }, + setReversed: function(reversed) { + getVimGlobalState().isReversed = reversed; + } + }; + function getSearchState(cm) { + var vim = getVimState(cm); + return vim.searchState_ || (vim.searchState_ = new SearchState()); + } + function dialog(cm, text, shortText, callback, initialValue) { + if (cm.openDialog) { + cm.openDialog(text, callback, { bottom: true, value: initialValue }); + } + else { + callback(prompt(shortText, "")); + } + } + function findUnescapedSlashes(str) { + var escapeNextChar = false; + var slashes = []; + for (var i = 0; i < str.length; i++) { + var c = str.charAt(i); + if (!escapeNextChar && c == '/') { + slashes.push(i); + } + escapeNextChar = (c == '\\'); + } + return slashes; + } + /** + * Extract the regular expression from the query and return a Regexp object. + * Returns null if the query is blank. + * If ignoreCase is passed in, the Regexp object will have the 'i' flag set. + * If smartCase is passed in, and the query contains upper case letters, + * then ignoreCase is overridden, and the 'i' flag will not be set. + * If the query contains the /i in the flag part of the regular expression, + * then both ignoreCase and smartCase are ignored, and 'i' will be passed + * through to the Regex object. + */ + function parseQuery(cm, query, ignoreCase, smartCase) { + // First try to extract regex + flags from the input. If no flags found, + // extract just the regex. IE does not accept flags directly defined in + // the regex string in the form /regex/flags + var slashes = findUnescapedSlashes(query); + var regexPart; + var forceIgnoreCase; + if (!slashes.length) { + // Query looks like 'regexp' + regexPart = query; + } else { + // Query looks like 'regexp/...' + regexPart = query.substring(0, slashes[0]); + var flagsPart = query.substring(slashes[0]); + forceIgnoreCase = (flagsPart.indexOf('i') != -1); + } + if (!regexPart) { + return null; + } + if (smartCase) { + ignoreCase = (/^[^A-Z]*$/).test(regexPart); + } + try { + var regexp = new RegExp(regexPart, + (ignoreCase || forceIgnoreCase) ? 'i' : undefined); + return regexp; + } catch (e) { + showConfirm(cm, 'Invalid regex: ' + regexPart); + } + } + function showConfirm(cm, text) { + if (cm.openConfirm) { + cm.openConfirm('' + text + + ' ', function() {}, + {bottom: true}); + } else { + alert(text); + } + } + function makePrompt(prefix, desc) { + var raw = ''; + if (prefix) { + raw += '' + prefix + ''; + } + raw += ' ' + + ''; + if (desc) { + raw += ''; + raw += desc; + raw += ''; + } + return raw; + } + var searchPromptDesc = '(Javascript regexp)'; + function showPrompt(cm, onPromptClose, prefix, desc, initialValue) { + var shortText = (prefix || '') + ' ' + (desc || ''); + dialog(cm, makePrompt(prefix, desc), shortText, onPromptClose, + initialValue); + } + function regexEqual(r1, r2) { + if (r1 instanceof RegExp && r2 instanceof RegExp) { + var props = ["global", "multiline", "ignoreCase", "source"]; + for (var i = 0; i < props.length; i++) { + var prop = props[i]; + if (r1[prop] !== r2[prop]) { + return(false); + } + } + return(true); + } + return(false); + } + function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) { + cm.operation(function() { + var state = getSearchState(cm); + if (!rawQuery) { + return; + } + var query = parseQuery(cm, rawQuery, !!ignoreCase, !!smartCase); + if (!query) { + return; + } + if (regexEqual(query, state.getQuery())) { + return; + } + clearSearchHighlight(cm); + highlightSearchMatches(cm, query); + state.setQuery(query); + }); + } + function highlightSearchMatches(cm, query) { + // TODO: Highlight only text inside the viewport. Highlighting everything + // is inefficient and expensive. + if (cm.lineCount() < 2000) { // This is too expensive on big documents. + var marked = []; + for (var cursor = cm.getSearchCursor(query); + cursor.findNext();) { + marked.push(cm.markText(cursor.from(), cursor.to(), + { className: 'cm-searching' })); + } + getSearchState(cm).setMarked(marked); + } + } + function findNext(cm, prev, repeat) { + return cm.operation(function() { + var state = getSearchState(cm); + var query = state.getQuery(); + if (!query) { + return; + } + if (!state.getMarked()) { + highlightSearchMatches(cm, query); + } + var pos = cm.getCursor(); + // If search is initiated with ? instead of /, negate direction. + prev = (state.isReversed()) ? !prev : prev; + if (!prev) { + pos.ch += 1; + } + var cursor = cm.getSearchCursor(query, pos); + for (var i = 0; i < repeat; i++) { + if (!cursor.find(prev)) { + // SearchCursor may have returned null because it hit EOF, wrap + // around and try again. + cursor = cm.getSearchCursor(query, + (prev) ? { line: cm.lineCount() - 1} : {line: 0, ch: 0} ); + if (!cursor.find(prev)) { + return; + } + } + } + return cursor.from(); + });} + function clearSearchHighlight(cm) { + cm.operation(function() { + var state = getSearchState(cm); + if (!state.getQuery()) { + return; + } + var marked = state.getMarked(); + if (!marked) { + return; + } + for (var i = 0; i < marked.length; ++i) { + marked[i].clear(); + } + state.setMarked(null); + });} + /** + * Check if pos is in the specified range, INCLUSIVE. + * Range can be specified with 1 or 2 arguments. + * If the first range argument is an array, treat it as an array of line + * numbers. Match pos against any of the lines. + * If the first range argument is a number, + * if there is only 1 range argument, check if pos has the same line + * number + * if there are 2 range arguments, then check if pos is in between the two + * range arguments. + */ + function isInRange(pos, start, end) { + if (typeof pos != 'number') { + // Assume it is a cursor position. Get the line number. + pos = pos.line; + } + if (start instanceof Array) { + return inArray(pos, start); + } else { + if (end) { + return (pos >= start && pos <= end); + } else { + return pos == start; + } + } + } + + // Ex command handling + // Care must be taken when adding to the default Ex command map. For any + // pair of commands that have a shared prefix, at least one of their + // shortNames must not match the prefix of the other command. + var defaultExCommandMap = [ + { name: 'map', type: 'builtIn' }, + { name: 'write', shortName: 'w', type: 'builtIn' }, + { name: 'undo', shortName: 'u', type: 'builtIn' }, + { name: 'redo', shortName: 'red', type: 'builtIn' }, + { name: 'substitute', shortName: 's', type: 'builtIn'} + ]; + var ExCommandDispatcher = function() { + this.buildCommandMap_(); + }; + ExCommandDispatcher.prototype = { + processCommand: function(cm, input) { + var inputStream = new CodeMirror.StringStream(input); + var params = {}; + params.input = input; + try { + this.parseInput_(cm, inputStream, params); + } catch(e) { + showConfirm(cm, e); + return; + } + var commandName; + if (!params.commandName) { + // If only a line range is defined, move to the line. + if (params.line !== undefined) { + commandName = 'move'; + } + } else { + var command = this.matchCommand_(params.commandName); + if (command) { + commandName = command.name; + this.parseCommandArgs_(inputStream, params, command); + if (command.type == 'exToKey') { + // Handle Ex to Key mapping. + for (var i = 0; i < command.toKeys.length; i++) { + vim.handleKey(cm, command.toKeys[i]); + } + return; + } else if (command.type == 'exToEx') { + // Handle Ex to Ex mapping. + this.processCommand(cm, command.toInput); + return; + } + } + } + if (!commandName) { + showConfirm(cm, 'Not an editor command ":' + input + '"'); + return; + } + exCommands[commandName](cm, params); + }, + parseInput_: function(cm, inputStream, result) { + inputStream.eatWhile(':'); + // Parse range. + if (inputStream.eat('%')) { + result.line = 0; + result.lineEnd = cm.lineCount() - 1; + } else { + result.line = this.parseLineSpec_(cm, inputStream); + if (result.line && 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.lineCount() - 1; + case '\'': + var mark = getVimState(cm).marks[inputStream.next()]; + if (mark && mark.find()) { + return mark.find().line; + } else { + throw "Mark not set"; + } + break; + default: + inputStream.backUp(1); + return cm.getCursor().line; + } + }, + parseCommandArgs_: function(inputStream, params, command) { + if (inputStream.eol()) { + return; + } + params.argString = inputStream.match(/.*/)[0]; + // Parse command-line arguments + var delim = command.argDelimiter || /\s+/; + var args = 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.charAt(0) == ':') { + var commandName = lhs.substring(1); + if (rhs != ':' && rhs.charAt(0) == ':') { + // Ex to Ex mapping + this.commandMap_[commandName] = { + name: commandName, + type: 'exToEx', + toInput: rhs.substring(1) + }; + } else { + // Ex to key mapping + this.commandMap_[commandName] = { + name: commandName, + type: 'exToKey', + toKeys: parseKeyString(rhs) + }; + } + } else { + if (rhs != ':' && rhs.charAt(0) == ':') { + // Key to Ex mapping. + defaultKeymap.unshift({ + keys: parseKeyString(lhs), + type: 'keyToEx', + exArgs: { input: rhs.substring(1) }}); + } else { + // Key to key mapping + defaultKeymap.unshift({ + keys: parseKeyString(lhs), + type: 'keyToKey', + toKeys: parseKeyString(rhs) + }); + } + } + } + }; + + // Converts a key string sequence of the form abd into Vim's + // keymap representation. + function parseKeyString(str) { + var idx = 0; + var keys = []; + while (idx < str.length) { + if (str.charAt(idx) != '<') { + keys.push(str.charAt(idx)); + idx++; + continue; + } + // Vim key notation here means desktop Vim key-notation. + // See :help key-notation in desktop Vim. + var vimKeyNotationStart = ++idx; + while (str.charAt(idx++) != '>') {} + var vimKeyNotation = str.substring(vimKeyNotationStart, idx - 1); + var match = (/^C-(.+)$/).exec(vimKeyNotation); + if (match) { + var key; + switch (match[1]) { + case 'BS': + key = 'Backspace'; + break; + case 'CR': + key = 'Enter'; + break; + case 'Del': + key = 'Delete'; + break; + default: + key = match[1]; + break; + } + keys.push('Ctrl-' + key); + } + } + return keys; + } + + var exCommands = { + map: function(cm, params) { + var mapArgs = params.commandArgs; + if (!mapArgs || mapArgs.length < 2) { + if (cm) { + showConfirm(cm, 'Invalid mapping: ' + params.input); + } + return; + } + exCommandDispatcher.map(mapArgs[0], mapArgs[1], cm); + }, + move: function(cm, params) { + commandDispatcher.processMotion(cm, getVimState(cm), { + motion: 'moveToLineOrEdgeOfDocument', + motionArgs: { forward: false, explicitRepeat: true, + linewise: true, repeat: params.line }}); + }, + substitute: function(cm, params) { + var argString = params.argString; + var slashes = findUnescapedSlashes(argString); + if (slashes[0] !== 0) { + showConfirm(cm, 'Substitutions should be of the form ' + + ':s/pattern/replace/'); + return; + } + var regexPart = argString.substring(slashes[0] + 1, slashes[1]); + var replacePart = ''; + var flagsPart; + if (slashes[1]) { + replacePart = argString.substring(slashes[1] + 1, slashes[2]); + } + if (slashes[2]) { + flagsPart = argString.substring(slashes[2] + 1); + } + if (flagsPart) { + regexPart = regexPart + '/' + flagsPart; + } + updateSearchQuery(cm, regexPart, true /** ignoreCase */, + true /** smartCase */); + var state = getSearchState(cm); + var query = state.getQuery(); + var startPos = clipCursorToContent(cm, { line: params.line || 0, + ch: 0 }); + function doReplace() { + for (var cursor = cm.getSearchCursor(query, startPos); + cursor.findNext();) { + if (!isInRange(cursor.from(), params.line, params.lineEnd)) { + break; + } + var text = cm.getRange(cursor.from(), cursor.to()); + var newText = text.replace(query, replacePart); + cursor.replace(newText); + } + var vim = getVimState(cm); + if (vim.visualMode) { + exitVisualMode(cm, vim); + } + } + if (cm.compoundChange) { + // Only exists in v2 + cm.compoundChange(doReplace); + } else { + cm.operation(doReplace); + } + }, + redo: CodeMirror.commands.redo, + undo: CodeMirror.commands.undo, + write: function(cm) { + if (CodeMirror.commands.save) { + // If a save command is defined, call it. + CodeMirror.commands.save(cm); + } else { + // Saves to text area if no save command is defined. + cm.save(); + } + } + }; + + var exCommandDispatcher = new ExCommandDispatcher(); + + // Register Vim with CodeMirror + function buildVimKeyMap() { + /** + * Handle the raw key event from CodeMirror. Translate the + * Shift + key modifier to the resulting letter, while preserving other + * modifers. + */ + // TODO: Figure out a way to catch capslock. + function handleKeyEvent_(cm, key, modifier) { + if (isUpperCase(key)) { + // Convert to lower case if shift is not the modifier since the key + // we get from CodeMirror is always upper case. + if (modifier == 'Shift') { + modifier = null; + } + else { + key = key.toLowerCase(); + } + } + if (modifier) { + // Vim will parse modifier+key combination as a single key. + key = modifier + '-' + key; + } + vim.handleKey(cm, key); + } + + // Closure to bind CodeMirror, key, modifier. + function keyMapper(key, modifier) { + return function(cm) { + handleKeyEvent_(cm, key, modifier); + }; + } + + var modifiers = ['Shift', 'Ctrl']; + var keyMap = { + 'nofallthrough': true, + 'style': 'fat-cursor' + }; + function bindKeys(keys, modifier) { + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (!modifier && inArray(key, specialSymbols)) { + // Wrap special symbols with '' because that's how CodeMirror binds + // them. + key = "'" + key + "'"; + } + if (modifier) { + keyMap[modifier + '-' + key] = keyMapper(keys[i], modifier); + } else { + keyMap[key] = keyMapper(keys[i]); + } + } + } + bindKeys(upperCaseAlphabet); + bindKeys(upperCaseAlphabet, 'Shift'); + bindKeys(upperCaseAlphabet, 'Ctrl'); + bindKeys(specialSymbols); + bindKeys(specialSymbols, 'Ctrl'); + bindKeys(numbers); + bindKeys(numbers, 'Ctrl'); + bindKeys(specialKeys); + bindKeys(specialKeys, 'Ctrl'); + return keyMap; + } + CodeMirror.keyMap.vim = buildVimKeyMap(); + + function exitInsertMode(cm) { + cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1, true); + cm.setOption('keyMap', 'vim'); + } + + CodeMirror.keyMap['vim-insert'] = { + // TODO: override navigation keys so that Esc will cancel automatic + // indentation from o, O, i_ + 'Esc': exitInsertMode, + 'Ctrl-[': exitInsertMode, + 'Ctrl-C': exitInsertMode, + 'Ctrl-N': 'autocomplete', + 'Ctrl-P': 'autocomplete', + 'Enter': function(cm) { + var fn = CodeMirror.commands.newlineAndIndentContinueComment || + CodeMirror.commands.newlineAndIndent; + fn(cm); + }, + fallthrough: ['default'] + }; + + return vimApi; + }; + // Initialize Vim and make it available as an API. + var vim = Vim(); + CodeMirror.Vim = vim; +} +)(); diff --git a/codemirror/lib/codemirror.css b/codemirror/lib/codemirror.css new file mode 100644 index 0000000..2bed458 --- /dev/null +++ b/codemirror/lib/codemirror.css @@ -0,0 +1,245 @@ +/* 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 { + background-color: white; /* The little square between H and V scrollbars */ +} + +/* GUTTER */ + +.CodeMirror-gutters { + border-right: 1px solid #ddd; + background-color: #f7f7f7; +} +.CodeMirror-linenumbers {} +.CodeMirror-linenumber { + padding: 0 3px 0 5px; + min-width: 20px; + text-align: right; + color: #999; +} + +/* CURSOR */ + +.CodeMirror pre.CodeMirror-cursor { + border-left: 1px solid black; +} +/* Shown when moving in bi-directional text */ +.CodeMirror pre.CodeMirror-secondarycursor { + border-left: 1px solid silver; +} +.cm-keymap-fat-cursor pre.CodeMirror-cursor { + width: auto; + border: 0; + background: transparent; + background: rgba(0, 200, 0, .4); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#6600c800, endColorstr=#4c00c800); +} +/* Kludge to turn off filter in ie9+, which also accepts rgba */ +.cm-keymap-fat-cursor pre.CodeMirror-cursor:not(#nonsense_id) { + filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); +} +/* Can style cursor different in overwrite (non-insert) mode */ +.CodeMirror pre.CodeMirror-cursor.CodeMirror-overwrite {} + +/* 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-error {color: #f00;} +.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-emstrong {font-style: italic; font-weight: bold;} +.cm-link {text-decoration: underline;} + +.cm-invalidchar {color: #f00;} + +div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} +div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} + +/* 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; +} + +.CodeMirror-scroll { + /* 30px is the magic margin used to hide the element's real scrollbars */ + /* See overflow: hidden in .CodeMirror, and the paddings in .CodeMirror-sizer */ + margin-bottom: -30px; margin-right: -30px; + padding-bottom: 30px; padding-right: 30px; + height: 100%; + outline: none; /* Prevent dragging from highlighting the element */ + position: relative; +} +.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 { + 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; + z-index: 6; +} + +.CodeMirror-gutters { + position: absolute; left: 0; top: 0; + height: 100%; + z-index: 3; +} +.CodeMirror-gutter { + height: 100%; + 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; -o-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-linebackground { + position: absolute; + left: 0; right: 0; top: 0; bottom: 0; + z-index: 0; +} + +.CodeMirror-linewidget { + position: relative; + z-index: 2; +} + +.CodeMirror-wrap .CodeMirror-scroll { + overflow-x: hidden; +} + +.CodeMirror-measure { + position: absolute; + width: 100%; height: 0px; + overflow: hidden; + visibility: hidden; +} +.CodeMirror-measure pre { position: static; } + +.CodeMirror pre.CodeMirror-cursor { + position: absolute; + visibility: hidden; + border-right: none; + width: 0; +} +.CodeMirror-focused pre.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; } +.CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee;} + .cm-tab { + background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAMCAYAAAAkuj5RAAAAAXNSR0IArs4c6QAAAGFJREFUSMft1LsRQFAQheHPowAKoACx3IgEKtaEHujDjORSgWTH/ZOdnZOcM/sgk/kFFWY0qV8foQwS4MKBCS3qR6ixBJvElOobYAtivseIE120FaowJPN75GMu8j/LfMwNjh4HUpwg4LUAAAAASUVORK5CYII=); + background-position: right; + background-repeat: no-repeat; + } + +@media print { + /* Hide the cursor when printing */ + .CodeMirror pre.CodeMirror-cursor { + visibility: hidden; + } +} diff --git a/codemirror/lib/codemirror.js b/codemirror/lib/codemirror.js new file mode 100644 index 0000000..fd16cce --- /dev/null +++ b/codemirror/lib/codemirror.js @@ -0,0 +1,4646 @@ +// 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 = /MSIE [1-7]\b/.test(navigator.userAgent); + var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent); + 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|IEMobile/i.test(navigator.userAgent); + var mac = ios || /Mac/.test(navigator.platform); + var windows = /windows/i.test(navigator.platform); + + var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/); + if (opera_version) opera_version = Number(opera_version[1]); + // 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)); + + // 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 display = this.display = makeDisplay(place); + display.wrapper.CodeMirror = this; + updateGutters(this); + if (options.autofocus && !mobile) focusInput(this); + + this.view = makeView(new BranchChunk([new LeafChunk([makeLine("", null, textHeight(display))])])); + this.nextOpId = 0; + loadMode(this); + themeChanged(this); + if (options.lineWrapping) + this.display.wrapper.className += " CodeMirror-wrap"; + + // Initialize the content. + this.setValue(options.value || ""); + // Override magic textarea content restore that IE sometimes does + // on our hidden textarea on reload + if (ie) setTimeout(bind(resetInput, this, true), 20); + this.view.history = makeHistory(); + + 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) { + var d = {}; + var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none;"); + if (!webkit) input.setAttribute("wrap", "off"); + input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); + // 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"); + // DIVs containing the selection and the actual code + d.lineDiv = elt("div"); + 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("pre", "\u00a0", "CodeMirror-cursor"); + // Secondary cursor, shown when on a 'jump' in bi-directional text + d.otherCursor = elt("pre", "\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", "\u00a0", null, "position: absolute; height: " + scrollerCutOff + "px"); + // Will contain the gutters, if any + d.gutters = elt("div", null, "CodeMirror-gutters"); + d.lineGutter = null; + // Helper element to properly size the gutter backgrounds + var scrollerInner = elt("div", [d.sizer, d.heightForcer, d.gutters], null, "position: relative; min-height: 100%"); + // Provides scrolling + d.scroller = elt("div", [scrollerInner], "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.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.showingFrom = d.showingTo = d.lastSizeC = 0; + + // 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(); + // True when a drag from the editor is active + d.draggingText = false; + + 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; + + // Used to adjust overwrite behaviour when a paste has been + // detected + d.pasteIncoming = false; + + return d; + } + + // VIEW CONSTRUCTOR + + function makeView(doc) { + var selPos = {line: 0, ch: 0}; + return { + doc: doc, + // frontier is the point up to which the content has been parsed, + frontier: 0, highlight: new Delayed(), + sel: {from: selPos, to: selPos, head: selPos, anchor: selPos, shift: false, extend: false}, + scrollTop: 0, scrollLeft: 0, + overwrite: false, focused: false, + // Tracks the maximum line length so that + // the horizontal scrollbar can be kept + // static when scrolling. + maxLine: getLine(doc, 0), + maxLineLength: 0, + maxLineChanged: false, + suppressEdits: false, + goalColumn: null, + cantEdit: false, + keyMaps: [], + overlays: [], + modeGen: 0 + }; + } + + // STATE UPDATES + + // Used to get the editor into a consistent state again when options change. + + function loadMode(cm) { + var doc = cm.view.doc; + cm.view.mode = CodeMirror.getMode(cm.options, cm.options.mode); + doc.iter(0, doc.size, function(line) { if (line.stateAfter) line.stateAfter = null; }); + cm.view.frontier = 0; + startWorker(cm, 100); + cm.view.modeGen++; + } + + function wrappingChanged(cm) { + var doc = cm.view.doc, th = textHeight(cm.display); + if (cm.options.lineWrapping) { + cm.display.wrapper.className += " CodeMirror-wrap"; + var perLine = cm.display.scroller.clientWidth / charWidth(cm.display) - 3; + doc.iter(0, doc.size, function(line) { + if (line.height == 0) return; + var guess = Math.ceil(line.text.length / perLine) || 1; + if (guess != 1) updateLineHeight(line, guess * th); + }); + cm.display.sizer.style.minWidth = ""; + } else { + cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", ""); + computeMaxLength(cm.view); + doc.iter(0, doc.size, function(line) { + if (line.height != 0) updateLineHeight(line, th); + }); + } + regChange(cm, 0, doc.size); + clearCaches(cm); + setTimeout(function(){updateScrollbars(cm.display, cm.view.doc.height);}, 100); + } + + function keyMapChanged(cm) { + var style = keyMap[cm.options.keyMap].style; + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") + + (style ? " cm-keymap-" + style : ""); + } + + 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); + updateDisplay(cm, true); + } + + 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(view) { + view.maxLine = getLine(view.doc, 0); + view.maxLineLength = lineLength(view.doc, view.maxLine); + view.maxLineChanged = true; + view.doc.iter(1, view.doc.size, function(line) { + var len = lineLength(view.doc, line); + if (len > view.maxLineLength) { + view.maxLineLength = len; + view.maxLine = line; + } + }); + } + + // Make sure the gutters options contains the element + // "CodeMirror-linenumbers" when the lineNumbers option is true. + function setGuttersForLineNumbers(options) { + var found = false; + for (var i = 0; i < options.gutters.length; ++i) { + if (options.gutters[i] == "CodeMirror-linenumbers") { + if (options.lineNumbers) found = true; + else options.gutters.splice(i--, 1); + } + } + if (!found && options.lineNumbers) + options.gutters.push("CodeMirror-linenumbers"); + } + + // SCROLLBARS + + // Re-synchronize the fake scrollbars with the actual size of the + // content. Optionally force a scrollTop. + function updateScrollbars(d /* display */, docHeight) { + var totalHeight = docHeight + 2 * paddingTop(d); + d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px"; + var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight); + var needsH = d.scroller.scrollWidth > d.scroller.clientWidth; + var needsV = scrollHeight > d.scroller.clientHeight; + 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 = ""; + 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 = ""; + 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 (mac_geLion && scrollbarWidth(d.measure) === 0) + d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px"; + } + + 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) return; + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.view.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; + } + display.gutters.style.left = (comp + gutterW) + "px"; + } + + function maybeUpdateLineNumberWidth(cm) { + if (!cm.options.lineNumbers) return false; + var doc = cm.view.doc, last = lineNumberFor(cm.options, 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 display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; + } + + // DISPLAY DRAWING + + function updateDisplay(cm, changes, viewPort) { + var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo; + var updated = updateDisplayInner(cm, changes, viewPort); + if (updated) { + signalLater(cm, cm, "update", cm); + if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo) + signalLater(cm, cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo); + } + updateSelection(cm); + updateScrollbars(cm.display, cm.view.doc.height); + + 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, viewPort) { + var display = cm.display, doc = cm.view.doc; + if (!display.wrapper.clientWidth) { + display.showingFrom = display.showingTo = display.viewOffset = 0; + return; + } + + // Compute the new visible window + // If scrollTop is specified, use that to determine which lines + // to render instead of the current scrollbar position. + var visible = visibleLines(display, doc, viewPort); + // Bail out if the visible area is already rendered and nothing changed. + if (changes !== true && changes.length == 0 && + visible.from > display.showingFrom && visible.to < display.showingTo) + return; + + if (changes && maybeUpdateLineNumberWidth(cm)) + changes = true; + display.sizer.style.marginLeft = display.scrollbarH.style.left = display.gutters.offsetWidth + "px"; + + // When merged lines are present, the line that needs to be + // redrawn might not be the one that was changed. + if (changes !== true && sawCollapsedSpans) + for (var i = 0; i < changes.length; ++i) { + var ch = changes[i], merged; + while (merged = collapsedSpanAtStart(getLine(doc, ch.from))) { + var from = merged.find().from.line; + if (ch.diff) ch.diff -= ch.from - from; + ch.from = from; + } + } + + // Used to determine which lines need their line numbers updated + var positionsChangedFrom = changes === true ? 0 : Infinity; + if (cm.options.lineNumbers && changes && changes !== true) + for (var i = 0; i < changes.length; ++i) + if (changes[i].diff) { positionsChangedFrom = changes[i].from; break; } + + var from = Math.max(visible.from - cm.options.viewportMargin, 0); + var to = Math.min(doc.size, visible.to + cm.options.viewportMargin); + if (display.showingFrom < from && from - display.showingFrom < 20) from = display.showingFrom; + if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(doc.size, display.showingTo); + if (sawCollapsedSpans) { + from = lineNo(visualLine(doc, getLine(doc, from))); + while (to < doc.size && lineIsHidden(getLine(doc, to))) ++to; + } + + // Create a range of theoretically intact lines, and punch holes + // in that using the change info. + var intact = changes === true ? [] : + computeIntact([{from: display.showingFrom, to: display.showingTo}], changes); + // 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 (intactLines == to - from && from == display.showingFrom && to == display.showingTo) + return; + intact.sort(function(a, b) {return a.from - b.from;}); + + var focused = document.activeElement; + if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none"; + patchDisplay(cm, from, to, intact, positionsChangedFrom); + display.lineDiv.style.display = ""; + if (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; + display.showingFrom = from; display.showingTo = to; + startWorker(cm, 100); + + 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 = node.getBoundingClientRect(); + 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); + } + display.viewOffset = heightAtLine(cm, getLine(doc, from)); + // Position the mover div to align with the current virtual scroll position + display.mover.style.top = display.viewOffset + "px"; + return true; + } + + 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; + // IE does bad things to nodes when .innerHTML = "" is used on a parent + // we still need widgets and markers intact to add back to the new content later + if (!intact.length && !ie && (!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 { + container.removeChild(node); + } + return next; + } + + var nextIntact = intact.shift(), lineNo = from; + cm.view.doc.iter(from, to, function(line) { + if (nextIntact && nextIntact.to == lineNo) nextIntact = intact.shift(); + if (lineIsHidden(line)) { + if (line.height != 0) updateLineHeight(line, 0); + } else if (nextIntact && nextIntact.from <= lineNo && nextIntact.to > lineNo) { + // 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 <= lineNo && cur.lineNumber) + setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineNo)); + cur = cur.nextSibling; + } else { + // This line needs to be generated. + var lineNode = buildLineElement(cm, line, lineNo, dims); + container.insertBefore(lineNode, cur); + lineNode.lineObj = line; + } + ++lineNo; + }); + while (cur) cur = rm(cur); + } + + function buildLineElement(cm, line, lineNo, dims) { + var lineElement = lineContent(cm, line); + var markers = line.gutterMarkers, display = cm.display; + + if (!cm.options.lineNumbers && !markers && !line.bgClass && !line.wrapClass && + (!line.widgets || !line.widgets.length)) return lineElement; + + // Lines with gutter elements or a background class need + // to be wrapped again, and have the extra elements added + // to the wrapper div + + var wrap = elt("div", null, line.wrapClass, "position: relative"); + if (cm.options.lineNumbers || markers) { + var gutterWrap = wrap.appendChild(elt("div", null, null, "position: absolute; left: " + + dims.fixedPos + "px")); + wrap.alignable = [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")); + } + } + // Kludge to make sure the styled element lies behind the selection (by z-index) + if (line.bgClass) + wrap.appendChild(elt("div", "\u00a0", line.bgClass + " CodeMirror-linebackground")); + wrap.appendChild(lineElement); + if (line.widgets) + for (var i = 0, ws = line.widgets; i < ws.length; ++i) { + var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); + node.widget = widget; + 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"; + } + if (widget.above) + wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement); + else + wrap.appendChild(node); + } + + if (ie_lt8) wrap.style.zIndex = 2; + return wrap; + } + + // SELECTION / CURSOR + + function updateSelection(cm) { + var display = cm.display; + var collapsed = posEq(cm.view.sel.from, cm.view.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 + var headPos = cursorCoords(cm, cm.view.sel.head, "div"); + var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); + 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.view.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.view.doc, sel = cm.view.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, retTop) { + var lineObj = getLine(doc, line); + var lineLen = lineObj.text.length, rVal = retTop ? Infinity : -Infinity; + function coords(ch) { + return charCoords(cm, {line: line, ch: ch}, "div", lineObj); + } + + iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { + var leftPos = coords(dir == "rtl" ? to - 1 : from); + var rightPos = coords(dir == "rtl" ? from : to - 1); + var left = leftPos.left, right = rightPos.right; + 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 (fromArg == null && from == 0) left = pl; + rVal = retTop ? Math.min(rightPos.top, rVal) : Math.max(rightPos.bottom, rVal); + if (left < pl + 1) left = pl; + add(left, rightPos.top, right - left, rightPos.bottom); + }); + return rVal; + } + + if (sel.from.line == sel.to.line) { + drawForLine(sel.from.line, sel.from.ch, sel.to.ch); + } else { + var fromObj = getLine(doc, sel.from.line); + var cur = fromObj, merged, path = [sel.from.line, sel.from.ch], singleLine; + while (merged = collapsedSpanAtEnd(cur)) { + var found = merged.find(); + path.push(found.from.ch, found.to.line, found.to.ch); + if (found.to.line == sel.to.line) { + path.push(sel.to.ch); + singleLine = true; + break; + } + cur = getLine(doc, found.to.line); + } + + // This is a single, merged line + if (singleLine) { + for (var i = 0; i < path.length; i += 3) + drawForLine(path[i], path[i+1], path[i+2]); + } else { + var middleTop, middleBot, toObj = getLine(doc, sel.to.line); + if (sel.from.ch) + // Draw the first line of selection. + middleTop = drawForLine(sel.from.line, sel.from.ch, null, false); + else + // Simply include it in the middle block. + middleTop = heightAtLine(cm, fromObj) - display.viewOffset; + + if (!sel.to.ch) + middleBot = heightAtLine(cm, toObj) - display.viewOffset; + else + middleBot = drawForLine(sel.to.line, collapsedSpanAtStart(toObj) ? null : 0, sel.to.ch, true); + + if (middleTop < middleBot) add(pl, middleTop, null, middleBot); + } + } + + removeChildrenAndAdd(display.selectionDiv, fragment); + display.selectionDiv.style.display = ""; + } + + // Cursor-blinking + function restartBlink(cm) { + var display = cm.display; + clearInterval(display.blinker); + var on = true; + display.cursor.style.visibility = display.otherCursor.style.visibility = ""; + display.blinker = setInterval(function() { + if (!display.cursor.offsetHeight) return; + display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden"; + }, cm.options.cursorBlinkRate); + } + + // HIGHLIGHT WORKER + + function startWorker(cm, time) { + if (cm.view.mode.startState && cm.view.frontier < cm.display.showingTo) + cm.view.highlight.set(time, bind(highlightWorker, cm)); + } + + function highlightWorker(cm) { + var view = cm.view, doc = view.doc; + if (view.frontier >= cm.display.showingTo) return; + var end = +new Date + cm.options.workTime; + var state = copyState(view.mode, getStateBefore(cm, view.frontier)); + var changed = [], prevChange; + doc.iter(view.frontier, Math.min(doc.size, cm.display.showingTo + 500), function(line) { + if (view.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 == view.frontier) prevChange.end++; + else changed.push(prevChange = {start: view.frontier, end: view.frontier + 1}); + } + line.stateAfter = copyState(view.mode, state); + } else { + processLine(cm, line, state); + line.stateAfter = view.frontier % 5 == 0 ? copyState(view.mode, state) : null; + } + ++view.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) { + var minindent, minline, doc = cm.view.doc; + for (var search = n, lim = n - 100; search > lim; --search) { + if (search == 0) return 0; + var line = getLine(doc, search-1); + if (line.stateAfter) 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) { + var view = cm.view; + if (!view.mode.startState) return true; + var pos = findStartLine(cm, n), state = pos && getLine(view.doc, pos-1).stateAfter; + if (!state) state = startState(view.mode); + else state = copyState(view.mode, state); + view.doc.iter(pos, n, function(line) { + processLine(cm, line, state); + var save = pos == n - 1 || pos % 5 == 0 || pos >= view.showingFrom && pos < view.showingTo; + line.stateAfter = save ? copyState(view.mode, state) : null; + ++pos; + }); + return state; + } + + // POSITION MEASUREMENT + + function paddingTop(display) {return display.lineSpace.offsetTop;} + function paddingLeft(display) { + var e = removeChildrenAndAdd(display.measure, elt("pre")).appendChild(elt("span", "x")); + return e.offsetLeft; + } + + function measureChar(cm, line, ch, data) { + var dir = -1; + data = data || measureLine(cm, line); + + for (var pos = ch;; pos += dir) { + var r = data[pos]; + if (r) break; + if (dir < 0 && pos == 0) dir = 1; + } + return {left: pos < ch ? r.right : r.left, + right: pos > ch ? r.left : r.right, + top: r.top, bottom: r.bottom}; + } + + function measureLine(cm, line) { + // First look in the cache + var display = cm.display, 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 && + display.scroller.clientWidth == memo.width) + return memo.measure; + } + + var measure = measureLineInner(cm, line); + // Store result in the cache + var memo = {text: line.text, width: display.scroller.clientWidth, + markedSpans: line.markedSpans, measure: measure}; + if (cache.length == 16) cache[++display.measureLineCachePos % 16] = memo; + else cache.push(memo); + return measure; + } + + function measureLineInner(cm, line) { + var display = cm.display, measure = emptyArray(line.text.length); + var pre = lineContent(cm, line, measure); + + // 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 = display.lineDiv.getBoundingClientRect(); + var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight; + for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) { + var size = cur.getBoundingClientRect(); + var top = Math.max(0, size.top - outer.top), bot = Math.min(size.bottom - outer.top, maxBot); + for (var j = 0; j < vranges.length; j += 2) { + var rtop = vranges[j], rbot = vranges[j+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[j] = Math.min(top, rtop); + vranges[j+1] = Math.max(bot, rbot); + break; + } + } + if (j == vranges.length) vranges.push(top, bot); + data[i] = {left: size.left - outer.left, right: size.right - outer.left, top: j}; + } + for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) { + var vr = cur.top; + cur.top = vranges[vr]; cur.bottom = vranges[vr+1]; + } + return data; + } + + function clearCaches(cm) { + cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0; + cm.display.cachedCharWidth = cm.display.cachedTextHeight = null; + cm.view.maxLineChanged = true; + } + + // 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 = lineObj.widgets[i].node.offsetHeight; + rect.top += size; rect.bottom += size; + } + if (context == "line") return rect; + if (!context) context = "local"; + var yOff = heightAtLine(cm, lineObj); + if (context != "local") yOff -= cm.display.viewOffset; + if (context == "page") { + var lOff = cm.display.lineSpace.getBoundingClientRect(); + yOff += lOff.top + (window.pageYOffset || (document.documentElement || document.body).scrollTop); + var xOff = lOff.left + (window.pageXOffset || (document.documentElement || document.body).scrollLeft); + rect.left += xOff; rect.right += xOff; + } + rect.top += yOff; rect.bottom += yOff; + return rect; + } + + function charCoords(cm, pos, context, lineObj) { + if (!lineObj) lineObj = getLine(cm.view.doc, pos.line); + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch), context); + } + + function cursorCoords(cm, pos, context, lineObj, measurement) { + lineObj = lineObj || getLine(cm.view.doc, pos.line); + if (!measurement) measurement = measureLine(cm, lineObj); + function get(ch, right) { + var m = measureChar(cm, lineObj, ch, measurement); + if (right) m.left = m.right; else m.right = m.left; + return intoCoordSystem(cm, lineObj, m, context); + } + var order = getOrder(lineObj), ch = pos.ch; + if (!order) return get(ch); + var main, other, linedir = order[0].level; + for (var i = 0; i < order.length; ++i) { + var part = order[i], rtl = part.level % 2, nb, here; + if (part.from < ch && part.to > ch) return get(ch, rtl); + var left = rtl ? part.to : part.from, right = rtl ? part.from : part.to; + if (left == ch) { + // Opera and IE return bogus offsets and widths for edges + // where the direction flips, but only for the side with the + // lower level. So we try to use the side with the higher + // level. + if (i && part.level < (nb = order[i-1]).level) here = get(nb.level % 2 ? nb.from : nb.to - 1, true); + else here = get(rtl && part.from != part.to ? ch - 1 : ch); + if (rtl == linedir) main = here; else other = here; + } else if (right == ch) { + var nb = i < order.length - 1 && order[i+1]; + if (!rtl && nb && nb.from == nb.to) continue; + if (nb && part.level < nb.level) here = get(nb.level % 2 ? nb.to - 1 : nb.from); + else here = get(rtl ? ch : ch - 1, true); + if (rtl == linedir) main = here; else other = here; + } + } + if (linedir && !ch) other = get(order[0].to - 1); + if (!main) return other; + if (other) main.other = other; + return main; + } + + // Coords must be lineSpace-local + function coordsChar(cm, x, y) { + var doc = cm.view.doc; + y += cm.display.viewOffset; + if (y < 0) return {line: 0, ch: 0, outside: true}; + var lineNo = lineAtHeight(doc, y); + if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc, doc.size - 1).text.length}; + if (x < 0) x = 0; + + for (;;) { + var lineObj = getLine(doc, lineNo); + var found = coordsCharInner(cm, lineObj, lineNo, x, y); + var merged = collapsedSpanAtEnd(lineObj); + if (merged && found.ch == lineRight(lineObj)) + lineNo = merged.find().to.line; + else + return found; + } + } + + function coordsCharInner(cm, lineObj, lineNo, x, y) { + var innerOff = y - heightAtLine(cm, lineObj); + var wrongLine = false, cWidth = cm.display.wrapper.clientWidth; + var measurement = measureLine(cm, lineObj); + + function getX(ch) { + var sp = cursorCoords(cm, {line: lineNo, ch: ch}, "line", + lineObj, measurement); + wrongLine = true; + if (innerOff > sp.bottom) return Math.max(0, sp.left - cWidth); + else if (innerOff < sp.top) return sp.left + cWidth; + else wrongLine = false; + return sp.left; + } + + var bidi = getOrder(lineObj), dist = lineObj.text.length; + var from = lineLeft(lineObj), to = lineRight(lineObj); + var fromX = paddingLeft(cm.display), toX = getX(to); + + if (x > toX) return {line: lineNo, ch: to, outside: wrongLine}; + // Do a binary search between these bounds. + for (;;) { + if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { + var after = x - fromX < toX - x, ch = after ? from : to; + while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch; + return {line: lineNo, ch: ch, after: after, outside: wrongLine}; + } + 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 (wrongLine) toX += 1000; dist -= step;} + else {from = middle; fromX = middleX; 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. + + function startOperation(cm) { + if (cm.curOp) ++cm.curOp.depth; + else cm.curOp = { + // Nested operations delay update until the outermost one + // finishes. + depth: 1, + // An array of ranges of lines that have to be updated. See + // updateDisplay. + changes: [], + delayedCallbacks: [], + updateInput: null, + userSelChange: null, + textChanged: null, + selectionChanged: false, + updateMaxLine: false, + id: ++cm.nextOpId + }; + } + + function endOperation(cm) { + var op = cm.curOp; + if (--op.depth) return; + cm.curOp = null; + var view = cm.view, display = cm.display; + if (op.updateMaxLine) computeMaxLength(view); + if (view.maxLineChanged && !cm.options.lineWrapping) { + var width = measureChar(cm, view.maxLine, view.maxLine.text.length).right; + display.sizer.style.minWidth = (width + 3 + scrollerCutOff) + "px"; + view.maxLineChanged = false; + var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.offsetWidth - display.scroller.clientWidth); + if (maxScrollLeft < view.scrollLeft) + setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true); + } + var newScrollPos, updated; + if (op.selectionChanged) { + var coords = cursorCoords(cm, view.sel.head); + newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom); + } + if (op.changes.length || newScrollPos && newScrollPos.scrollTop != null) + updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop); + if (!updated && op.selectionChanged) updateSelection(cm); + if (newScrollPos) scrollCursorIntoView(cm); + if (op.selectionChanged) restartBlink(cm); + + if (view.focused && op.updateInput) + resetInput(cm, op.userSelChange); + + if (op.textChanged) + signal(cm, "change", cm, op.textChanged); + if (op.selectionChanged) signal(cm, "cursorActivity", cm); + for (var i = 0; i < op.delayedCallbacks.length; ++i) op.delayedCallbacks[i](cm); + } + + // Wraps a function in an operation. Returns the wrapped function. + function operation(cm1, f) { + return function() { + var cm = cm1 || this; + startOperation(cm); + try {var result = f.apply(cm, arguments);} + finally {endOperation(cm);} + return result; + }; + } + + function regChange(cm, from, to, lendiff) { + cm.curOp.changes.push({from: from, to: to, diff: lendiff}); + } + + // INPUT HANDLING + + function slowPoll(cm) { + if (cm.view.pollingFast) return; + cm.display.poll.set(cm.options.pollInterval, function() { + readInput(cm); + if (cm.view.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, view = cm.view, sel = view.sel; + if (!view.focused || hasSelection(input) || isReadOnly(cm)) return false; + var text = input.value; + if (text == prevInput && posEq(sel.from, sel.to)) return false; + startOperation(cm); + view.sel.shift = false; + var same = 0, l = Math.min(prevInput.length, text.length); + while (same < l && prevInput[same] == text[same]) ++same; + var from = sel.from, to = sel.to; + if (same < prevInput.length) + from = {line: from.line, ch: from.ch - (prevInput.length - same)}; + else if (view.overwrite && posEq(from, to) && !cm.display.pasteIncoming) + to = {line: to.line, ch: Math.min(getLine(cm.view.doc, to.line).text.length, to.ch + (text.length - same))}; + var updateInput = cm.curOp.updateInput; + updateDoc(cm, from, to, splitLines(text.slice(same)), "end", + cm.display.pasteIncoming ? "paste" : "input", {from: from, to: to}); + cm.curOp.updateInput = updateInput; + if (text.length > 1000) input.value = cm.display.prevInput = ""; + else cm.display.prevInput = text; + endOperation(cm); + cm.display.pasteIncoming = false; + return true; + } + + function resetInput(cm, user) { + var view = cm.view, minimal, selected; + if (!posEq(view.sel.from, view.sel.to)) { + cm.display.prevInput = ""; + minimal = hasCopyEvent && + (view.sel.to.line - view.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000); + if (minimal) cm.display.input.value = "-"; + else cm.display.input.value = selected || cm.getSelection(); + if (view.focused) selectInput(cm.display.input); + } else if (user) cm.display.prevInput = cm.display.input.value = ""; + cm.display.inaccurateSelection = minimal; + } + + function focusInput(cm) { + if (cm.options.readOnly != "nocursor" && (ie || document.activeElement != cm.display.input)) + cm.display.input.focus(); + } + + function isReadOnly(cm) { + return cm.options.readOnly || cm.view.cantEdit; + } + + // EVENT HANDLERS + + function registerEventHandlers(cm) { + var d = cm.display; + on(d.scroller, "mousedown", operation(cm, onMouseDown)); + on(d.scroller, "dblclick", operation(cm, e_preventDefault)); + 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 (!gecko) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); + + on(d.scroller, "scroll", function() { + setScrollTop(cm, d.scroller.scrollTop); + setScrollLeft(cm, d.scroller.scrollLeft, true); + signal(cm, "scroll", cm); + }); + on(d.scrollbarV, "scroll", function() { + setScrollTop(cm, d.scrollbarV.scrollTop); + }); + on(d.scrollbarH, "scroll", function() { + 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.view.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; }); + on(window, "resize", function resizeHandler() { + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = null; + clearCaches(cm); + if (d.wrapper.parentNode) updateDisplay(cm, true); + else off(window, "resize", resizeHandler); + }); + + on(d.input, "keyup", operation(cm, function(e) { + if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; + if (e_prop(e, "keyCode") == 16) cm.view.sel.shift = false; + })); + on(d.input, "input", bind(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 (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(){ + if (eventInWidget(d, e)) return; + focusInput(cm); + fastPoll(cm); + }); + on(d.input, "paste", function() { + d.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 (/\bCodeMirror-(?:line)?widget\b/.test(n.className) || + 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) return null; + } + var x, y, space = display.lineSpace.getBoundingClientRect(); + // 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) { + var cm = this, display = cm.display, view = cm.view, sel = view.sel, doc = view.doc; + sel.shift = e_prop(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 (gecko) onContextMenu.call(cm, cm, e); + return; + case 2: + if (start) extendSelection(cm, 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 (!view.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, 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; + view.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, start); + focusInput(cm); + } + }); + // Let the drag handler handle this. + if (webkit) display.scroller.draggable = true; + view.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, clipPos(doc, start)); + + var startstart = sel.from, startend = sel.to; + + function doSelect(cur) { + if (type == "single") { + extendSelection(cm, 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, word.from, startend); + else extendSelection(cm, startstart, word.to); + } else if (type == "triple") { + if (posLess(cur, startstart)) extendSelection(cm, startend, clipPos(doc, {line: cur.line, ch: 0})); + else extendSelection(cm, startstart, clipPos(doc, {line: cur.line + 1, ch: 0})); + } + } + + var editorSize = display.wrapper.getBoundingClientRect(); + // Used to ensure timeout re-tries don't fire when another extend + // happened in the meantime (clearTimeout isn't reliable -- at + // least on Chrome, the timeouts still happen even when cleared, + // if the clear happens after their scheduled firing time). + var counter = 0; + + function extend(e) { + var curCount = ++counter; + var cur = posFromMouse(cm, e, true); + if (!cur) return; + if (!posEq(cur, last)) { + if (!view.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; + var cur = posFromMouse(cm, e); + if (cur) doSelect(cur); + 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 onDrop(e) { + var cm = this; + if (eventInWidget(cm.display, e) || (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e)))) + return; + e_preventDefault(e); + 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.view.doc, pos); + operation(cm, function() { + var end = replaceRange(cm, text.join(""), pos, pos, "paste"); + setSelection(cm, pos, end); + })(); + } + }; + 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.view.draggingText && !(posLess(pos, cm.view.sel.from) || posLess(cm.view.sel.to, pos))) { + cm.view.draggingText(e); + if (ie) setTimeout(bind(focusInput, cm), 50); + return; + } + try { + var text = e.dataTransfer.getData("Text"); + if (text) { + var curFrom = cm.view.sel.from, curTo = cm.view.sel.to; + setSelection(cm, pos, pos); + if (cm.view.draggingText) replaceRange(cm, "", curFrom, curTo, "paste"); + cm.replaceSelection(text, null, "paste"); + focusInput(cm); + onFocus(cm); + } + } + catch(e){} + } + } + + function clickInGutter(cm, e) { + var display = cm.display; + try { var mX = e.clientX, mY = e.clientY; } + catch(e) { return false; } + + if (mX >= Math.floor(display.gutters.getBoundingClientRect().right)) return false; + e_preventDefault(e); + if (!hasHandler(cm, "gutterClick")) return true; + + var lineBox = display.lineDiv.getBoundingClientRect(); + if (mY > lineBox.bottom) return true; + mY -= lineBox.top - display.viewOffset; + + for (var i = 0; i < cm.options.gutters.length; ++i) { + var g = display.gutters.childNodes[i]; + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.view.doc, mY); + var gutter = cm.options.gutters[i]; + signalLater(cm, cm, "gutterClick", cm, line, gutter, e); + break; + } + } + return true; + } + + function onDragStart(cm, e) { + if (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) + e.dataTransfer.setDragImage(elt('img'), 0, 0); + } + + function setScrollTop(cm, val) { + if (Math.abs(cm.view.scrollTop - val) < 2) return; + cm.view.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, []); + } + function setScrollLeft(cm, val, isScroller) { + if (isScroller ? val == cm.view.scrollLeft : Math.abs(cm.view.scrollLeft - val) < 2) return; + val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); + cm.view.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, wheelDX, wheelDY, wheelStartX, wheelStartY, 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; + + // 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; + } + } + } + + var scroll = cm.display.scroller; + // 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); + wheelStartX = null; // Abort measurement, if in progress + return; + } + + if (dy && wheelPixelsPerUnit != null) { + var pixels = dy * wheelPixelsPerUnit; + var top = cm.view.scrollTop, bot = top + cm.display.wrapper.clientHeight; + if (pixels < 0) top = Math.max(0, top + pixels - 50); + else bot = Math.min(cm.view.doc.height, bot + pixels + 50); + updateDisplay(cm, [], {top: top, bottom: bot}); + } + + if (wheelSamples < 20) { + if (wheelStartX == null) { + wheelStartX = scroll.scrollLeft; wheelStartY = scroll.scrollTop; + wheelDX = dx; wheelDY = dy; + setTimeout(function() { + if (wheelStartX == null) return; + var movedX = scroll.scrollLeft - wheelStartX; + var movedY = scroll.scrollTop - wheelStartY; + var sample = (movedY && wheelDY && movedY / wheelDY) || + (movedX && wheelDX && movedX / wheelDX); + wheelStartX = wheelStartY = null; + if (!sample) return; + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); + ++wheelSamples; + }, 200); + } else { + wheelDX += dx; 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 view = cm.view, prevShift = view.sel.shift; + try { + if (isReadOnly(cm)) view.suppressEdits = true; + if (dropShift) view.sel.shift = false; + bound(cm); + } catch(e) { + if (e != Pass) throw e; + return false; + } finally { + view.sel.shift = prevShift; + view.suppressEdits = false; + } + return true; + } + + function allKeyMaps(cm) { + var maps = cm.view.keyMaps.slice(0); + maps.push(cm.options.keyMap); + if (cm.options.extraKeys) maps.unshift(cm.options.extraKeys); + 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); + }, 50); + + var name = keyNames[e_prop(e, "keyCode")], handled = false; + if (name == null || e.altGraphKey) return false; + if (e_prop(e, "altKey")) name = "Alt-" + name; + if (e_prop(e, flipCtrlCmd ? "metaKey" : "ctrlKey")) name = "Ctrl-" + name; + if (e_prop(e, flipCtrlCmd ? "ctrlKey" : "metaKey")) name = "Cmd-" + name; + + var stopped = false; + function stop() { stopped = true; } + var keymaps = allKeyMaps(cm); + + if (e_prop(e, "shiftKey")) { + handled = lookupKey("Shift-" + name, keymaps, + function(b) {return doHandleBinding(cm, b, true);}, stop) + || lookupKey(name, keymaps, function(b) { + if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(cm, b); + }, stop); + } else { + handled = lookupKey(name, keymaps, + function(b) { return doHandleBinding(cm, b); }, stop); + } + if (stopped) handled = false; + if (handled) { + e_preventDefault(e); + restartBlink(cm); + if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; } + } + 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); + } + return handled; + } + + var lastStoppedKey = null; + function onKeyDown(e) { + var cm = this; + if (!cm.view.focused) onFocus(cm); + if (ie && e.keyCode == 27) { e.returnValue = false; } + if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; + var code = e_prop(e, "keyCode"); + // IE does strange things with escape. + cm.view.sel.shift = code == 16 || e_prop(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 && e_prop(e, mac ? "metaKey" : "ctrlKey")) + cm.replaceSelection(""); + } + } + + function onKeyPress(e) { + var cm = this; + if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; + var keyCode = e_prop(e, "keyCode"), charCode = e_prop(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.view.mode.electricChars && + this.options.smartIndent && !isReadOnly(this) && + this.view.mode.electricChars.indexOf(ch) > -1) + setTimeout(operation(cm, function() {indentLine(cm, cm.view.sel.to.line, "smart");}), 75); + if (handleCharBinding(cm, e, ch)) return; + fastPoll(cm); + } + + function onFocus(cm) { + if (cm.options.readOnly == "nocursor") return; + if (!cm.view.focused) { + signal(cm, "focus", cm); + cm.view.focused = true; + if (cm.display.scroller.className.search(/\bCodeMirror-focused\b/) == -1) + cm.display.scroller.className += " CodeMirror-focused"; + resetInput(cm, true); + } + slowPoll(cm); + restartBlink(cm); + } + function onBlur(cm) { + if (cm.view.focused) { + signal(cm, "blur", cm); + cm.view.focused = false; + cm.display.scroller.className = cm.display.scroller.className.replace(" CodeMirror-focused", ""); + } + clearInterval(cm.display.blinker); + setTimeout(function() {if (!cm.view.focused) cm.view.sel.shift = false;}, 150); + } + + var detectingSelectAll; + function onContextMenu(cm, e) { + var display = cm.display; + if (eventInWidget(display, e)) return; + + var sel = cm.view.sel; + var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; + if (!pos || opera) return; // Opera is difficult. + if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to)) + operation(cm, setSelection)(cm, 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; 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 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) { + clearTimeout(detectingSelectAll); + var extval = display.input.value = " " + (posEq(sel.from, sel.to) ? "" : display.input.value), i = 0; + display.prevInput = " "; + display.input.selectionStart = 1; display.input.selectionEnd = extval.length; + detectingSelectAll = setTimeout(function poll(){ + if (display.prevInput == " " && display.input.selectionStart == 0) + operation(cm, commands.selectAll)(cm); + else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500); + else resetInput(cm); + }, 200); + } + } + + if (gecko) { + e_stop(e); + on(window, "mouseup", function mouseup() { + off(window, "mouseup", mouseup); + setTimeout(rehide, 20); + }); + } else { + setTimeout(rehide, 50); + } + } + + // UPDATING + + // Replace the range from from to to by the strings in newText. + // Afterwards, set the selection to selFrom, selTo. + function updateDoc(cm, from, to, newText, selUpdate, origin) { + // Possibly split or suppress the update based on the presence + // of read-only spans in its range. + var split = sawReadOnlySpans && + removeReadOnlyRanges(cm.view.doc, from, to); + if (split) { + for (var i = split.length - 1; i >= 1; --i) + updateDocInner(cm, split[i].from, split[i].to, [""], origin); + if (split.length) + return updateDocInner(cm, split[0].from, split[0].to, newText, selUpdate, origin); + } else { + return updateDocInner(cm, from, to, newText, selUpdate, origin); + } + } + + function updateDocInner(cm, from, to, newText, selUpdate, origin) { + if (cm.view.suppressEdits) return; + + var view = cm.view, doc = view.doc, old = []; + doc.iter(from.line, to.line + 1, function(line) { + old.push(newHL(line.text, line.markedSpans)); + }); + var startSelFrom = view.sel.from, startSelTo = view.sel.to; + var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText); + var retval = updateDocNoUndo(cm, from, to, lines, selUpdate, origin); + if (view.history) addChange(cm, from.line, newText.length, old, origin, + startSelFrom, startSelTo, view.sel.from, view.sel.to); + return retval; + } + + function unredoHelper(cm, type) { + var doc = cm.view.doc, hist = cm.view.history; + var set = (type == "undo" ? hist.done : hist.undone).pop(); + if (!set) return; + var anti = {events: [], fromBefore: set.fromAfter, toBefore: set.toAfter, + fromAfter: set.fromBefore, toAfter: set.toBefore}; + for (var i = set.events.length - 1; i >= 0; i -= 1) { + hist.dirtyCounter += type == "undo" ? -1 : 1; + var change = set.events[i]; + var replaced = [], end = change.start + change.added; + doc.iter(change.start, end, function(line) { replaced.push(newHL(line.text, line.markedSpans)); }); + anti.events.push({start: change.start, added: change.old.length, old: replaced}); + var selPos = i ? null : {from: set.fromBefore, to: set.toBefore}; + updateDocNoUndo(cm, {line: change.start, ch: 0}, {line: end - 1, ch: getLine(doc, end-1).text.length}, + change.old, selPos, type); + } + (type == "undo" ? hist.undone : hist.done).push(anti); + } + + function updateDocNoUndo(cm, from, to, lines, selUpdate, origin) { + var view = cm.view, doc = view.doc, display = cm.display; + if (view.suppressEdits) return; + + var nlines = to.line - from.line, firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); + var recomputeMaxLength = false, checkWidthStart = from.line; + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(doc, firstLine)); + doc.iter(checkWidthStart, to.line + 1, function(line) { + if (lineLength(doc, line) == view.maxLineLength) { + recomputeMaxLength = true; + return true; + } + }); + } + + var lastHL = lst(lines), th = textHeight(display); + + // First adjust the line structure + if (from.ch == 0 && to.ch == 0 && hlText(lastHL) == "") { + // This is a whole-line replace. Treated specially to make + // sure line objects move the way they are supposed to. + var added = []; + for (var i = 0, e = lines.length - 1; i < e; ++i) + added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th)); + updateLine(cm, lastLine, lastLine.text, hlSpans(lastHL)); + if (nlines) doc.remove(from.line, nlines, cm); + if (added.length) doc.insert(from.line, added); + } else if (firstLine == lastLine) { + if (lines.length == 1) { + updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]) + + firstLine.text.slice(to.ch), hlSpans(lines[0])); + } else { + for (var added = [], i = 1, e = lines.length - 1; i < e; ++i) + added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th)); + added.push(makeLine(hlText(lastHL) + firstLine.text.slice(to.ch), hlSpans(lastHL), th)); + updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0])); + doc.insert(from.line + 1, added); + } + } else if (lines.length == 1) { + updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]) + + lastLine.text.slice(to.ch), hlSpans(lines[0])); + doc.remove(from.line + 1, nlines, cm); + } else { + var added = []; + updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0])); + updateLine(cm, lastLine, hlText(lastHL) + lastLine.text.slice(to.ch), hlSpans(lastHL)); + for (var i = 1, e = lines.length - 1; i < e; ++i) + added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th)); + if (nlines > 1) doc.remove(from.line + 1, nlines - 1, cm); + doc.insert(from.line + 1, added); + } + + if (cm.options.lineWrapping) { + var perLine = Math.max(5, display.scroller.clientWidth / charWidth(display) - 3); + doc.iter(from.line, from.line + lines.length, function(line) { + if (line.height == 0) return; + var guess = (Math.ceil(line.text.length / perLine) || 1) * th; + if (guess != line.height) updateLineHeight(line, guess); + }); + } else { + doc.iter(checkWidthStart, from.line + lines.length, function(line) { + var len = lineLength(doc, line); + if (len > view.maxLineLength) { + view.maxLine = line; + view.maxLineLength = len; + view.maxLineChanged = true; + recomputeMaxLength = false; + } + }); + if (recomputeMaxLength) cm.curOp.updateMaxLine = true; + } + + // Adjust frontier, schedule worker + view.frontier = Math.min(view.frontier, from.line); + startWorker(cm, 400); + + var lendiff = lines.length - nlines - 1; + // Remember that these lines changed, for updating the display + regChange(cm, from.line, to.line + 1, lendiff); + if (hasHandler(cm, "change")) { + // Normalize lines to contain only strings, since that's what + // the change event handler expects + for (var i = 0; i < lines.length; ++i) + if (typeof lines[i] != "string") lines[i] = lines[i].text; + var changeObj = {from: from, to: to, text: lines, origin: origin}; + if (cm.curOp.textChanged) { + for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {} + cur.next = changeObj; + } else cm.curOp.textChanged = changeObj; + } + + // Update the selection + var newSelFrom, newSelTo, end = {line: from.line + lines.length - 1, + ch: hlText(lastHL).length + (lines.length == 1 ? from.ch : 0)}; + if (selUpdate && typeof selUpdate != "string") { + if (selUpdate.from) { newSelFrom = selUpdate.from; newSelTo = selUpdate.to; } + else newSelFrom = newSelTo = selUpdate; + } else if (selUpdate == "end") { + newSelFrom = newSelTo = end; + } else if (selUpdate == "start") { + newSelFrom = newSelTo = from; + } else if (selUpdate == "around") { + newSelFrom = from; newSelTo = end; + } else { + var adjustPos = function(pos) { + if (posLess(pos, from)) return pos; + if (!posLess(to, pos)) return end; + var line = pos.line + lendiff; + var ch = pos.ch; + if (pos.line == to.line) + ch += hlText(lastHL).length - (to.ch - (to.line == from.line ? from.ch : 0)); + return {line: line, ch: ch}; + }; + newSelFrom = adjustPos(view.sel.from); + newSelTo = adjustPos(view.sel.to); + } + setSelection(cm, newSelFrom, newSelTo, null, true); + return end; + } + + function replaceRange(cm, code, from, to, origin) { + if (!to) to = from; + if (posLess(to, from)) { var tmp = to; to = from; from = tmp; } + return updateDoc(cm, from, to, splitLines(code), null, origin); + } + + // SELECTION + + 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 {line: x.line, ch: x.ch};} + + function clipLine(doc, n) {return Math.max(0, Math.min(n, doc.size-1));} + function clipPos(doc, pos) { + if (pos.line < 0) return {line: 0, ch: 0}; + if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc, doc.size-1).text.length}; + var ch = pos.ch, linelen = getLine(doc, pos.line).text.length; + if (ch == null || ch > linelen) return {line: pos.line, ch: linelen}; + else if (ch < 0) return {line: pos.line, ch: 0}; + else return pos; + } + function isLine(doc, l) {return l >= 0 && l < doc.size;} + + // If shift is held, this will move the selection anchor. Otherwise, + // it'll set the whole selection. + function extendSelection(cm, pos, other, bias) { + var sel = cm.view.sel; + if (sel.shift || sel.extend) { + var anchor = 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(cm, anchor, pos, bias); + } else { + setSelection(cm, pos, other || pos, bias); + } + cm.curOp.userSelChange = true; + } + + // 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(cm, anchor, head, bias, checkAtomic) { + cm.view.goalColumn = null; + var sel = cm.view.sel; + // Skip over atomic spans. + if (checkAtomic || !posEq(anchor, sel.anchor)) + anchor = skipAtomic(cm, anchor, bias, checkAtomic != "push"); + if (checkAtomic || !posEq(head, sel.head)) + head = skipAtomic(cm, 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; + + cm.curOp.updateInput = true; + cm.curOp.selectionChanged = true; + } + + function reCheckSelection(cm) { + setSelection(cm, cm.view.sel.from, cm.view.sel.to, null, "push"); + } + + function skipAtomic(cm, pos, bias, mayClear) { + var doc = cm.view.doc, flipped = false, curPos = pos; + var dir = bias || 1; + cm.view.cantEdit = false; + search: for (;;) { + var line = getLine(doc, curPos.line), toClear; + 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 && m.clearOnEnter) { + (toClear || (toClear = [])).push(m); + continue; + } else 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) newPos = clipPos(doc, {line: newPos.line - 1}); + else newPos = null; + } else if (newPos.ch > line.text.length) { + if (newPos.line < doc.size - 1) newPos = {line: newPos.line + 1, ch: 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(cm, pos, bias, true); + // Otherwise, turn off editing until further notice, and return the start of the doc + cm.view.cantEdit = true; + return {line: 0, ch: 0}; + } + flipped = true; newPos = pos; dir = -dir; + } + } + curPos = newPos; + continue search; + } + } + if (toClear) for (var i = 0; i < toClear.length; ++i) toClear[i].clear(); + } + return curPos; + } + } + + // SCROLLING + + function scrollCursorIntoView(cm) { + var view = cm.view; + var coords = scrollPosIntoView(cm, view.sel.head); + if (!view.focused) return; + var display = cm.display, box = display.sizer.getBoundingClientRect(), 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) { + for (;;) { + var changed = false, coords = cursorCoords(cm, pos); + var scrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom); + var startTop = cm.view.scrollTop, startLeft = cm.view.scrollLeft; + if (scrollPos.scrollTop != null) { + setScrollTop(cm, scrollPos.scrollTop); + if (Math.abs(cm.view.scrollTop - startTop) > 1) changed = true; + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + if (Math.abs(cm.view.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, pt = paddingTop(display); + y1 += pt; y2 += pt; + var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {}; + var docBottom = cm.view.doc.height + 2 * pt; + var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10; + if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1); + else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2) - screen; + + 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; + } + + // API UTILITIES + + function indentLine(cm, n, how, aggressive) { + var doc = cm.view.doc; + if (!how) how = "add"; + if (how == "smart") { + if (!cm.view.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.view.mode.indent(state, line.text.slice(curSpaceString.length), line.text); + if (indentation == Pass) { + if (!aggressive) return; + how = "prev"; + } + } + if (how == "prev") { + if (n) 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; + 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, indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length}, "input"); + line.stateAfter = null; + } + + function changeLine(cm, handle, op) { + var no = handle, line = handle, doc = cm.view.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(cm, dir, unit, visually) { + var doc = cm.view.doc, end = cm.view.sel.head, line = end.line, ch = end.ch; + var lineObj = getLine(doc, line); + function findNextLine() { + var l = line + dir; + if (l < 0 || l == doc.size) return 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 false; + } else ch = next; + return true; + } + if (unit == "char") moveOnce(); + else if (unit == "column") moveOnce(true); + else if (unit == "word") { + var sawWord = false; + for (;;) { + if (dir < 0) if (!moveOnce()) break; + if (isWordChar(lineObj.text.charAt(ch))) sawWord = true; + else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;} + if (dir > 0) if (!moveOnce()) break; + } + } + return skipAtomic(cm, {line: line, ch: ch}, dir, true); + } + + function findWordAt(line, pos) { + var start = pos.ch, end = pos.ch; + if (line) { + if (pos.after === false || end == line.length) --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: {line: pos.line, ch: start}, to: {line: pos.line, ch: end}}; + } + + function selectLine(cm, line) { + extendSelection(cm, {line: line, ch: 0}, clipPos(cm.view.doc, {line: line + 1, ch: 0})); + } + + // PROTOTYPE + + // The publicly visible API. Note that operation(null, f) means + // 'wrap f in an operation, performed on its `this` parameter' + + CodeMirror.prototype = { + getValue: function(lineSep) { + var text = [], doc = this.view.doc; + doc.iter(0, doc.size, function(line) { text.push(line.text); }); + return text.join(lineSep || "\n"); + }, + + setValue: operation(null, function(code) { + var doc = this.view.doc, top = {line: 0, ch: 0}, lastLen = getLine(doc, doc.size-1).text.length; + updateDocInner(this, top, {line: doc.size - 1, ch: lastLen}, splitLines(code), top, top, "setValue"); + }), + + getSelection: function(lineSep) { return this.getRange(this.view.sel.from, this.view.sel.to, lineSep); }, + + replaceSelection: operation(null, function(code, collapse, origin) { + var sel = this.view.sel; + updateDoc(this, sel.from, sel.to, splitLines(code), collapse || "around", origin); + }), + + 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];}, + + getMode: function() {return this.view.mode;}, + + addKeyMap: function(map) { + this.view.keyMaps.push(map); + }, + + removeKeyMap: function(map) { + var maps = this.view.keyMaps; + for (var i = 0; i < maps.length; ++i) + if ((typeof map == "string" ? maps[i].name : maps[i]) == 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.view.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); + this.view.modeGen++; + regChange(this, 0, this.view.doc.size); + }), + removeOverlay: operation(null, function(spec) { + var overlays = this.view.overlays; + for (var i = 0; i < overlays.length; ++i) { + if (overlays[i].modeSpec == spec) { + overlays.splice(i, 1); + this.view.modeGen++; + regChange(this, 0, this.view.doc.size); + return; + } + } + }), + + undo: operation(null, function() {unredoHelper(this, "undo");}), + redo: operation(null, function() {unredoHelper(this, "redo");}), + + indentLine: operation(null, function(n, dir, aggressive) { + if (typeof dir != "string") { + if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; + else dir = dir ? "add" : "subtract"; + } + if (isLine(this.view.doc, n)) indentLine(this, n, dir, aggressive); + }), + + indentSelection: operation(null, function(how) { + var sel = this.view.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); + }), + + historySize: function() { + var hist = this.view.history; + return {undo: hist.done.length, redo: hist.undone.length}; + }, + + clearHistory: function() {this.view.history = makeHistory();}, + + markClean: function() { + this.view.history.dirtyCounter = 0; + this.view.history.lastOp = this.view.history.lastOrigin = null; + }, + + isClean: function () {return this.view.history.dirtyCounter == 0;}, + + getHistory: function() { + var hist = this.view.history; + function cp(arr) { + for (var i = 0, nw = [], nwelt; i < arr.length; ++i) { + var set = arr[i]; + nw.push({events: nwelt = [], fromBefore: set.fromBefore, toBefore: set.toBefore, + fromAfter: set.fromAfter, toAfter: set.toAfter}); + for (var j = 0, elt = set.events; j < elt.length; ++j) { + var old = [], cur = elt[j]; + nwelt.push({start: cur.start, added: cur.added, old: old}); + for (var k = 0; k < cur.old.length; ++k) old.push(hlText(cur.old[k])); + } + } + return nw; + } + return {done: cp(hist.done), undone: cp(hist.undone)}; + }, + + setHistory: function(histData) { + var hist = this.view.history = makeHistory(); + hist.done = histData.done; + hist.undone = histData.undone; + }, + + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function(pos) { + var doc = this.view.doc; + pos = clipPos(doc, pos); + var state = getStateBefore(this, pos.line), mode = this.view.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}; + }, + + getStateAfter: function(line) { + var doc = this.view.doc; + line = clipLine(doc, line == null ? doc.size - 1: line); + return getStateBefore(this, line + 1); + }, + + cursorCoords: function(start, mode) { + var pos, sel = this.view.sel; + if (start == null) pos = sel.head; + else if (typeof start == "object") pos = clipPos(this.view.doc, start); + else pos = start ? sel.from : sel.to; + return cursorCoords(this, pos, mode || "page"); + }, + + charCoords: function(pos, mode) { + return charCoords(this, clipPos(this.view.doc, pos), mode || "page"); + }, + + coordsChar: function(coords) { + var off = this.display.lineSpace.getBoundingClientRect(); + return coordsChar(this, coords.left - off.left, coords.top - off.top); + }, + + defaultTextHeight: function() { return textHeight(this.display); }, + + markText: operation(null, function(from, to, options) { + return markText(this, clipPos(this.view.doc, from), clipPos(this.view.doc, to), + options, "range"); + }), + + setBookmark: operation(null, function(pos, widget) { + pos = clipPos(this.view.doc, pos); + return markText(this, pos, pos, widget ? {replacedWith: widget} : {}, "bookmark"); + }), + + findMarksAt: function(pos) { + var doc = this.view.doc; + pos = clipPos(doc, pos); + var markers = [], spans = getLine(doc, 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); + } + return markers; + }, + + 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 i = 0, cm = this, doc = cm.view.doc; + doc.iter(0, doc.size, 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("\\b" + cls + "\\b").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 upd = cur.replace(new RegExp("^" + cls + "\\b\\s*|\\s*\\b" + cls + "\\b"), ""); + if (upd == cur) return false; + line[prop] = upd || null; + } + return true; + }); + }), + + addLineWidget: operation(null, function(handle, node, options) { + var widget = options || {}; + widget.node = node; + if (widget.noHScroll) this.display.alignWidgets = true; + changeLine(this, handle, function(line) { + (line.widgets || (line.widgets = [])).push(widget); + widget.line = line; + return true; + }); + return widget; + }), + + removeLineWidget: operation(null, function(widget) { + var ws = widget.line.widgets, no = lineNo(widget.line); + if (no == null || !ws) return; + for (var i = 0; i < ws.length; ++i) if (ws[i] == widget) ws.splice(i--, 1); + var newHeight = widget.node.offsetHeight ? widget.line.height - widget.node.offsetHeight : textHeight(this.display); + updateLineHeight(widget.line, newHeight); + regChange(this, no, no + 1); + }), + + lineInfo: function(line) { + if (typeof line == "number") { + if (!isLine(this.view.doc, line)) return null; + var n = line; + line = getLine(this.view.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.view.doc, pos)); + var top = pos.top, left = pos.left; + node.style.position = "absolute"; + display.sizer.appendChild(node); + if (vert == "over") top = pos.top; + else if (vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.view.doc.height), + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); + if (pos.bottom + node.offsetHeight > vspace && pos.top > node.offsetHeight) + top = pos.top - node.offsetHeight; + if (left + node.offsetWidth > hspace) + left = hspace - node.offsetWidth; + } + node.style.top = (top + paddingTop(display)) + "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); + }, + + lineCount: function() {return this.view.doc.size;}, + + clipPos: function(pos) {return clipPos(this.view.doc, pos);}, + + getCursor: function(start) { + var sel = this.view.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.view.sel.from, this.view.sel.to);}, + + setCursor: operation(null, function(line, ch, extend) { + var pos = clipPos(this.view.doc, typeof line == "number" ? {line: line, ch: ch || 0} : line); + if (extend) extendSelection(this, pos); + else setSelection(this, pos, pos); + }), + + setSelection: operation(null, function(anchor, head) { + var doc = this.view.doc; + setSelection(this, clipPos(doc, anchor), clipPos(doc, head || anchor)); + }), + + extendSelection: operation(null, function(from, to) { + var doc = this.view.doc; + extendSelection(this, clipPos(doc, from), to && clipPos(doc, to)); + }), + + setExtending: function(val) {this.view.sel.extend = val;}, + + getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, + + getLineHandle: function(line) { + var doc = this.view.doc; + if (isLine(doc, line)) return getLine(doc, line); + }, + + getLineNumber: function(line) {return lineNo(line);}, + + setLine: operation(null, function(line, text) { + if (isLine(this.view.doc, line)) + replaceRange(this, text, {line: line, ch: 0}, {line: line, ch: getLine(this.view.doc, line).text.length}); + }), + + removeLine: operation(null, function(line) { + if (isLine(this.view.doc, line)) + replaceRange(this, "", {line: line, ch: 0}, clipPos(this.view.doc, {line: line+1, ch: 0})); + }), + + replaceRange: operation(null, function(code, from, to) { + var doc = this.view.doc; + from = clipPos(doc, from); + to = to ? clipPos(doc, to) : from; + return replaceRange(this, code, from, to); + }), + + getRange: function(from, to, lineSep) { + var doc = this.view.doc; + from = clipPos(doc, from); to = clipPos(doc, to); + var l1 = from.line, l2 = to.line; + if (l1 == l2) return getLine(doc, l1).text.slice(from.ch, to.ch); + var code = [getLine(doc, l1).text.slice(from.ch)]; + doc.iter(l1 + 1, l2, function(line) { code.push(line.text); }); + code.push(getLine(doc, l2).text.slice(0, to.ch)); + return code.join(lineSep || "\n"); + }, + + triggerOnKeyDown: operation(null, onKeyDown), + + execCommand: function(cmd) {return commands[cmd](this);}, + + // Stuff used by commands, probably not much use to outside code. + moveH: operation(null, function(dir, unit) { + var sel = this.view.sel, pos = dir < 0 ? sel.from : sel.to; + if (sel.shift || sel.extend || posEq(sel.from, sel.to)) + pos = findPosH(this, dir, unit, this.options.rtlMoveVisually); + extendSelection(this, pos, pos, dir); + }), + + deleteH: operation(null, function(dir, unit) { + var sel = this.view.sel; + if (!posEq(sel.from, sel.to)) replaceRange(this, "", sel.from, sel.to, "delete"); + else replaceRange(this, "", sel.from, findPosH(this, dir, unit, false), "delete"); + this.curOp.userSelChange = true; + }), + + moveV: operation(null, function(dir, unit) { + var view = this.view, doc = view.doc, display = this.display; + var cur = view.sel.head, pos = cursorCoords(this, cur, "div"); + var x = pos.left, y; + if (view.goalColumn != null) x = view.goalColumn; + if (unit == "page") { + var pageSize = Math.min(display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); + y = pos.top + dir * pageSize; + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3; + } + do { + var target = coordsChar(this, x, y); + y += dir * 5; + } while (target.outside && (dir < 0 ? y > 0 : y < doc.height)); + + if (unit == "page") display.scrollbarV.scrollTop += charCoords(this, target, "div").top - pos.top; + extendSelection(this, target, target, dir); + view.goalColumn = x; + }), + + toggleOverwrite: function() { + if (this.view.overwrite = !this.view.overwrite) + this.display.cursor.className += " CodeMirror-overwrite"; + else + this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", ""); + }, + + posFromIndex: function(off) { + var lineNo = 0, ch, doc = this.view.doc; + doc.iter(0, doc.size, function(line) { + var sz = line.text.length + 1; + if (sz > off) { ch = off; return true; } + off -= sz; + ++lineNo; + }); + return clipPos(doc, {line: lineNo, ch: ch}); + }, + indexFromPos: function (coords) { + coords = clipPos(this.view.doc, coords); + var index = coords.ch; + this.view.doc.iter(0, coords.line, function (line) { + index += line.text.length + 1; + }); + return index; + }, + + scrollTo: function(x, y) { + if (x != null) this.display.scrollbarH.scrollLeft = this.display.scroller.scrollLeft = x; + if (y != null) this.display.scrollbarV.scrollTop = this.display.scroller.scrollTop = y; + updateDisplay(this, []); + }, + 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: function(pos) { + if (typeof pos == "number") pos = {line: pos, ch: 0}; + if (!pos || pos.line != null) { + pos = pos ? clipPos(this.view.doc, pos) : this.view.sel.head; + scrollPosIntoView(this, pos); + } else { + scrollIntoView(this, pos.left, pos.top, pos.right, pos.bottom); + } + }, + + setSize: 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); + this.refresh(); + }, + + on: function(type, f) {on(this, type, f);}, + off: function(type, f) {off(this, type, f);}, + + operation: function(f){return operation(this, f)();}, + + refresh: function() { + clearCaches(this); + if (this.display.scroller.scrollHeight > this.view.scrollTop) + this.display.scrollbarV.scrollTop = this.display.scroller.scrollTop = this.view.scrollTop; + updateDisplay(this, true); + }, + + getInputField: function(){return this.display.input;}, + getWrapperElement: function(){return this.display.wrapper;}, + getScrollerElement: function(){return this.display.scroller;}, + getGutterElement: function(){return this.display.gutters;} + }; + + // 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, loadMode, true); + + option("indentUnit", 2, loadMode, true); + option("indentWithTabs", false); + option("smartIndent", true); + option("tabSize", 4, function(cm) { + loadMode(cm); + clearCaches(cm); + updateDisplay(cm, true); + }, 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("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("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("cursorHeight", 1); + option("workTime", 100); + option("workDelay", 100); + option("flattenSpans", true); + option("pollInterval", 100); + option("undoDepth", 40); + option("viewportMargin", 10, function(cm){cm.refresh();}, true); + + 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 (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) { + 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] = {}); + for (var prop in properties) if (properties.hasOwnProperty(prop)) + exts[prop] = properties[prop]; + }; + + // EXTENSIONS + + CodeMirror.defineExtension = function(name, func) { + CodeMirror.prototype[name] = func; + }; + + CodeMirror.defineOption = option; + + var initHooks = []; + CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; + + // 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); + state = info.state; + mode = info.mode; + } + return info || {mode: mode, state: state}; + }; + + // STANDARD COMMANDS + + var commands = CodeMirror.commands = { + selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});}, + 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, {line: from.line + 1, ch: 0}, "delete"); + else cm.replaceRange("", from, sel ? to : {line: from.line}, "delete"); + }, + deleteLine: function(cm) { + var l = cm.getCursor().line; + cm.replaceRange("", {line: l, ch: 0}, {line: l}, "delete"); + }, + undo: function(cm) {cm.undo();}, + redo: function(cm) {cm.redo();}, + goDocStart: function(cm) {cm.extendSelection({line: 0, ch: 0});}, + goDocEnd: function(cm) {cm.extendSelection({line: cm.lineCount() - 1});}, + 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({line: start.line, ch: inWS ? 0 : firstNonWS}); + } else cm.extendSelection(start); + }, + goLineEnd: function(cm) { + cm.extendSelection(lineEnd(cm, cm.getCursor().line)); + }, + 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");}, + 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");}, + 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), + {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: 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", "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": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delWordBefore", "Ctrl-Delete": "delWordAfter", "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": "goWordLeft", + "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordBefore", + "Ctrl-Alt-Backspace": "delWordAfter", "Alt-Delete": "delWordAfter", "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", + 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, stop) { + function lookup(map) { + map = getKeyMap(map); + var found = map[name]; + if (found === false) { + if (stop) stop(); + return true; + } + if (found != null && handle(found)) return true; + if (map.nofallthrough) { + if (stop) stop(); + return true; + } + 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) { + if (lookup(fallthrough[i])) return true; + } + return false; + } + + for (var i = 0; i < maps.length; ++i) + if (lookup(maps[i])) return true; + } + function isModifierKey(event) { + var name = keyNames[e_prop(event, "keyCode")]; + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; + } + CodeMirror.isModifierKey = isModifierKey; + + // FROMTEXTAREA + + CodeMirror.fromTextArea = function(textarea, options) { + if (!options) options = {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabindex) + options.tabindex = textarea.tabindex; + // 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) { + // Deplorable hack to make the submit method do the right thing. + on(textarea.form, "submit", save); + var form = textarea.form, realSubmit = form.submit; + try { + form.submit = function wrappedSubmit() { + 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; + } + + 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() {return countColumn(this.string, this.start, this.tabSize);}, + 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;}; + if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) { + 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(cm, type) { + this.lines = []; + this.type = type; + this.cm = cm; + } + + TextMarker.prototype.clear = function() { + if (this.explicitlyCleared) return; + startOperation(this.cm); + 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(line)) + updateLineHeight(line, textHeight(this.cm.display)); + } + if (min != null) regChange(this.cm, min, max + 1); + this.lines.length = 0; + this.explicitlyCleared = true; + if (this.collapsed && this.cm.view.cantEdit) { + this.cm.view.cantEdit = false; + reCheckSelection(this.cm); + } + endOperation(this.cm); + signalLater(this.cm, this, "clear"); + }; + + 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 = {line: found, ch: span.from}; + if (span.to != null) to = {line: found, ch: span.to}; + } + } + if (this.type == "bookmark") return from; + return from && {from: from, to: to}; + }; + + function markText(cm, from, to, options, type) { + var doc = cm.view.doc; + var marker = new TextMarker(cm, type); + if (type == "range" && !posLess(from, to)) return marker; + if (options) for (var opt in options) if (options.hasOwnProperty(opt)) + marker[opt] = options[opt]; + if (marker.replacedWith) { + marker.collapsed = true; + marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget"); + } + if (marker.collapsed) sawCollapsedSpans = true; + + var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd; + doc.iter(curLine, to.line + 1, function(line) { + 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); + if (marker.collapsed && curLine == from.line && lineIsHidden(line)) + updateLineHeight(line, 0); + ++curLine; + }); + + if (marker.readOnly) { + sawReadOnlySpans = true; + if (cm.view.history.done.length || cm.view.history.undone.length) + cm.clearHistory(); + } + if (marker.collapsed) { + if (collapsedAtStart != collapsedAtEnd) + throw new Error("Inserting collapsed marker overlapping an existing one"); + marker.size = size; + marker.atomic = true; + } + if (marker.className || marker.startStyle || marker.endStyle || marker.collapsed) + regChange(cm, from.line, to.line + 1); + if (marker.atomic) reCheckSelection(cm); + return marker; + } + + // 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.lines.push(line); + } + + function markedSpansBefore(old, startCh) { + 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) { + 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, startCh, endCh) { + 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 && span.from != startCh) { + 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 updateMarkedSpans(oldFirst, oldLast, startCh, endCh, newText) { + if (!oldFirst && !oldLast) return newText; + // Get the spans that 'stick out' on both sides + var first = markedSpansBefore(oldFirst, startCh); + var last = markedSpansAfter(oldLast, startCh, endCh); + + // Next, merge those two ends + var sameLine = newText.length == 1, offset = lst(newText).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); + } + } + } + + var newMarkers = [newHL(newText[0], first)]; + if (!sameLine) { + // Fill gap with whole-line-spans + var gap = newText.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(newHL(newText[i+1], gapMarkers)); + newMarkers.push(newHL(lst(newText), last)); + } + return newMarkers; + } + + 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 m = markers[i].find(); + for (var j = 0; j < parts.length; ++j) { + var p = parts[j]; + if (!posLess(m.from, p.to) || posLess(m.to, p.from)) continue; + var newParts = [j, 1]; + if (posLess(p.from, m.from)) newParts.push({from: p.from, to: m.from}); + if (posLess(m.to, p.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(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.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(line, sp)) + return true; + } + } + window.lineIsHidden = lineIsHidden; + function lineIsHiddenInner(line, span) { + if (span.to == null || 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.from == span.to && + (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && + lineIsHiddenInner(line, sp)) return true; + } + } + + // hl stands for history-line, a data structure that can be either a + // string (line without markers) or a {text, markedSpans} object. + function hlText(val) { return typeof val == "string" ? val : val.text; } + function hlSpans(val) { + if (typeof val == "string") return null; + var spans = val.markedSpans, out = null; + for (var i = 0; i < spans.length; ++i) { + if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } + else if (out) out.push(spans[i]); + } + return !out ? spans : out.length ? out : null; + } + function newHL(text, spans) { return spans ? {text: text, markedSpans: spans} : text; } + + function detachMarkedSpans(line) { + var spans = line.markedSpans; + if (!spans) return; + for (var i = 0; i < spans.length; ++i) { + var lines = spans[i].marker.lines; + var ix = indexOf(lines, line); + lines.splice(ix, 1); + } + line.markedSpans = null; + } + + function attachMarkedSpans(line, spans) { + if (!spans) return; + for (var i = 0; i < spans.length; ++i) + spans[i].marker.lines.push(line); + line.markedSpans = spans; + } + + // LINE DATA STRUCTURE + + // Line objects. These hold state related to a line, including + // highlighting info (the styles array). + function makeLine(text, markedSpans, height) { + var line = {text: text, height: height}; + attachMarkedSpans(line, markedSpans); + if (lineIsHidden(line)) line.height = 0; + return line; + } + + function updateLine(cm, line, text, markedSpans) { + 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); + if (lineIsHidden(line)) line.height = 0; + else if (!line.height) line.height = textHeight(cm.display); + signalLater(cm, line, "change"); + } + + 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 = cm.options.flattenSpans; + var curText = "", curStyle = null; + var stream = new StringStream(text, cm.options.tabSize); + if (text == "" && mode.blankLine) mode.blankLine(state); + while (!stream.eol()) { + var style = mode.token(stream, state); + if (stream.pos > 5000) { + // Webkit seems to refuse to render text nodes longer than 57444 characters + stream.pos = Math.min(text.length, stream.pos + 50000); + style = null; + } + var substr = stream.current(); + stream.start = stream.pos; + if (!flattenSpans || curStyle != style) { + if (curText) f(curText, curStyle); + curText = substr; curStyle = style; + } else curText = curText + substr; + } + if (curText) f(curText, curStyle); + } + + 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.view.modeGen]; + // Compute the base array of styles + runMode(cm, line.text, cm.view.mode, state, function(txt, style) {st.push(txt, style);}); + + // Run overlays, adjust style array. + for (var o = 0; o < cm.view.overlays.length; ++o) { + var overlay = cm.view.overlays[o], i = 1; + runMode(cm, line.text, overlay.mode, true, function(txt, style) { + var start = i, len = txt.length; + // Ensure there's a token end at the current position, and that i points at it + while (len) { + var cur = st[i], len_ = cur.length; + if (len_ <= len) { + len -= len_; + } else { + st.splice(i, 1, cur.slice(0, len), st[i+1], cur.slice(len)); + len = 0; + } + i += 2; + } + if (!style) return; + if (overlay.opaque) { + st.splice(start, i - start, txt, 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.view.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.view.mode; + var stream = new StringStream(line.text, cm.options.tabSize); + if (line.text == "" && mode.blankLine) mode.blankLine(state); + while (!stream.eol() && stream.pos <= 5000) { + mode.token(stream, state); + stream.start = stream.pos; + } + } + + var styleToClassCache = {}; + function styleToClass(style) { + if (!style) return null; + return styleToClassCache[style] || + (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-")); + } + + function lineContent(cm, realLine, measure) { + var merged, line = realLine, lineBefore, sawBefore, simple = true; + while (merged = collapsedSpanAtStart(line)) { + simple = false; + line = getLine(cm.view.doc, merged.find().from.line); + if (!lineBefore) lineBefore = line; + } + + var builder = {pre: elt("pre"), col: 0, pos: 0, display: !measure, + measure: null, addedOne: false, cm: cm}; + if (line.textClass) builder.pre.className = line.textClass; + + do { + builder.measure = line == realLine && measure; + builder.pos = 0; + builder.addToken = builder.measure ? buildTokenMeasure : buildToken; + if (measure && sawBefore && line != realLine && !builder.addedOne) { + measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure)); + builder.addedOne = true; + } + var next = insertLineContent(line, builder, getLineStyles(cm, line)); + sawBefore = line == lineBefore; + if (next) { + line = getLine(cm.view.doc, next.to.line); + simple = false; + } + } while (next); + + if (measure && !builder.addedOne) + measure[0] = builder.pre.appendChild(simple ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure)); + if (!builder.pre.firstChild && !lineIsHidden(realLine)) + builder.pre.appendChild(document.createTextNode("\u00a0")); + + return builder.pre; + } + + var tokenSpecialChars = /[\t\u0000-\u0019\u200b\u2028\u2029\uFEFF]/g; + function buildToken(builder, text, style, startStyle, endStyle) { + 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; + return builder.pre.appendChild(elt("span", [content], fullStyle)); + } + builder.pre.appendChild(content); + } + + function buildTokenMeasure(builder, text, style, startStyle, endStyle) { + for (var i = 0; i < text.length; ++i) { + if (i && i < text.length - 1 && + builder.cm.options.lineWrapping && + spanAffectsWrapping.test(text.slice(i - 1, i + 1))) + builder.pre.appendChild(elt("wbr")); + builder.measure[builder.pos++] = + buildToken(builder, text.charAt(i), style, + i == 0 && startStyle, i == text.length - 1 && endStyle); + } + if (text.length) builder.addedOne = true; + } + + function buildCollapsedSpan(builder, size, widget) { + if (widget) { + if (!builder.display) widget = widget.cloneNode(true); + builder.pre.appendChild(widget); + if (builder.measure && size) { + builder.measure[builder.pos] = widget; + builder.addedOne = 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; + if (!spans) { + for (var i = 1; i < styles.length; i+=2) + builder.addToken(builder, styles[i], styleToClass(styles[i+1])); + return; + } + + var allText = line.text, len = allText.length; + var pos = 0, i = 1, text = "", style; + var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed; + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = ""; + collapsed = null; nextChange = Infinity; + var foundBookmark = null; + 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.collapsed && (!collapsed || collapsed.marker.width < m.width)) + collapsed = sp; + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from; + } + if (m.type == "bookmark" && sp.from == pos && m.replacedWith) + foundBookmark = m.replacedWith; + } + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos, + collapsed.from != null && collapsed.marker.replacedWith); + if (collapsed.to == null) return collapsed.marker.find(); + } + if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark); + } + 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 + spanStyle, + spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : ""); + } + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} + pos = end; + spanStartStyle = ""; + } + text = styles[i++]; style = styleToClass(styles[i++]); + } + } + } + + // DOCUMENT DATA STRUCTURE + + 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; }, + remove: function(at, n, cm) { + for (var i = at, e = at + n; i < e; ++i) { + var line = this.lines[i]; + this.height -= line.height; + cleanUpLine(line); + signalLater(cm, line, "delete"); + } + this.lines.splice(at, n); + }, + collapse: function(lines) { + lines.splice.apply(lines, [lines.length, 0].concat(this.lines)); + }, + insertHeight: 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; }, + remove: function(at, n, callbacks) { + 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.remove(at, rm, callbacks); + 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); + }, + insert: function(at, lines) { + var height = 0; + for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height; + this.insertHeight(at, lines, height); + }, + insertHeight: 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.insertHeight(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(); + }, + iter: function(from, to, op) { this.iterN(from, to - from, op); }, + 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; + } + } + }; + + // LINE UTILITIES + + function getLine(chunk, n) { + 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 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; + } + + function lineAtHeight(chunk, h) { + var n = 0; + 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.view.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() { + 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: [], + // Used to track when changes can be merged into a single undo + // event + lastTime: 0, lastOp: null, lastOrigin: null, + // Used by the isClean() method + dirtyCounter: 0 + }; + } + + function addChange(cm, start, added, old, origin, fromBefore, toBefore, fromAfter, toAfter) { + var history = cm.view.history; + history.undone.length = 0; + var time = +new Date, cur = lst(history.done); + + if (cur && + (history.lastOp == cm.curOp.id || + history.lastOrigin == origin && (origin == "input" || origin == "delete") && + history.lastTime > time - 600)) { + // Merge this change into the last event + var last = lst(cur.events); + if (last.start > start + old.length || last.start + last.added < start) { + // Doesn't intersect with last sub-event, add new sub-event + cur.events.push({start: start, added: added, old: old}); + } else { + // Patch up the last sub-event + var startBefore = Math.max(0, last.start - start), + endAfter = Math.max(0, (start + old.length) - (last.start + last.added)); + for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]); + for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]); + if (startBefore) last.start = start; + last.added += added - (old.length - startBefore - endAfter); + } + cur.fromAfter = fromAfter; cur.toAfter = toAfter; + } else { + // Can not be merged, start a new event. + cur = {events: [{start: start, added: added, old: old}], + fromBefore: fromBefore, toBefore: toBefore, fromAfter: fromAfter, toAfter: toAfter}; + history.done.push(cur); + while (history.done.length > cm.options.undoDepth) + history.done.shift(); + if (history.dirtyCounter < 0) + // The user has made a change after undoing past the last clean state. + // We can never get back to a clean state now until markClean() is called. + history.dirtyCounter = NaN; + else + history.dirtyCounter++; + } + history.lastTime = time; + history.lastOp = cm.curOp.id; + history.lastOrigin = origin; + } + + // 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_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; + } + + // Allow 3rd-party code to override event properties by adding an override + // object to an event object. + function e_prop(e, prop) { + var overridden = e.override && e.override.hasOwnProperty(prop); + return overridden ? e.override[prop] : e[prop]; + } + + // 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); + } + + function signalLater(cm, emitter, type /*, values...*/) { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + var args = Array.prototype.slice.call(arguments, 3), flist = cm.curOp && cm.curOp.delayedCallbacks; + function bnd(f) {return function(){f.apply(null, args);};}; + for (var i = 0; i < arr.length; ++i) + if (flist) flist.push(bnd(arr[i])); + else arr[i].apply(null, args); + } + + 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; + + // 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) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) end = string.length; + } + for (var i = 0, n = 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 node.select(); + } + + 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 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]/; + function isWordChar(ch) { + return /\w/.test(ch) || ch > "\x80" && + (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); + } + + function isEmpty(obj) { + var c = 0; + for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) ++c; + return !c; + } + + 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]/; + + // 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) { + e.innerHTML = ""; + 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; + } + + // 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 regexps matches the + // character combinations that suffer from this phenomenon on the + // various browsers. + var spanAffectsWrapping = /^$/; // Won't match any two-character string + if (gecko) spanAffectsWrapping = /$'/; + else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/; + else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/; + + 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"); + 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"); + } + } + + 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.view.doc, lineN); + var visual = visualLine(cm.view.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 {line: lineN, ch: ch}; + } + function lineEnd(cm, lineNo) { + var merged, line; + while (merged = collapsedSpanAtEnd(line = getLine(cm.view.doc, lineNo))) + lineNo = merged.find().to.line; + var order = getOrder(line); + var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); + return {line: lineNo, ch: ch}; + } + + // 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 moveOneUnit = byUnit ? function(pos, dir) { + do pos += dir; + while (pos > 0 && isExtendingChar.test(line.text.charAt(pos))); + return pos; + } : function(pos, dir) { return pos + dir; }; + var linedir = bidi[0].level; + for (var i = 0; i < bidi.length; ++i) { + var part = bidi[i], sticky = part.level % 2 == linedir; + if ((part.from < start && part.to > start) || + (sticky && (part.from == start || part.to == start))) break; + } + var target = moveOneUnit(start, part.level % 2 ? -dir : dir); + + while (target != null) { + if (part.level % 2 == linedir) { + if (target < part.from || target > part.to) { + part = bidi[i += dir]; + target = part && (dir > 0 == part.level % 2 ? moveOneUnit(part.to, -1) : moveOneUnit(part.from, 1)); + } else break; + } else { + if (target == bidiLeft(part)) { + part = bidi[--i]; + target = part && bidiRight(part); + } else if (target == bidiRight(part)) { + part = bidi[++i]; + target = part && bidiLeft(part); + } else break; + } + } + + return target < 0 || target > line.text.length ? null : target; + } + + 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 charOrdering(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.0 +"; + + return CodeMirror; +})(); diff --git a/codemirror/lib/util/closetag.js b/codemirror/lib/util/closetag.js new file mode 100644 index 0000000..7320c17 --- /dev/null +++ b/codemirror/lib/util/closetag.js @@ -0,0 +1,85 @@ +/** + * 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) { autoCloseTag(cm, '/'); }; + if (typeof val != "object" || val.whenOpening) + map["'>'"] = function(cm) { autoCloseTag(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 autoCloseTag(cm, ch) { + var pos = cm.getCursor(), tok = cm.getTokenAt(pos); + var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state; + if (inner.mode.name != "xml") throw 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); + + if (ch == ">" && state.tagName) { + 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" || + /\/\s*$/.test(tok.string) || + dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1) + throw CodeMirror.Pass; + + var doIndent = indentTags && indexOf(indentTags, lowerTagName) > -1; + cm.replaceSelection(">" + (doIndent ? "\n\n" : "") + "", + doIndent ? {line: pos.line + 1, ch: 0} : {line: pos.line, ch: pos.ch + 1}); + if (doIndent) { + cm.indentLine(pos.line + 1); + cm.indentLine(pos.line + 2); + } + return; + } else if (ch == "/" && tok.type == "tag" && tok.string == "<") { + var tagName = state.context && state.context.tagName; + if (tagName) cm.replaceSelection("/" + tagName + ">", "end"); + return; + } + throw CodeMirror.Pass; + } + + 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; + } +})(); diff --git a/codemirror/lib/util/colorize.js b/codemirror/lib/util/colorize.js new file mode 100644 index 0000000..62286d2 --- /dev/null +++ b/codemirror/lib/util/colorize.js @@ -0,0 +1,29 @@ +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"; + } + }; +})(); diff --git a/codemirror/lib/util/continuecomment.js b/codemirror/lib/util/continuecomment.js new file mode 100644 index 0000000..dac83a8 --- /dev/null +++ b/codemirror/lib/util/continuecomment.js @@ -0,0 +1,36 @@ +(function() { + var modes = ["clike", "css", "javascript"]; + for (var i = 0; i < modes.length; ++i) + CodeMirror.extendMode(modes[i], {blockCommentStart: "/*", + blockCommentEnd: "*/", + blockCommentContinue: " * "}); + + CodeMirror.commands.newlineAndIndentContinueComment = function(cm) { + var pos = cm.getCursor(), token = cm.getTokenAt(pos); + var mode = CodeMirror.innerMode(cm.getMode(), token.state).mode; + var space; + + if (token.type == "comment" && mode.blockCommentStart) { + var end = token.string.indexOf(mode.blockCommentEnd); + var full = cm.getRange({line: pos.line, ch: 0}, {line: pos.line, ch: 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) { + space = full.slice(0, token.start); + if (!/^\s*$/.test(space)) { + space = ""; + for (var i = 0; i < token.start; ++i) space += " "; + } + } else if ((found = full.indexOf(mode.blockCommentContinue)) != -1 && + found + mode.blockCommentContinue.length > token.start && + /^\s*$/.test(full.slice(0, found))) { + space = full.slice(0, found); + } + } + + if (space != null) + cm.replaceSelection("\n" + space + mode.blockCommentContinue, "end"); + else + cm.execCommand("newlineAndIndent"); + }; +})(); diff --git a/codemirror/lib/util/continuelist.js b/codemirror/lib/util/continuelist.js new file mode 100644 index 0000000..33b343b --- /dev/null +++ b/codemirror/lib/util/continuelist.js @@ -0,0 +1,28 @@ +(function() { + CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) { + var pos = cm.getCursor(), token = cm.getTokenAt(pos); + var space; + if (token.className == "string") { + var full = cm.getRange({line: pos.line, ch: 0}, {line: pos.line, ch: token.end}); + var listStart = /\*|\d+\./, listContinue; + if (token.string.search(listStart) == 0) { + var reg = /^[\W]*(\d+)\./g; + var matches = reg.exec(full); + if(matches) + listContinue = (parseInt(matches[1]) + 1) + ". "; + else + listContinue = "* "; + space = full.slice(0, token.start); + if (!/^\s*$/.test(space)) { + space = ""; + for (var i = 0; i < token.start; ++i) space += " "; + } + } + } + + if (space != null) + cm.replaceSelection("\n" + space + listContinue, "end"); + else + cm.execCommand("newlineAndIndent"); + }; +})(); diff --git a/codemirror/lib/util/dialog.css b/codemirror/lib/util/dialog.css new file mode 100644 index 0000000..2e7c0fc --- /dev/null +++ b/codemirror/lib/util/dialog.css @@ -0,0 +1,32 @@ +.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%; +} diff --git a/codemirror/lib/util/dialog.js b/codemirror/lib/util/dialog.js new file mode 100644 index 0000000..e113f7c --- /dev/null +++ b/codemirror/lib/util/dialog.js @@ -0,0 +1,76 @@ +// 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 (e.keyCode == 13 || e.keyCode == 27) { + CodeMirror.e_stop(e); + close(); + me.focus(); + if (e.keyCode == 13) callback(inp.value); + } + }); + 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; }); + } + }); +})(); diff --git a/codemirror/lib/util/foldcode.js b/codemirror/lib/util/foldcode.js new file mode 100644 index 0000000..407bac2 --- /dev/null +++ b/codemirror/lib/util/foldcode.js @@ -0,0 +1,182 @@ +// the tagRangeFinder function is +// Copyright (C) 2011 by Daniel Glazman +// released under the MIT license (../../LICENSE) like the rest of CodeMirror +CodeMirror.tagRangeFinder = function(cm, start) { + 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 xmlNAMERegExp = new RegExp("^[" + nameStartChar + "][" + nameChar + "]*"); + + var lineText = cm.getLine(start.line); + var found = false; + var tag = null; + var pos = start.ch; + while (!found) { + pos = lineText.indexOf("<", pos); + if (-1 == pos) // no tag on line + return; + if (pos + 1 < lineText.length && lineText[pos + 1] == "/") { // closing tag + pos++; + continue; + } + // ok we seem to have a start tag + if (!lineText.substr(pos + 1).match(xmlNAMERegExp)) { // not a tag name... + pos++; + continue; + } + var gtPos = lineText.indexOf(">", pos + 1); + if (-1 == gtPos) { // end of start tag not in line + var l = start.line + 1; + var foundGt = false; + var lastLine = cm.lineCount(); + while (l < lastLine && !foundGt) { + var lt = cm.getLine(l); + gtPos = lt.indexOf(">"); + if (-1 != gtPos) { // found a > + foundGt = true; + var slash = lt.lastIndexOf("/", gtPos); + if (-1 != slash && slash < gtPos) { + var str = lineText.substr(slash, gtPos - slash + 1); + if (!str.match( /\/\s*\>/ )) // yep, that's the end of empty tag + return; + } + } + l++; + } + found = true; + } + else { + var slashPos = lineText.lastIndexOf("/", gtPos); + if (-1 == slashPos) { // cannot be empty tag + found = true; + // don't continue + } + else { // empty tag? + // check if really empty tag + var str = lineText.substr(slashPos, gtPos - slashPos + 1); + if (!str.match( /\/\s*\>/ )) { // finally not empty + found = true; + // don't continue + } + } + } + if (found) { + var subLine = lineText.substr(pos + 1); + tag = subLine.match(xmlNAMERegExp); + if (tag) { + // we have an element name, wooohooo ! + tag = tag[0]; + // do we have the close tag on same line ??? + if (-1 != lineText.indexOf("", pos)) // yep + { + found = false; + } + // we don't, so we have a candidate... + } + else + found = false; + } + if (!found) + pos++; + } + + if (found) { + var startTag = "(\\<\\/" + tag + "\\>)|(\\<" + tag + "\\>)|(\\<" + tag + "\\s)|(\\<" + tag + "$)"; + var startTagRegExp = new RegExp(startTag); + var endTag = ""; + var depth = 1; + var l = start.line + 1; + var lastLine = cm.lineCount(); + while (l < lastLine) { + lineText = cm.getLine(l); + var match = lineText.match(startTagRegExp); + if (match) { + for (var i = 0; i < match.length; i++) { + if (match[i] == endTag) + depth--; + else + depth++; + if (!depth) return {from: {line: start.line, ch: gtPos + 1}, + to: {line: l, ch: match.index}}; + } + } + l++; + } + return; + } +}; + +CodeMirror.braceRangeFinder = function(cm, start) { + var line = start.line, lineText = cm.getLine(line); + var at = lineText.length, startChar, tokenType; + for (;;) { + var found = lineText.lastIndexOf("{", at); + if (found < start.ch) break; + tokenType = cm.getTokenAt({line: line, ch: found}).type; + if (!/^(comment|string)/.test(tokenType)) { startChar = found; break; } + at = found - 1; + } + if (startChar == null || lineText.lastIndexOf("}") > startChar) return; + var count = 1, lastLine = cm.lineCount(), end, endCh; + outer: for (var i = line + 1; i < lastLine; ++i) { + var text = cm.getLine(i), pos = 0; + for (;;) { + var nextOpen = text.indexOf("{", pos), nextClose = text.indexOf("}", 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.getTokenAt({line: i, ch: pos + 1}).type == tokenType) { + if (pos == nextOpen) ++count; + else if (!--count) { end = i; endCh = pos; break outer; } + } + ++pos; + } + } + if (end == null || end == line + 1) return; + return {from: {line: line, ch: startChar + 1}, + to: {line: end, ch: endCh}}; +}; + +CodeMirror.indentRangeFinder = function(cm, start) { + var tabSize = cm.getOption("tabSize"), firstLine = cm.getLine(start.line); + var myIndent = CodeMirror.countColumn(firstLine, null, tabSize); + for (var i = start.line + 1, end = cm.lineCount(); i < end; ++i) { + var curLine = cm.getLine(i); + if (CodeMirror.countColumn(curLine, null, tabSize) < myIndent) + return {from: {line: start.line, ch: firstLine.length}, + to: {line: i, ch: curLine.length}}; + } +}; + +CodeMirror.newFoldFunction = function(rangeFinder, widget) { + if (widget == null) widget = "\u2194"; + if (typeof widget == "string") { + var text = document.createTextNode(widget); + widget = document.createElement("span"); + widget.appendChild(text); + widget.className = "CodeMirror-foldmarker"; + } + + return function(cm, pos) { + if (typeof pos == "number") pos = {line: pos, ch: 0}; + var range = rangeFinder(cm, pos); + if (!range) return; + + var present = cm.findMarksAt(range.from), cleared = 0; + for (var i = 0; i < present.length; ++i) { + if (present[i].__isFold) { + ++cleared; + present[i].clear(); + } + } + if (cleared) return; + + var myWidget = widget.cloneNode(true); + CodeMirror.on(myWidget, "mousedown", function() {myRange.clear();}); + var myRange = cm.markText(range.from, range.to, { + replacedWith: myWidget, + clearOnEnter: true, + __isFold: true + }); + }; +}; diff --git a/codemirror/lib/util/formatting.js b/codemirror/lib/util/formatting.js new file mode 100644 index 0000000..ccf2a9a --- /dev/null +++ b/codemirror/lib/util/formatting.js @@ -0,0 +1,108 @@ +(function() { + + CodeMirror.extendMode("css", { + commentStart: "/*", + commentEnd: "*/", + newlineAfterToken: function(_type, content) { + return /^[;{}]$/.test(content); + } + }); + + CodeMirror.extendMode("javascript", { + commentStart: "/*", + commentEnd: "*/", + // FIXME semicolons inside of for + newlineAfterToken: function(_type, content, textAfter, state) { + if (this.jsonMode) { + return /^[\[,{]$/.test(content) || /^}/.test(textAfter); + } else { + if (content == ";" && state.lexical && state.lexical.type == ")") return false; + return /^[;{}]$/.test(content) && !/^;/.test(textAfter); + } + } + }); + + CodeMirror.extendMode("xml", { + commentStart: "", + newlineAfterToken: function(type, content, textAfter) { + return type == "tag" && />$/.test(content) || /^ -1 && endIndex > -1 && endIndex > startIndex) { + // Take string till comment start + selText = selText.substr(0, startIndex) + // From comment start till comment end + + selText.substring(startIndex + curMode.commentStart.length, endIndex) + // From comment end till string end + + selText.substr(endIndex + curMode.commentEnd.length); + } + cm.replaceRange(selText, from, to); + } + }); + }); + + // Applies automatic mode-aware indentation to the specified range + CodeMirror.defineExtension("autoIndentRange", function (from, to) { + var cmInstance = this; + this.operation(function () { + for (var i = from.line; i <= to.line; i++) { + cmInstance.indentLine(i, "smart"); + } + }); + }); + + // Applies automatic formatting to the specified range + CodeMirror.defineExtension("autoFormatRange", function (from, to) { + var cm = this; + var outer = cm.getMode(), text = cm.getRange(from, to).split("\n"); + var state = CodeMirror.copyState(outer, cm.getTokenAt(from).state); + var tabSize = cm.getOption("tabSize"); + + var out = "", lines = 0, atSol = from.ch == 0; + function newline() { + out += "\n"; + atSol = true; + ++lines; + } + + for (var i = 0; i < text.length; ++i) { + var stream = new CodeMirror.StringStream(text[i], tabSize); + while (!stream.eol()) { + var inner = CodeMirror.innerMode(outer, state); + var style = outer.token(stream, state), cur = stream.current(); + stream.start = stream.pos; + if (!atSol || /\S/.test(cur)) { + out += cur; + atSol = false; + } + if (!atSol && inner.mode.newlineAfterToken && + inner.mode.newlineAfterToken(style, cur, stream.string.slice(stream.pos) || text[i+1] || "", inner.state)) + newline(); + } + if (!stream.pos && outer.blankLine) outer.blankLine(state); + if (!atSol) newline(); + } + + cm.operation(function () { + cm.replaceRange(out, from, to); + for (var cur = from.line + 1, end = from.line + lines; cur <= end; ++cur) + cm.indentLine(cur, "smart"); + cm.setSelection(from, cm.getCursor(false)); + }); + }); +})(); diff --git a/codemirror/lib/util/javascript-hint.js b/codemirror/lib/util/javascript-hint.js new file mode 100644 index 0000000..be6098e --- /dev/null +++ b/codemirror/lib/util/javascript-hint.js @@ -0,0 +1,138 @@ +(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, options) { + // 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, + 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, {line: cur.line, ch: tprop.start}); + if (tprop.string != ".") return; + tprop = getToken(editor, {line: cur.line, ch: tprop.start}); + if (tprop.string == ')') { + var level = 1; + do { + tprop = getToken(editor, {line: cur.line, ch: tprop.start}); + switch (tprop.string) { + case ')': level++; break; + case '(': level--; break; + default: break; + } + } while (level > 0); + tprop = getToken(editor, {line: cur.line, ch: tprop.start}); + if (tprop.type == 'variable') + tprop.type = 'function'; + else return; // no clue + } + if (!context) var context = []; + context.push(tprop); + } + return {list: getCompletions(token, context, keywords, options), + from: {line: cur.line, ch: token.start}, + to: {line: cur.line, ch: token.end}}; + } + + CodeMirror.javascriptHint = function(editor, options) { + return scriptHint(editor, javascriptKeywords, + function (e, cur) {return e.getTokenAt(cur);}, + options); + }; + + 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; + } + + CodeMirror.coffeescriptHint = function(editor, options) { + return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken, options); + }; + + 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) { + // 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") { + 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; + } +})(); diff --git a/codemirror/lib/util/loadmode.js b/codemirror/lib/util/loadmode.js new file mode 100644 index 0000000..60fafbb --- /dev/null +++ b/codemirror/lib/util/loadmode.js @@ -0,0 +1,51 @@ +(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")); + }); + }; +}()); diff --git a/codemirror/lib/util/match-highlighter.js b/codemirror/lib/util/match-highlighter.js new file mode 100644 index 0000000..bb93ebc --- /dev/null +++ b/codemirror/lib/util/match-highlighter.js @@ -0,0 +1,46 @@ +// Define match-highlighter commands. Depends on searchcursor.js +// Use by attaching the following function call to the cursorActivity event: + //myCodeMirror.matchHighlight(minChars); +// And including a special span.CodeMirror-matchhighlight css class (also optionally a separate one for .CodeMirror-focused -- see demo matchhighlighter.html) + +(function() { + var DEFAULT_MIN_CHARS = 2; + + function MatchHighlightState() { + this.marked = []; + } + function getMatchHighlightState(cm) { + return cm._matchHighlightState || (cm._matchHighlightState = new MatchHighlightState()); + } + + function clearMarks(cm) { + var state = getMatchHighlightState(cm); + for (var i = 0; i < state.marked.length; ++i) + state.marked[i].clear(); + state.marked = []; + } + + function markDocument(cm, className, minChars) { + clearMarks(cm); + minChars = (typeof minChars !== 'undefined' ? minChars : DEFAULT_MIN_CHARS); + if (cm.somethingSelected() && cm.getSelection().replace(/^\s+|\s+$/g, "").length >= minChars) { + var state = getMatchHighlightState(cm); + var query = cm.getSelection(); + cm.operation(function() { + if (cm.lineCount() < 2000) { // This is too expensive on big documents. + for (var cursor = cm.getSearchCursor(query); cursor.findNext();) { + //Only apply matchhighlight to the matches other than the one actually selected + if (cursor.from().line !== cm.getCursor(true).line || + cursor.from().ch !== cm.getCursor(true).ch) + state.marked.push(cm.markText(cursor.from(), cursor.to(), + {className: className})); + } + } + }); + } + } + + CodeMirror.defineExtension("matchHighlight", function(className, minChars) { + markDocument(this, className, minChars); + }); +})(); diff --git a/codemirror/lib/util/matchbrackets.js b/codemirror/lib/util/matchbrackets.js new file mode 100644 index 0000000..2df2fbb --- /dev/null +++ b/codemirror/lib/util/matchbrackets.js @@ -0,0 +1,63 @@ +(function() { + var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"}; + function findMatchingBracket(cm) { + var cur = 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; + var style = cm.getTokenAt({line: cur.line, ch: pos + 1}).type; + + 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 (start != null) pos = start + d; + for (; pos != end; pos += d) { + var ch = line.text.charAt(pos); + if (re.test(ch) && cm.getTokenAt({line: lineNo, ch: pos + 1}).type == 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: {line: cur.line, ch: pos}, to: found && {line: i, ch: found.pos}, match: found && found.match}; + } + + function matchBrackets(cm, autoclear) { + var found = findMatchingBracket(cm); + if (!found) return; + var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; + var one = cm.markText(found.from, {line: found.from.line, ch: found.from.ch + 1}, + {className: style}); + var two = found.to && cm.markText(found.to, {line: found.to.line, ch: found.to.ch + 1}, + {className: style}); + 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) { + if (val) cm.on("cursorActivity", doMatchBrackets); + else cm.off("cursorActivity", doMatchBrackets); + }); + + CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);}); + CodeMirror.defineExtension("findMatchingBracket", function(){return findMatchingBracket(this);}); +})(); diff --git a/codemirror/lib/util/multiplex.js b/codemirror/lib/util/multiplex.js new file mode 100644 index 0000000..e77ff2a --- /dev/null +++ b/codemirror/lib/util/multiplex.js @@ -0,0 +1,95 @@ +CodeMirror.multiplexingMode = function(outer /*, others */) { + // Others should be {open, close, mode [, delimStyle]} 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); + 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 (mode.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}; + } + }; +}; diff --git a/codemirror/lib/util/overlay.js b/codemirror/lib/util/overlay.js new file mode 100644 index 0000000..fba3898 --- /dev/null +++ b/codemirror/lib/util/overlay.js @@ -0,0 +1,59 @@ +// 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); + } + }; +}; diff --git a/codemirror/lib/util/pig-hint.js b/codemirror/lib/util/pig-hint.js new file mode 100644 index 0000000..149b468 --- /dev/null +++ b/codemirror/lib/util/pig-hint.js @@ -0,0 +1,117 @@ +(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 == ":" ? "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: {line: cur.line, ch: token.start}, + to: {line: cur.line, ch: token.end}}; + } + + CodeMirror.pigHint = function(editor) { + return scriptHint(editor, pigKeywordsU, function (e, cur) {return e.getTokenAt(cur);}); + }; + + 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; + } +})(); diff --git a/codemirror/lib/util/runmode-standalone.js b/codemirror/lib/util/runmode-standalone.js new file mode 100644 index 0000000..afdf044 --- /dev/null +++ b/codemirror/lib/util/runmode-standalone.js @@ -0,0 +1,90 @@ +/* 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") { + function cased(str) {return caseInsensitive ? str.toLowerCase() : str;} + if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) { + if (consume !== false) this.pos += pattern.length; + return true; + } + } + else { + var match = this.string.slice(this.pos).match(pattern); + 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) { modes[name] = mode; }; +exports.defineMIME = function(mime, spec) { mimeModes[mime] = spec; }; +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); + stream.start = stream.pos; + } + } +}; diff --git a/codemirror/lib/util/runmode.js b/codemirror/lib/util/runmode.js new file mode 100644 index 0000000..3e1bed7 --- /dev/null +++ b/codemirror/lib/util/runmode.js @@ -0,0 +1,52 @@ +CodeMirror.runMode = function(string, modespec, callback, options) { + var mode = CodeMirror.getMode(CodeMirror.defaults, modespec); + + 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") { + 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 = 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); + stream.start = stream.pos; + } + } +}; diff --git a/codemirror/lib/util/search.js b/codemirror/lib/util/search.js new file mode 100644 index 0000000..ab0cb20 --- /dev/null +++ b/codemirror/lib/util/search.js @@ -0,0 +1,131 @@ +// 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._searchState || (cm._searchState = 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(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 ? {line: cm.lineCount() - 1} : {line: 0, ch: 0}); + if (!cursor.find(rev)) return; + } + cm.setSelection(cursor.from(), 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()); + function advance() { + 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()); + confirmDialog(cm, doReplaceConfirm, "Replace?", + [function() {doReplace(match);}, advance]); + } + function doReplace(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);}; +})(); diff --git a/codemirror/lib/util/searchcursor.js b/codemirror/lib/util/searchcursor.js new file mode 100644 index 0000000..58fed74 --- /dev/null +++ b/codemirror/lib/util/searchcursor.js @@ -0,0 +1,119 @@ +(function(){ + function SearchCursor(cm, query, pos, caseFold) { + this.atOccurrence = false; this.cm = cm; + if (caseFold == null && typeof query == "string") caseFold = false; + + pos = pos ? cm.clipPos(pos) : {line: 0, ch: 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 = cm.getLine(pos.line).slice(0, pos.ch), match = query.exec(line), start = 0; + while (match) { + start += match.index + 1; + line = line.slice(start); + query.lastIndex = 0; + var newmatch = query.exec(line); + if (newmatch) match = newmatch; + else break; + } + start--; + } else { + query.lastIndex = pos.ch; + var line = cm.getLine(pos.line), match = query.exec(line), + start = match && match.index; + } + if (match) + return {from: {line: pos.line, ch: start}, + to: {line: pos.line, ch: start + match[0].length}, + 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) + this.matches = function(reverse, pos) { + var line = fold(cm.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: {line: pos.line, ch: match}, + to: {line: pos.line, ch: match + len}}; + }; + else + this.matches = function(reverse, pos) { + var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(cm.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 == cm.lineCount() - 1) return; + line = fold(cm.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 = {line: pos.line, ch: offsetA}, end = {line: ln, ch: 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.cm.clipPos(reverse ? this.pos.from : this.pos.to); + function savePosAndFail(line) { + var pos = {line: line, ch: 0}; + self.pos = {from: pos, to: pos}; + self.atOccurrence = false; + return false; + } + + for (;;) { + if (this.pos = this.matches(reverse, pos)) { + this.atOccurrence = true; + return this.pos.match || true; + } + if (reverse) { + if (!pos.line) return savePosAndFail(0); + pos = {line: pos.line-1, ch: this.cm.getLine(pos.line-1).length}; + } + else { + var maxLine = this.cm.lineCount(); + if (pos.line == maxLine - 1) return savePosAndFail(maxLine); + pos = {line: pos.line+1, ch: 0}; + } + } + }, + + from: function() {if (this.atOccurrence) return this.pos.from;}, + to: function() {if (this.atOccurrence) return this.pos.to;}, + + replace: function(newText) { + var self = this; + if (this.atOccurrence) + self.pos.to = this.cm.replaceRange(newText, self.pos.from, self.pos.to); + } + }; + + CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) { + return new SearchCursor(this, query, pos, caseFold); + }); +})(); diff --git a/codemirror/lib/util/simple-hint.css b/codemirror/lib/util/simple-hint.css new file mode 100644 index 0000000..4387cb9 --- /dev/null +++ b/codemirror/lib/util/simple-hint.css @@ -0,0 +1,16 @@ +.CodeMirror-completions { + position: absolute; + z-index: 10; + overflow: hidden; + -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); +} +.CodeMirror-completions select { + background: #fafafa; + outline: none; + border: none; + padding: 0; + margin: 0; + font-family: monospace; +} diff --git a/codemirror/lib/util/simple-hint.js b/codemirror/lib/util/simple-hint.js new file mode 100644 index 0000000..1565bd4 --- /dev/null +++ b/codemirror/lib/util/simple-hint.js @@ -0,0 +1,102 @@ +(function() { + CodeMirror.simpleHint = function(editor, getHints, givenOptions) { + // Determine effective options based on given values and defaults. + var options = {}, defaults = CodeMirror.simpleHint.defaults; + for (var opt in defaults) + if (defaults.hasOwnProperty(opt)) + options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt]; + + function collectHints(previousToken) { + // We want a single cursor position. + if (editor.somethingSelected()) return; + + var tempToken = editor.getTokenAt(editor.getCursor()); + + // Don't show completions if token has changed and the option is set. + if (options.closeOnTokenChange && previousToken != null && + (tempToken.start != previousToken.start || tempToken.type != previousToken.type)) { + return; + } + + var result = getHints(editor, givenOptions); + if (!result || !result.list.length) return; + var completions = result.list; + function insert(str) { + editor.replaceRange(str, result.from, result.to); + } + // When there is only one completion, use it directly. + if (options.completeSingle && completions.length == 1) { + insert(completions[0]); + return true; + } + + // Build the select widget + var complete = document.createElement("div"); + complete.className = "CodeMirror-completions"; + var sel = complete.appendChild(document.createElement("select")); + // Opera doesn't move the selection when pressing up/down in a + // multi-select, but it does properly support the size property on + // single-selects, so no multi-select is necessary. + if (!window.opera) sel.multiple = true; + for (var i = 0; i < completions.length; ++i) { + var opt = sel.appendChild(document.createElement("option")); + opt.appendChild(document.createTextNode(completions[i])); + } + sel.firstChild.selected = true; + sel.size = Math.min(10, completions.length); + var pos = editor.cursorCoords(options.alignWithWord ? result.from : null); + complete.style.left = pos.left + "px"; + complete.style.top = pos.bottom + "px"; + document.body.appendChild(complete); + // 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); + if(winW - pos.left < sel.clientWidth) + complete.style.left = (pos.left - sel.clientWidth) + "px"; + // Hack to hide the scrollbar. + if (completions.length <= 10) + complete.style.width = (sel.clientWidth - 1) + "px"; + + var done = false; + function close() { + if (done) return; + done = true; + complete.parentNode.removeChild(complete); + } + function pick() { + insert(completions[sel.selectedIndex]); + close(); + setTimeout(function(){editor.focus();}, 50); + } + CodeMirror.on(sel, "blur", close); + CodeMirror.on(sel, "keydown", function(event) { + var code = event.keyCode; + // Enter + if (code == 13) {CodeMirror.e_stop(event); pick();} + // Escape + else if (code == 27) {CodeMirror.e_stop(event); close(); editor.focus();} + else if (code != 38 && code != 40 && code != 33 && code != 34 && !CodeMirror.isModifierKey(event)) { + close(); editor.focus(); + // Pass the event to the CodeMirror instance so that it can handle things like backspace properly. + editor.triggerOnKeyDown(event); + // Don't show completions if the code is backspace and the option is set. + if (!options.closeOnBackspace || code != 8) { + setTimeout(function(){collectHints(tempToken);}, 50); + } + } + }); + CodeMirror.on(sel, "dblclick", pick); + + sel.focus(); + // Opera sometimes ignores focusing a freshly created node + if (window.opera) setTimeout(function(){if (!done) sel.focus();}, 100); + return true; + } + return collectHints(); + }; + CodeMirror.simpleHint.defaults = { + closeOnBackspace: true, + closeOnTokenChange: false, + completeSingle: true, + alignWithWord: true + }; +})(); diff --git a/codemirror/lib/util/xml-hint.js b/codemirror/lib/util/xml-hint.js new file mode 100644 index 0000000..e9ec6b7 --- /dev/null +++ b/codemirror/lib/util/xml-hint.js @@ -0,0 +1,131 @@ + +(function() { + + CodeMirror.xmlHints = []; + + CodeMirror.xmlHint = function(cm, simbol) { + + if(simbol.length > 0) { + var cursor = cm.getCursor(); + cm.replaceSelection(simbol); + cursor = {line: cursor.line, ch: cursor.ch + 1}; + cm.setCursor(cursor); + } + + CodeMirror.simpleHint(cm, getHint); + }; + + var getHint = function(cm) { + + var cursor = cm.getCursor(); + + if (cursor.ch > 0) { + + var text = cm.getRange({line: 0, ch: 0}, cursor); + var typed = ''; + var simbol = ''; + for(var i = text.length - 1; i >= 0; i--) { + if(text[i] == ' ' || text[i] == '<') { + simbol = text[i]; + break; + } + else { + typed = text[i] + typed; + } + } + + text = text.slice(0, text.length - typed.length); + + var path = getActiveElement(text) + simbol; + var hints = CodeMirror.xmlHints[path]; + + if(typeof hints === 'undefined') + hints = ['']; + else { + hints = hints.slice(0); + for (var i = hints.length - 1; i >= 0; i--) { + if(hints[i].indexOf(typed) != 0) + hints.splice(i, 1); + } + } + + return { + list: hints, + from: { line: cursor.line, ch: cursor.ch - typed.length }, + to: cursor + }; + }; + }; + + var getActiveElement = function(text) { + + var element = ''; + + if(text.length >= 0) { + + var regex = new RegExp('<([^!?][^\\s/>]*).*?>', 'g'); + + var matches = []; + var match; + while ((match = regex.exec(text)) != null) { + matches.push({ + tag: match[1], + selfclose: (match[0].slice(match[0].length - 2) === '/>') + }); + } + + for (var i = matches.length - 1, skip = 0; i >= 0; i--) { + + var item = matches[i]; + + if (item.tag[0] == '/') + { + skip++; + } + else if (item.selfclose == false) + { + if (skip > 0) + { + skip--; + } + else + { + element = '<' + item.tag + '>' + element; + } + } + } + + element += getOpenTag(text); + } + + return element; + }; + + var getOpenTag = function(text) { + + var open = text.lastIndexOf('<'); + var close = text.lastIndexOf('>'); + + if (close < open) + { + text = text.slice(open); + + if(text != '<') { + + var space = text.indexOf(' '); + if(space < 0) + space = text.indexOf('\t'); + if(space < 0) + space = text.indexOf('\n'); + + if (space < 0) + space = text.length; + + return text.slice(0, space); + } + } + + return ''; + }; + +})(); diff --git a/codemirror/mode/clike/clike.js b/codemirror/mode/clike/clike.js new file mode 100644 index 0000000..1b350ae --- /dev/null +++ b/codemirror/mode/clike/clike.js @@ -0,0 +1,302 @@ +CodeMirror.defineMode("clike", function(config, parserConfig) { + var indentUnit = config.indentUnit, + statementIndentUnit = parserConfig.statementIndentUnit || indentUnit, + dontAlignCalls = parserConfig.dontAlignCalls, + keywords = parserConfig.keywords || {}, + builtin = parserConfig.builtin || {}, + blockKeywords = parserConfig.blockKeywords || {}, + atoms = parserConfig.atoms || {}, + hooks = parserConfig.hooks || {}, + multiLineStrings = parserConfig.multiLineStrings; + var isOperatorChar = /[+\-*&%=<>!?|\/]/; + + var curPunc; + + function tokenBase(stream, state) { + var ch = stream.next(); + if (hooks[ch]) { + var result = hooks[ch](stream, state); + if (result !== false) return result; + } + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + curPunc = ch; + return null; + } + if (/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/); + return "number"; + } + if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } + if (stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } + } + if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return "operator"; + } + stream.eatWhile(/[\w\$_]/); + var cur = stream.current(); + if (keywords.propertyIsEnumerable(cur)) { + if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; + return "keyword"; + } + if (builtin.propertyIsEnumerable(cur)) { + if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; + return "builtin"; + } + if (atoms.propertyIsEnumerable(cur)) return "atom"; + return "variable"; + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) {end = true; break;} + escaped = !escaped && next == "\\"; + } + if (end || !(escaped || multiLineStrings)) + state.tokenize = null; + return "string"; + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = null; + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + + function Context(indented, column, type, align, prev) { + this.indented = indented; + this.column = column; + this.type = type; + this.align = align; + this.prev = prev; + } + function pushContext(state, col, type) { + var indent = state.indented; + if (state.context && state.context.type == "statement") + indent = state.context.indented; + return state.context = new Context(indent, col, type, null, state.context); + } + function popContext(state) { + var t = state.context.type; + if (t == ")" || t == "]" || t == "}") + state.indented = state.context.indented; + return state.context = state.context.prev; + } + + // Interface + + return { + startState: function(basecolumn) { + return { + tokenize: null, + context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), + indented: 0, + startOfLine: true + }; + }, + + token: function(stream, state) { + var ctx = state.context; + if (stream.sol()) { + if (ctx.align == null) ctx.align = false; + state.indented = stream.indentation(); + state.startOfLine = true; + } + if (stream.eatSpace()) return null; + curPunc = null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style == "comment" || style == "meta") return style; + if (ctx.align == null) ctx.align = true; + + if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement") popContext(state); + else if (curPunc == "{") pushContext(state, stream.column(), "}"); + else if (curPunc == "[") pushContext(state, stream.column(), "]"); + else if (curPunc == "(") pushContext(state, stream.column(), ")"); + else if (curPunc == "}") { + while (ctx.type == "statement") ctx = popContext(state); + if (ctx.type == "}") ctx = popContext(state); + while (ctx.type == "statement") ctx = popContext(state); + } + else if (curPunc == ctx.type) popContext(state); + else if (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement")) + pushContext(state, stream.column(), "statement"); + state.startOfLine = false; + return style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass; + var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); + if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev; + var closing = firstChar == ctx.type; + if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit); + else if (dontAlignCalls && ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit; + else if (ctx.align) return ctx.column + (closing ? 0 : 1); + else return ctx.indented + (closing ? 0 : indentUnit); + }, + + electricChars: "{}" + }; +}); + +(function() { + function words(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + var cKeywords = "auto if break int case long char register continue return default short do sizeof " + + "double static else struct entry switch extern typedef float union for unsigned " + + "goto while enum void const signed volatile"; + + function cppHook(stream, state) { + if (!state.startOfLine) return false; + for (;;) { + if (stream.skipTo("\\")) { + stream.next(); + if (stream.eol()) { + state.tokenize = cppHook; + break; + } + } else { + stream.skipToEnd(); + state.tokenize = null; + break; + } + } + return "meta"; + } + + // C#-style strings where "" escapes a quote. + function tokenAtString(stream, state) { + var next; + while ((next = stream.next()) != null) { + if (next == '"' && !stream.eat('"')) { + state.tokenize = null; + break; + } + } + return "string"; + } + + function mimes(ms, mode) { + for (var i = 0; i < ms.length; ++i) CodeMirror.defineMIME(ms[i], mode); + } + + mimes(["text/x-csrc", "text/x-c", "text/x-chdr"], { + name: "clike", + keywords: words(cKeywords), + blockKeywords: words("case do else for if switch while struct"), + atoms: words("null"), + hooks: {"#": cppHook} + }); + mimes(["text/x-c++src", "text/x-c++hdr"], { + name: "clike", + keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " + + "static_cast typeid catch operator template typename class friend private " + + "this using const_cast inline public throw virtual delete mutable protected " + + "wchar_t"), + blockKeywords: words("catch class do else finally for if struct switch try while"), + atoms: words("true false null"), + hooks: {"#": cppHook} + }); + CodeMirror.defineMIME("text/x-java", { + name: "clike", + keywords: words("abstract assert boolean break byte case catch char class const continue default " + + "do double else enum extends final finally float for goto if implements import " + + "instanceof int interface long native new package private protected public " + + "return short static strictfp super switch synchronized this throw throws transient " + + "try void volatile while"), + blockKeywords: words("catch class do else finally for if switch try while"), + atoms: words("true false null"), + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "meta"; + } + } + }); + CodeMirror.defineMIME("text/x-csharp", { + name: "clike", + keywords: words("abstract as base break case catch checked class const continue" + + " default delegate do else enum event explicit extern finally fixed for" + + " foreach goto if implicit in interface internal is lock namespace new" + + " operator out override params private protected public readonly ref return sealed" + + " sizeof stackalloc static struct switch this throw try typeof unchecked" + + " unsafe using virtual void volatile while add alias ascending descending dynamic from get" + + " global group into join let orderby partial remove select set value var yield"), + blockKeywords: words("catch class do else finally for foreach if struct switch try while"), + builtin: words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" + + " Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32" + + " UInt64 bool byte char decimal double short int long object" + + " sbyte float string ushort uint ulong"), + atoms: words("true false null"), + hooks: { + "@": function(stream, state) { + if (stream.eat('"')) { + state.tokenize = tokenAtString; + return tokenAtString(stream, state); + } + stream.eatWhile(/[\w\$_]/); + return "meta"; + } + } + }); + CodeMirror.defineMIME("text/x-scala", { + name: "clike", + keywords: words( + + /* scala */ + "abstract case catch class def do else extends false final finally for forSome if " + + "implicit import lazy match new null object override package private protected return " + + "sealed super this throw trait try trye type val var while with yield _ : = => <- <: " + + "<% >: # @ " + + + /* package scala */ + "assert assume require print println printf readLine readBoolean readByte readShort " + + "readChar readInt readLong readFloat readDouble " + + + "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " + + "Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " + + "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " + + "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " + + "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector :: #:: " + + + /* package java.lang */ + "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + + "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void" + + + ), + blockKeywords: words("catch class do else finally for forSome if match switch try while"), + atoms: words("true false null"), + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "meta"; + } + } + }); +}()); diff --git a/codemirror/mode/clike/index.html b/codemirror/mode/clike/index.html new file mode 100644 index 0000000..048e210 --- /dev/null +++ b/codemirror/mode/clike/index.html @@ -0,0 +1,106 @@ + + + + + CodeMirror: C-like mode + + + + + + + + + +

CodeMirror: C-like mode

+ +
+ + + +

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

+ +

MIME types defined: text/x-csrc + (C code), text/x-c++src (C++ + code), text/x-java (Java + code), text/x-csharp (C#).

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

CodeMirror: Clojure mode

+
+ + +

MIME types defined: text/x-clojure.

+ + + diff --git a/codemirror/mode/coffeescript/LICENSE b/codemirror/mode/coffeescript/LICENSE new file mode 100644 index 0000000..977e284 --- /dev/null +++ b/codemirror/mode/coffeescript/LICENSE @@ -0,0 +1,22 @@ +The MIT License + +Copyright (c) 2011 Jeff Pickhardt +Modified from the Python CodeMirror mode, Copyright (c) 2010 Timothy Farrell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/codemirror/mode/coffeescript/coffeescript.js b/codemirror/mode/coffeescript/coffeescript.js new file mode 100644 index 0000000..670e01f --- /dev/null +++ b/codemirror/mode/coffeescript/coffeescript.js @@ -0,0 +1,346 @@ +/** + * Link to the project's GitHub page: + * https://github.com/pickhardt/coffeescript-codemirror-mode + */ +CodeMirror.defineMode('coffeescript', function(conf) { + var ERRORCLASS = 'error'; + + function wordRegexp(words) { + return new RegExp("^((" + words.join(")|(") + "))\\b"); + } + + var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!\?]"); + var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\},:`=;\\.]'); + var doubleOperators = new RegExp("^((\->)|(\=>)|(\\+\\+)|(\\+\\=)|(\\-\\-)|(\\-\\=)|(\\*\\*)|(\\*\\=)|(\\/\\/)|(\\/\\=)|(==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//))"); + var doubleDelimiters = new RegExp("^((\\.\\.)|(\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))"); + var tripleDelimiters = new RegExp("^((\\.\\.\\.)|(//=)|(>>=)|(<<=)|(\\*\\*=))"); + var identifiers = new RegExp("^[_A-Za-z$][_A-Za-z$0-9]*"); + var properties = new RegExp("^(@|this\.)[_A-Za-z$][_A-Za-z$0-9]*"); + + var wordOperators = wordRegexp(['and', 'or', 'not', + 'is', 'isnt', 'in', + 'instanceof', 'typeof']); + var indentKeywords = ['for', 'while', 'loop', 'if', 'unless', 'else', + 'switch', 'try', 'catch', 'finally', 'class']; + var commonKeywords = ['break', 'by', 'continue', 'debugger', 'delete', + 'do', 'in', 'of', 'new', 'return', 'then', + 'this', 'throw', 'when', 'until']; + + var keywords = wordRegexp(indentKeywords.concat(commonKeywords)); + + indentKeywords = wordRegexp(indentKeywords); + + + var stringPrefixes = new RegExp("^('{3}|\"{3}|['\"])"); + var regexPrefixes = new RegExp("^(/{3}|/)"); + var commonConstants = ['Infinity', 'NaN', 'undefined', 'null', 'true', 'false', 'on', 'off', 'yes', 'no']; + var constants = wordRegexp(commonConstants); + + // Tokenizers + function tokenBase(stream, state) { + // Handle scope changes + if (stream.sol()) { + var scopeOffset = state.scopes[0].offset; + if (stream.eatSpace()) { + var lineOffset = stream.indentation(); + if (lineOffset > scopeOffset) { + return 'indent'; + } else if (lineOffset < scopeOffset) { + return 'dedent'; + } + return null; + } else { + if (scopeOffset > 0) { + dedent(stream, state); + } + } + } + if (stream.eatSpace()) { + return null; + } + + var ch = stream.peek(); + + // Handle docco title comment (single line) + if (stream.match("####")) { + stream.skipToEnd(); + return 'comment'; + } + + // Handle multi line comments + if (stream.match("###")) { + state.tokenize = longComment; + return state.tokenize(stream, state); + } + + // Single line comment + if (ch === '#') { + stream.skipToEnd(); + return 'comment'; + } + + // Handle number literals + if (stream.match(/^-?[0-9\.]/, false)) { + var floatLiteral = false; + // Floats + if (stream.match(/^-?\d*\.\d+(e[\+\-]?\d+)?/i)) { + floatLiteral = true; + } + if (stream.match(/^-?\d+\.\d*/)) { + floatLiteral = true; + } + if (stream.match(/^-?\.\d+/)) { + floatLiteral = true; + } + + if (floatLiteral) { + // prevent from getting extra . on 1.. + if (stream.peek() == "."){ + stream.backUp(1); + } + return 'number'; + } + // Integers + var intLiteral = false; + // Hex + if (stream.match(/^-?0x[0-9a-f]+/i)) { + intLiteral = true; + } + // Decimal + if (stream.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)) { + intLiteral = true; + } + // Zero by itself with no other piece of number. + if (stream.match(/^-?0(?![\dx])/i)) { + intLiteral = true; + } + if (intLiteral) { + return 'number'; + } + } + + // Handle strings + if (stream.match(stringPrefixes)) { + state.tokenize = tokenFactory(stream.current(), 'string'); + return state.tokenize(stream, state); + } + // Handle regex literals + if (stream.match(regexPrefixes)) { + if (stream.current() != '/' || stream.match(/^.*\//, false)) { // prevent highlight of division + state.tokenize = tokenFactory(stream.current(), 'string-2'); + return state.tokenize(stream, state); + } else { + stream.backUp(1); + } + } + + // Handle operators and delimiters + if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) { + return 'punctuation'; + } + if (stream.match(doubleOperators) + || stream.match(singleOperators) + || stream.match(wordOperators)) { + return 'operator'; + } + if (stream.match(singleDelimiters)) { + return 'punctuation'; + } + + if (stream.match(constants)) { + return 'atom'; + } + + if (stream.match(keywords)) { + return 'keyword'; + } + + if (stream.match(identifiers)) { + return 'variable'; + } + + if (stream.match(properties)) { + return 'property'; + } + + // Handle non-detected items + stream.next(); + return ERRORCLASS; + } + + function tokenFactory(delimiter, outclass) { + var singleline = delimiter.length == 1; + return function 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 (conf.mode.singleLineStringErrors) { + outclass = ERRORCLASS; + } else { + state.tokenize = tokenBase; + } + } + return outclass; + }; + } + + function longComment(stream, state) { + while (!stream.eol()) { + stream.eatWhile(/[^#]/); + if (stream.match("###")) { + state.tokenize = tokenBase; + break; + } + stream.eatWhile("#"); + } + return "comment"; + } + + function indent(stream, state, type) { + type = type || 'coffee'; + var indentUnit = 0; + if (type === 'coffee') { + for (var i = 0; i < state.scopes.length; i++) { + if (state.scopes[i].type === 'coffee') { + indentUnit = state.scopes[i].offset + conf.indentUnit; + break; + } + } + } else { + indentUnit = stream.column() + stream.current().length; + } + state.scopes.unshift({ + offset: indentUnit, + type: type + }); + } + + function dedent(stream, state) { + if (state.scopes.length == 1) return; + if (state.scopes[0].type === 'coffee') { + var _indent = stream.indentation(); + var _indent_index = -1; + for (var i = 0; i < state.scopes.length; ++i) { + if (_indent === state.scopes[i].offset) { + _indent_index = i; + break; + } + } + if (_indent_index === -1) { + return true; + } + while (state.scopes[0].offset !== _indent) { + state.scopes.shift(); + } + return false; + } else { + state.scopes.shift(); + return false; + } + } + + function tokenLexer(stream, state) { + var style = state.tokenize(stream, state); + var current = stream.current(); + + // Handle '.' connected identifiers + if (current === '.') { + style = state.tokenize(stream, state); + current = stream.current(); + if (style === 'variable') { + return 'variable'; + } else { + return ERRORCLASS; + } + } + + // Handle scope changes. + if (current === 'return') { + state.dedent += 1; + } + if (((current === '->' || current === '=>') && + !state.lambda && + state.scopes[0].type == 'coffee' && + stream.peek() === '') + || style === 'indent') { + indent(stream, state); + } + var delimiter_index = '[({'.indexOf(current); + if (delimiter_index !== -1) { + indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1)); + } + if (indentKeywords.exec(current)){ + indent(stream, state); + } + if (current == 'then'){ + dedent(stream, state); + } + + + if (style === 'dedent') { + if (dedent(stream, state)) { + return ERRORCLASS; + } + } + delimiter_index = '])}'.indexOf(current); + if (delimiter_index !== -1) { + if (dedent(stream, state)) { + return ERRORCLASS; + } + } + if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'coffee') { + if (state.scopes.length > 1) state.scopes.shift(); + state.dedent -= 1; + } + + return style; + } + + var external = { + startState: function(basecolumn) { + return { + tokenize: tokenBase, + scopes: [{offset:basecolumn || 0, type:'coffee'}], + lastToken: null, + lambda: false, + dedent: 0 + }; + }, + + token: function(stream, state) { + var style = tokenLexer(stream, state); + + state.lastToken = {style:style, content: stream.current()}; + + if (stream.eol() && stream.lambda) { + state.lambda = false; + } + + return style; + }, + + indent: function(state) { + if (state.tokenize != tokenBase) { + return 0; + } + + return state.scopes[0].offset; + } + + }; + return external; +}); + +CodeMirror.defineMIME('text/x-coffeescript', 'coffeescript'); diff --git a/codemirror/mode/coffeescript/index.html b/codemirror/mode/coffeescript/index.html new file mode 100644 index 0000000..ee72b8d --- /dev/null +++ b/codemirror/mode/coffeescript/index.html @@ -0,0 +1,728 @@ + + + + + CodeMirror: CoffeeScript mode + + + + + + + +

CodeMirror: CoffeeScript mode

+
+ + +

MIME types defined: text/x-coffeescript.

+ +

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

+ + + diff --git a/codemirror/mode/commonlisp/commonlisp.js b/codemirror/mode/commonlisp/commonlisp.js new file mode 100644 index 0000000..eeba759 --- /dev/null +++ b/codemirror/mode/commonlisp/commonlisp.js @@ -0,0 +1,101 @@ +CodeMirror.defineMode("commonlisp", function (config) { + var assumeBody = /^with|^def|^do|^prog|case$|^cond$|bind$|when$|unless$/; + var numLiteral = /^(?:[+\-]?(?:\d+|\d*\.\d+)(?:[efd][+\-]?\d+)?|[+\-]?\d+(?:\/[+\-]?\d+)?|#b[+\-]?[01]+|#o[+\-]?[0-7]+|#x[+\-]?[\da-f]+)/; + var symbol = /[^\s'`,@()\[\]";]/; + var type; + + function readSym(stream) { + var ch; + while (ch = stream.next()) { + if (ch == "\\") stream.next(); + else if (!symbol.test(ch)) { stream.backUp(1); break; } + } + return stream.current(); + } + + function base(stream, state) { + if (stream.eatSpace()) {type = "ws"; return null;} + if (stream.match(numLiteral)) return "number"; + var ch = stream.next(); + if (ch == "\\") ch = stream.next(); + + if (ch == '"') return (state.tokenize = inString)(stream, state); + else if (ch == "(") { type = "open"; return "bracket"; } + else if (ch == ")" || ch == "]") { type = "close"; return "bracket"; } + else if (ch == ";") { stream.skipToEnd(); type = "ws"; return "comment"; } + else if (/['`,@]/.test(ch)) return null; + else if (ch == "|") { + if (stream.skipTo("|")) { stream.next(); return "symbol"; } + else { stream.skipToEnd(); return "error"; } + } else if (ch == "#") { + var ch = stream.next(); + if (ch == "[") { type = "open"; return "bracket"; } + else if (/[+\-=\.']/.test(ch)) return null; + else if (/\d/.test(ch) && stream.match(/^\d*#/)) return null; + else if (ch == "|") return (state.tokenize = inComment)(stream, state); + else if (ch == ":") { readSym(stream); return "meta"; } + else return "error"; + } else { + var name = readSym(stream); + if (name == ".") return null; + type = "symbol"; + if (name == "nil" || name == "t") return "atom"; + if (name.charAt(0) == ":") return "keyword"; + if (name.charAt(0) == "&") return "variable-2"; + return "variable"; + } + } + + function inString(stream, state) { + var escaped = false, next; + while (next = stream.next()) { + if (next == '"' && !escaped) { state.tokenize = base; break; } + escaped = !escaped && next == "\\"; + } + return "string"; + } + + function inComment(stream, state) { + var next, last; + while (next = stream.next()) { + if (next == "#" && last == "|") { state.tokenize = base; break; } + last = next; + } + type = "ws"; + return "comment"; + } + + return { + startState: function () { + return {ctx: {prev: null, start: 0, indentTo: 0}, tokenize: base}; + }, + + token: function (stream, state) { + if (stream.sol() && typeof state.ctx.indentTo != "number") + state.ctx.indentTo = state.ctx.start + 1; + + type = null; + var style = state.tokenize(stream, state); + if (type != "ws") { + if (state.ctx.indentTo == null) { + if (type == "symbol" && assumeBody.test(stream.current())) + state.ctx.indentTo = state.ctx.start + config.indentUnit; + else + state.ctx.indentTo = "next"; + } else if (state.ctx.indentTo == "next") { + state.ctx.indentTo = stream.column(); + } + } + if (type == "open") state.ctx = {prev: state.ctx, start: stream.column(), indentTo: null}; + else if (type == "close") state.ctx = state.ctx.prev || state.ctx; + return style; + }, + + indent: function (state, _textAfter) { + var i = state.ctx.indentTo; + return typeof i == "number" ? i : state.ctx.start + 1; + } + }; +}); + +CodeMirror.defineMIME("text/x-common-lisp", "commonlisp"); diff --git a/codemirror/mode/commonlisp/index.html b/codemirror/mode/commonlisp/index.html new file mode 100644 index 0000000..f9766a8 --- /dev/null +++ b/codemirror/mode/commonlisp/index.html @@ -0,0 +1,165 @@ + + + + + CodeMirror: Common Lisp mode + + + + + + + +

CodeMirror: Common Lisp mode

+
+ + +

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

+ + + diff --git a/codemirror/mode/css/css.js b/codemirror/mode/css/css.js new file mode 100644 index 0000000..37ef76c --- /dev/null +++ b/codemirror/mode/css/css.js @@ -0,0 +1,465 @@ +CodeMirror.defineMode("css", function(config) { + var indentUnit = config.indentUnit, type; + + var atMediaTypes = keySet([ + "all", "aural", "braille", "handheld", "print", "projection", "screen", + "tty", "tv", "embossed" + ]); + + var atMediaFeatures = keySet([ + "width", "min-width", "max-width", "height", "min-height", "max-height", + "device-width", "min-device-width", "max-device-width", "device-height", + "min-device-height", "max-device-height", "aspect-ratio", + "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio", + "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color", + "max-color", "color-index", "min-color-index", "max-color-index", + "monochrome", "min-monochrome", "max-monochrome", "resolution", + "min-resolution", "max-resolution", "scan", "grid" + ]); + + var propertyKeywords = keySet([ + "align-content", "align-items", "align-self", "alignment-adjust", + "alignment-baseline", "anchor-point", "animation", "animation-delay", + "animation-direction", "animation-duration", "animation-iteration-count", + "animation-name", "animation-play-state", "animation-timing-function", + "appearance", "azimuth", "backface-visibility", "background", + "background-attachment", "background-clip", "background-color", + "background-image", "background-origin", "background-position", + "background-repeat", "background-size", "baseline-shift", "binding", + "bleed", "bookmark-label", "bookmark-level", "bookmark-state", + "bookmark-target", "border", "border-bottom", "border-bottom-color", + "border-bottom-left-radius", "border-bottom-right-radius", + "border-bottom-style", "border-bottom-width", "border-collapse", + "border-color", "border-image", "border-image-outset", + "border-image-repeat", "border-image-slice", "border-image-source", + "border-image-width", "border-left", "border-left-color", + "border-left-style", "border-left-width", "border-radius", "border-right", + "border-right-color", "border-right-style", "border-right-width", + "border-spacing", "border-style", "border-top", "border-top-color", + "border-top-left-radius", "border-top-right-radius", "border-top-style", + "border-top-width", "border-width", "bottom", "box-decoration-break", + "box-shadow", "box-sizing", "break-after", "break-before", "break-inside", + "caption-side", "clear", "clip", "color", "color-profile", "column-count", + "column-fill", "column-gap", "column-rule", "column-rule-color", + "column-rule-style", "column-rule-width", "column-span", "column-width", + "columns", "content", "counter-increment", "counter-reset", "crop", "cue", + "cue-after", "cue-before", "cursor", "direction", "display", + "dominant-baseline", "drop-initial-after-adjust", + "drop-initial-after-align", "drop-initial-before-adjust", + "drop-initial-before-align", "drop-initial-size", "drop-initial-value", + "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis", + "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap", + "float", "float-offset", "font", "font-feature-settings", "font-family", + "font-kerning", "font-language-override", "font-size", "font-size-adjust", + "font-stretch", "font-style", "font-synthesis", "font-variant", + "font-variant-alternates", "font-variant-caps", "font-variant-east-asian", + "font-variant-ligatures", "font-variant-numeric", "font-variant-position", + "font-weight", "grid-cell", "grid-column", "grid-column-align", + "grid-column-sizing", "grid-column-span", "grid-columns", "grid-flow", + "grid-row", "grid-row-align", "grid-row-sizing", "grid-row-span", + "grid-rows", "grid-template", "hanging-punctuation", "height", "hyphens", + "icon", "image-orientation", "image-rendering", "image-resolution", + "inline-box-align", "justify-content", "left", "letter-spacing", + "line-break", "line-height", "line-stacking", "line-stacking-ruby", + "line-stacking-shift", "line-stacking-strategy", "list-style", + "list-style-image", "list-style-position", "list-style-type", "margin", + "margin-bottom", "margin-left", "margin-right", "margin-top", + "marker-offset", "marks", "marquee-direction", "marquee-loop", + "marquee-play-count", "marquee-speed", "marquee-style", "max-height", + "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index", + "nav-left", "nav-right", "nav-up", "opacity", "order", "orphans", "outline", + "outline-color", "outline-offset", "outline-style", "outline-width", + "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y", + "padding", "padding-bottom", "padding-left", "padding-right", "padding-top", + "page", "page-break-after", "page-break-before", "page-break-inside", + "page-policy", "pause", "pause-after", "pause-before", "perspective", + "perspective-origin", "pitch", "pitch-range", "play-during", "position", + "presentation-level", "punctuation-trim", "quotes", "rendering-intent", + "resize", "rest", "rest-after", "rest-before", "richness", "right", + "rotation", "rotation-point", "ruby-align", "ruby-overhang", + "ruby-position", "ruby-span", "size", "speak", "speak-as", "speak-header", + "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set", + "tab-size", "table-layout", "target", "target-name", "target-new", + "target-position", "text-align", "text-align-last", "text-decoration", + "text-decoration-color", "text-decoration-line", "text-decoration-skip", + "text-decoration-style", "text-emphasis", "text-emphasis-color", + "text-emphasis-position", "text-emphasis-style", "text-height", + "text-indent", "text-justify", "text-outline", "text-shadow", + "text-space-collapse", "text-transform", "text-underline-position", + "text-wrap", "top", "transform", "transform-origin", "transform-style", + "transition", "transition-delay", "transition-duration", + "transition-property", "transition-timing-function", "unicode-bidi", + "vertical-align", "visibility", "voice-balance", "voice-duration", + "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress", + "voice-volume", "volume", "white-space", "widows", "width", "word-break", + "word-spacing", "word-wrap", "z-index" + ]); + + var colorKeywords = keySet([ + "black", "silver", "gray", "white", "maroon", "red", "purple", "fuchsia", + "green", "lime", "olive", "yellow", "navy", "blue", "teal", "aqua" + ]); + + var valueKeywords = keySet([ + "above", "absolute", "activeborder", "activecaption", "afar", + "after-white-space", "ahead", "alias", "all", "all-scroll", "alternate", + "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", + "arabic-indic", "armenian", "asterisks", "auto", "avoid", "background", + "backwards", "baseline", "below", "bidi-override", "binary", "bengali", + "blink", "block", "block-axis", "bold", "bolder", "border", "border-box", + "both", "bottom", "break-all", "break-word", "button", "button-bevel", + "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "cambodian", + "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", + "cell", "center", "checkbox", "circle", "cjk-earthly-branch", + "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", + "col-resize", "collapse", "compact", "condensed", "contain", "content", + "content-box", "context-menu", "continuous", "copy", "cover", "crop", + "cross", "crosshair", "currentcolor", "cursive", "dashed", "decimal", + "decimal-leading-zero", "default", "default-button", "destination-atop", + "destination-in", "destination-out", "destination-over", "devanagari", + "disc", "discard", "document", "dot-dash", "dot-dot-dash", "dotted", + "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", + "element", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", + "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", + "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", + "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", + "ethiopic-halehame-gez", "ethiopic-halehame-om-et", + "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", + "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", + "ethiopic-halehame-tig", "ew-resize", "expanded", "extra-condensed", + "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "footnotes", + "forwards", "from", "geometricPrecision", "georgian", "graytext", "groove", + "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hebrew", + "help", "hidden", "hide", "higher", "highlight", "highlighttext", + "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "icon", "ignore", + "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", + "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", + "inline-block", "inline-table", "inset", "inside", "intrinsic", "invert", + "italic", "justify", "kannada", "katakana", "katakana-iroha", "khmer", + "landscape", "lao", "large", "larger", "left", "level", "lighter", + "line-through", "linear", "lines", "list-item", "listbox", "listitem", + "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", + "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", + "lower-roman", "lowercase", "ltr", "malayalam", "match", + "media-controls-background", "media-current-time-display", + "media-fullscreen-button", "media-mute-button", "media-play-button", + "media-return-to-realtime-button", "media-rewind-button", + "media-seek-back-button", "media-seek-forward-button", "media-slider", + "media-sliderthumb", "media-time-remaining-display", "media-volume-slider", + "media-volume-slider-container", "media-volume-sliderthumb", "medium", + "menu", "menulist", "menulist-button", "menulist-text", + "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic", + "mix", "mongolian", "monospace", "move", "multiple", "myanmar", "n-resize", + "narrower", "navy", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", + "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", + "ns-resize", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote", + "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", + "outside", "overlay", "overline", "padding", "padding-box", "painted", + "paused", "persian", "plus-darker", "plus-lighter", "pointer", "portrait", + "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button", + "radio", "read-only", "read-write", "read-write-plaintext-only", "relative", + "repeat", "repeat-x", "repeat-y", "reset", "reverse", "rgb", "rgba", + "ridge", "right", "round", "row-resize", "rtl", "run-in", "running", + "s-resize", "sans-serif", "scroll", "scrollbar", "se-resize", "searchfield", + "searchfield-cancel-button", "searchfield-decoration", + "searchfield-results-button", "searchfield-results-decoration", + "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama", + "single", "skip-white-space", "slide", "slider-horizontal", + "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", + "small", "small-caps", "small-caption", "smaller", "solid", "somali", + "source-atop", "source-in", "source-out", "source-over", "space", "square", + "square-button", "start", "static", "status-bar", "stretch", "stroke", + "sub", "subpixel-antialiased", "super", "sw-resize", "table", + "table-caption", "table-cell", "table-column", "table-column-group", + "table-footer-group", "table-header-group", "table-row", "table-row-group", + "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", + "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", + "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", + "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top", + "transparent", "ultra-condensed", "ultra-expanded", "underline", "up", + "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", + "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", + "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", + "visibleStroke", "visual", "w-resize", "wait", "wave", "white", "wider", + "window", "windowframe", "windowtext", "x-large", "x-small", "xor", + "xx-large", "xx-small", "yellow" + ]); + + function keySet(array) { var keys = {}; for (var i = 0; i < array.length; ++i) keys[array[i]] = true; return keys; } + function ret(style, tp) {type = tp; return style;} + + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("def", stream.current());} + else if (ch == "/" && stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + else if (ch == "<" && stream.eat("!")) { + state.tokenize = tokenSGMLComment; + return tokenSGMLComment(stream, state); + } + else if (ch == "=") ret(null, "compare"); + else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare"); + else if (ch == "\"" || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + else if (ch == "#") { + stream.eatWhile(/[\w\\\-]/); + return ret("atom", "hash"); + } + else if (ch == "!") { + stream.match(/^\s*\w*/); + return ret("keyword", "important"); + } + else if (/\d/.test(ch)) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } + else if (ch === "-") { + if (/\d/.test(stream.peek())) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (stream.match(/^[^-]+-/)) { + return ret("meta", "meta"); + } + } + else if (/[,+>*\/]/.test(ch)) { + return ret(null, "select-op"); + } + else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { + return ret("qualifier", "qualifier"); + } + else if (ch == ":") { + return ret("operator", ch); + } + else if (/[;{}\[\]\(\)]/.test(ch)) { + return ret(null, ch); + } + else if (ch == "u" && stream.match("rl(")) { + stream.backUp(1); + state.tokenize = tokenParenthesized; + return ret("property", "variable"); + } + else { + stream.eatWhile(/[\w\\\-]/); + return ret("property", "variable"); + } + } + + function tokenCComment(stream, state) { + var maybeEnd = false, ch; + while ((ch = stream.next()) != null) { + if (maybeEnd && ch == "/") { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return ret("comment", "comment"); + } + + function tokenSGMLComment(stream, state) { + var dashes = 0, ch; + while ((ch = stream.next()) != null) { + if (dashes >= 2 && ch == ">") { + state.tokenize = tokenBase; + break; + } + dashes = (ch == "-") ? dashes + 1 : 0; + } + return ret("comment", "comment"); + } + + function tokenString(quote, nonInclusive) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) + break; + escaped = !escaped && ch == "\\"; + } + if (!escaped) { + if (nonInclusive) stream.backUp(1); + state.tokenize = tokenBase; + } + return ret("string", "string"); + }; + } + + function tokenParenthesized(stream, state) { + stream.next(); // Must be '(' + if (!stream.match(/\s*[\"\']/, false)) + state.tokenize = tokenString(")", true); + else + state.tokenize = tokenBase; + return ret(null, "("); + } + + return { + startState: function(base) { + return {tokenize: tokenBase, + baseIndent: base || 0, + stack: []}; + }, + + token: function(stream, state) { + + // Use these terms when applicable (see http://www.xanthir.com/blog/b4E50) + // + // rule** or **ruleset: + // A selector + braces combo, or an at-rule. + // + // declaration block: + // A sequence of declarations. + // + // declaration: + // A property + colon + value combo. + // + // property value: + // The entire value of a property. + // + // component value: + // A single piece of a property value. Like the 5px in + // text-shadow: 0 0 5px blue;. Can also refer to things that are + // multiple terms, like the 1-4 terms that make up the background-size + // portion of the background shorthand. + // + // term: + // The basic unit of author-facing CSS, like a single number (5), + // dimension (5px), string ("foo"), or function. Officially defined + // by the CSS 2.1 grammar (look for the 'term' production) + // + // + // simple selector: + // A single atomic selector, like a type selector, an attr selector, a + // class selector, etc. + // + // compound selector: + // One or more simple selectors without a combinator. div.example is + // compound, div > .example is not. + // + // complex selector: + // One or more compound selectors chained with combinators. + // + // combinator: + // The parts of selectors that express relationships. There are four + // currently - the space (descendant combinator), the greater-than + // bracket (child combinator), the plus sign (next sibling combinator), + // and the tilda (following sibling combinator). + // + // sequence of selectors: + // One or more of the named type of selector chained with commas. + + if (state.tokenize == tokenBase && stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + + // Changing style returned based on context + var context = state.stack[state.stack.length-1]; + if (style == "property") { + if (context == "propertyValue"){ + if (valueKeywords[stream.current()]) { + style = "string-2"; + } else if (colorKeywords[stream.current()]) { + style = "keyword"; + } else { + style = "variable-2"; + } + } else if (context == "rule") { + if (!propertyKeywords[stream.current()]) { + style += " error"; + } + } else if (!context || context == "@media{") { + style = "tag"; + } else if (context == "@media") { + if (atMediaTypes[stream.current()]) { + style = "attribute"; // Known attribute + } else if (/^(only|not)$/i.test(stream.current())) { + style = "keyword"; + } else if (stream.current().toLowerCase() == "and") { + style = "error"; // "and" is only allowed in @mediaType + } else if (atMediaFeatures[stream.current()]) { + style = "error"; // Known property, should be in @mediaType( + } else { + // Unknown, expecting keyword or attribute, assuming attribute + style = "attribute error"; + } + } else if (context == "@mediaType") { + if (atMediaTypes[stream.current()]) { + style = "attribute"; + } else if (stream.current().toLowerCase() == "and") { + style = "operator"; + } else if (/^(only|not)$/i.test(stream.current())) { + style = "error"; // Only allowed in @media + } else if (atMediaFeatures[stream.current()]) { + style = "error"; // Known property, should be in parentheses + } else { + // Unknown attribute or property, but expecting property (preceded + // by "and"). Should be in parentheses + style = "error"; + } + } else if (context == "@mediaType(") { + if (propertyKeywords[stream.current()]) { + // do nothing, remains "property" + } else if (atMediaTypes[stream.current()]) { + style = "error"; // Known property, should be in parentheses + } else if (stream.current().toLowerCase() == "and") { + style = "operator"; + } else if (/^(only|not)$/i.test(stream.current())) { + style = "error"; // Only allowed in @media + } else { + style += " error"; + } + } else { + style = "error"; + } + } else if (style == "atom") { + if(!context || context == "@media{") { + style = "builtin"; + } else if (context == "propertyValue") { + if (!/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(stream.current())) { + style += " error"; + } + } else { + style = "error"; + } + } else if (context == "@media" && type == "{") { + style = "error"; + } + + // Push/pop context stack + if (type == "{") { + if (context == "@media" || context == "@mediaType") { + state.stack.pop(); + state.stack[state.stack.length-1] = "@media{"; + } + else state.stack.push("rule"); + } + else if (type == "}") { + state.stack.pop(); + if (context == "propertyValue") state.stack.pop(); + } + else if (type == "@media") state.stack.push("@media"); + else if (context == "@media" && /\b(keyword|attribute)\b/.test(style)) + state.stack.push("@mediaType"); + else if (context == "@mediaType" && stream.current() == ",") state.stack.pop(); + else if (context == "@mediaType" && type == "(") state.stack.push("@mediaType("); + else if (context == "@mediaType(" && type == ")") state.stack.pop(); + else if (context == "rule" && type == ":") state.stack.push("propertyValue"); + else if (context == "propertyValue" && type == ";") state.stack.pop(); + return style; + }, + + indent: function(state, textAfter) { + var n = state.stack.length; + if (/^\}/.test(textAfter)) + n -= state.stack[state.stack.length-1] == "propertyValue" ? 2 : 1; + return state.baseIndent + n * indentUnit; + }, + + electricChars: "}" + }; +}); + +CodeMirror.defineMIME("text/css", "css"); diff --git a/codemirror/mode/css/index.html b/codemirror/mode/css/index.html new file mode 100644 index 0000000..ae2c3bf --- /dev/null +++ b/codemirror/mode/css/index.html @@ -0,0 +1,58 @@ + + + + + CodeMirror: CSS mode + + + + + + + +

CodeMirror: CSS mode

+
+ + +

MIME types defined: text/css.

+ +

Parsing/Highlighting Tests: normal, verbose.

+ + + diff --git a/codemirror/mode/css/test.js b/codemirror/mode/css/test.js new file mode 100644 index 0000000..fd6a4b8 --- /dev/null +++ b/codemirror/mode/css/test.js @@ -0,0 +1,501 @@ +// Initiate ModeTest and set defaults +var MT = ModeTest; +MT.modeName = 'css'; +MT.modeOptions = {}; + +// Requires at least one media query +MT.testMode( + 'atMediaEmpty', + '@media { }', + [ + 'def', '@media', + null, ' ', + 'error', '{', + null, ' }' + ] +); + +MT.testMode( + 'atMediaMultiple', + '@media not screen and (color), not print and (color) { }', + [ + 'def', '@media', + null, ' ', + 'keyword', 'not', + null, ' ', + 'attribute', 'screen', + null, ' ', + 'operator', 'and', + null, ' (', + 'property', 'color', + null, '), ', + 'keyword', 'not', + null, ' ', + 'attribute', 'print', + null, ' ', + 'operator', 'and', + null, ' (', + 'property', 'color', + null, ') { }' + ] +); + +MT.testMode( + 'atMediaCheckStack', + '@media screen { } foo { }', + [ + 'def', '@media', + null, ' ', + 'attribute', 'screen', + null, ' { } ', + 'tag', 'foo', + null, ' { }' + ] +); + +MT.testMode( + 'atMediaCheckStack', + '@media screen (color) { } foo { }', + [ + 'def', '@media', + null, ' ', + 'attribute', 'screen', + null, ' (', + 'property', 'color', + null, ') { } ', + 'tag', 'foo', + null, ' { }' + ] +); + +MT.testMode( + 'atMediaCheckStackInvalidAttribute', + '@media foobarhello { } foo { }', + [ + 'def', '@media', + null, ' ', + 'attribute error', 'foobarhello', + null, ' { } ', + 'tag', 'foo', + null, ' { }' + ] +); + +// Error, because "and" is only allowed immediately preceding a media expression +MT.testMode( + 'atMediaInvalidAttribute', + '@media foobarhello { }', + [ + 'def', '@media', + null, ' ', + 'attribute error', 'foobarhello', + null, ' { }' + ] +); + +// Error, because "and" is only allowed immediately preceding a media expression +MT.testMode( + 'atMediaInvalidAnd', + '@media and screen { }', + [ + 'def', '@media', + null, ' ', + 'error', 'and', + null, ' ', + 'attribute', 'screen', + null, ' { }' + ] +); + +// Error, because "not" is only allowed as the first item in each media query +MT.testMode( + 'atMediaInvalidNot', + '@media screen not (not) { }', + [ + 'def', '@media', + null, ' ', + 'attribute', 'screen', + null, ' ', + 'error', 'not', + null, ' (', + 'error', 'not', + null, ') { }' + ] +); + +// Error, because "only" is only allowed as the first item in each media query +MT.testMode( + 'atMediaInvalidOnly', + '@media screen only (only) { }', + [ + 'def', '@media', + null, ' ', + 'attribute', 'screen', + null, ' ', + 'error', 'only', + null, ' (', + 'error', 'only', + null, ') { }' + ] +); + +// Error, because "foobarhello" is neither a known type or property, but +// property was expected (after "and"), and it should be in parenthese. +MT.testMode( + 'atMediaUnknownType', + '@media screen and foobarhello { }', + [ + 'def', '@media', + null, ' ', + 'attribute', 'screen', + null, ' ', + 'operator', 'and', + null, ' ', + 'error', 'foobarhello', + null, ' { }' + ] +); + +// Error, because "color" is not a known type, but is a known property, and +// should be in parentheses. +MT.testMode( + 'atMediaInvalidType', + '@media screen and color { }', + [ + 'def', '@media', + null, ' ', + 'attribute', 'screen', + null, ' ', + 'operator', 'and', + null, ' ', + 'error', 'color', + null, ' { }' + ] +); + +// Error, because "print" is not a known property, but is a known type, +// and should not be in parenthese. +MT.testMode( + 'atMediaInvalidProperty', + '@media screen and (print) { }', + [ + 'def', '@media', + null, ' ', + 'attribute', 'screen', + null, ' ', + 'operator', 'and', + null, ' (', + 'error', 'print', + null, ') { }' + ] +); + +// Soft error, because "foobarhello" is not a known property or type. +MT.testMode( + 'atMediaUnknownProperty', + '@media screen and (foobarhello) { }', + [ + 'def', '@media', + null, ' ', + 'attribute', 'screen', + null, ' ', + 'operator', 'and', + null, ' (', + 'property error', 'foobarhello', + null, ') { }' + ] +); + +MT.testMode( + 'tagSelector', + 'foo { }', + [ + 'tag', 'foo', + null, ' { }' + ] +); + +MT.testMode( + 'classSelector', + '.foo-bar_hello { }', + [ + 'qualifier', '.foo-bar_hello', + null, ' { }' + ] +); + +MT.testMode( + 'idSelector', + '#foo { #foo }', + [ + 'builtin', '#foo', + null, ' { ', + 'error', '#foo', + null, ' }' + ] +); + +MT.testMode( + 'tagSelectorUnclosed', + 'foo { margin: 0 } bar { }', + [ + 'tag', 'foo', + null, ' { ', + 'property', 'margin', + 'operator', ':', + null, ' ', + 'number', '0', + null, ' } ', + 'tag', 'bar', + null, ' { }' + ] +); + +MT.testMode( + 'tagStringNoQuotes', + 'foo { font-family: hello world; }', + [ + 'tag', 'foo', + null, ' { ', + 'property', 'font-family', + 'operator', ':', + null, ' ', + 'variable-2', 'hello', + null, ' ', + 'variable-2', 'world', + null, '; }' + ] +); + +MT.testMode( + 'tagStringDouble', + 'foo { font-family: "hello world"; }', + [ + 'tag', 'foo', + null, ' { ', + 'property', 'font-family', + 'operator', ':', + null, ' ', + 'string', '"hello world"', + null, '; }' + ] +); + +MT.testMode( + 'tagStringSingle', + 'foo { font-family: \'hello world\'; }', + [ + 'tag', 'foo', + null, ' { ', + 'property', 'font-family', + 'operator', ':', + null, ' ', + 'string', '\'hello world\'', + null, '; }' + ] +); + +MT.testMode( + 'tagColorKeyword', + 'foo { color: black; }', + [ + 'tag', 'foo', + null, ' { ', + 'property', 'color', + 'operator', ':', + null, ' ', + 'keyword', 'black', + null, '; }' + ] +); + +MT.testMode( + 'tagColorHex3', + 'foo { background: #fff; }', + [ + 'tag', 'foo', + null, ' { ', + 'property', 'background', + 'operator', ':', + null, ' ', + 'atom', '#fff', + null, '; }' + ] +); + +MT.testMode( + 'tagColorHex6', + 'foo { background: #ffffff; }', + [ + 'tag', 'foo', + null, ' { ', + 'property', 'background', + 'operator', ':', + null, ' ', + 'atom', '#ffffff', + null, '; }' + ] +); + +MT.testMode( + 'tagColorHex4', + 'foo { background: #ffff; }', + [ + 'tag', 'foo', + null, ' { ', + 'property', 'background', + 'operator', ':', + null, ' ', + 'atom error', '#ffff', + null, '; }' + ] +); + +MT.testMode( + 'tagColorHexInvalid', + 'foo { background: #ffg; }', + [ + 'tag', 'foo', + null, ' { ', + 'property', 'background', + 'operator', ':', + null, ' ', + 'atom error', '#ffg', + null, '; }' + ] +); + +MT.testMode( + 'tagNegativeNumber', + 'foo { margin: -5px; }', + [ + 'tag', 'foo', + null, ' { ', + 'property', 'margin', + 'operator', ':', + null, ' ', + 'number', '-5px', + null, '; }' + ] +); + +MT.testMode( + 'tagPositiveNumber', + 'foo { padding: 5px; }', + [ + 'tag', 'foo', + null, ' { ', + 'property', 'padding', + 'operator', ':', + null, ' ', + 'number', '5px', + null, '; }' + ] +); + +MT.testMode( + 'tagVendor', + 'foo { -foo-box-sizing: -foo-border-box; }', + [ + 'tag', 'foo', + null, ' { ', + 'meta', '-foo-', + 'property', 'box-sizing', + 'operator', ':', + null, ' ', + 'meta', '-foo-', + 'string-2', 'border-box', + null, '; }' + ] +); + +MT.testMode( + 'tagBogusProperty', + 'foo { barhelloworld: 0; }', + [ + 'tag', 'foo', + null, ' { ', + 'property error', 'barhelloworld', + 'operator', ':', + null, ' ', + 'number', '0', + null, '; }' + ] +); + +MT.testMode( + 'tagTwoProperties', + 'foo { margin: 0; padding: 0; }', + [ + 'tag', 'foo', + null, ' { ', + 'property', 'margin', + 'operator', ':', + null, ' ', + 'number', '0', + null, '; ', + 'property', 'padding', + 'operator', ':', + null, ' ', + 'number', '0', + null, '; }' + ] +); +// +//MT.testMode( +// 'tagClass', +// '@media only screen and (min-width: 500px), print {foo.bar#hello { color: black !important; background: #f00; margin: -5px; padding: 5px; -foo-box-sizing: border-box; } /* world */}', +// [ +// 'def', '@media', +// null, ' ', +// 'keyword', 'only', +// null, ' ', +// 'attribute', 'screen', +// null, ' ', +// 'operator', 'and', +// null, ' ', +// 'bracket', '(', +// 'property', 'min-width', +// 'operator', ':', +// null, ' ', +// 'number', '500px', +// 'bracket', ')', +// null, ', ', +// 'attribute', 'print', +// null, ' {', +// 'tag', 'foo', +// 'qualifier', '.bar', +// 'header', '#hello', +// null, ' { ', +// 'property', 'color', +// 'operator', ':', +// null, ' ', +// 'keyword', 'black', +// null, ' ', +// 'keyword', '!important', +// null, '; ', +// 'property', 'background', +// 'operator', ':', +// null, ' ', +// 'atom', '#f00', +// null, '; ', +// 'property', 'padding', +// 'operator', ':', +// null, ' ', +// 'number', '5px', +// null, '; ', +// 'property', 'margin', +// 'operator', ':', +// null, ' ', +// 'number', '-5px', +// null, '; ', +// 'meta', '-foo-', +// 'property', 'box-sizing', +// 'operator', ':', +// null, ' ', +// 'string-2', 'border-box', +// null, '; } ', +// 'comment', '/* world */', +// null, '}' +// ] +//); \ No newline at end of file diff --git a/codemirror/mode/diff/diff.js b/codemirror/mode/diff/diff.js new file mode 100644 index 0000000..9a0d90e --- /dev/null +++ b/codemirror/mode/diff/diff.js @@ -0,0 +1,32 @@ +CodeMirror.defineMode("diff", function() { + + var TOKEN_NAMES = { + '+': 'positive', + '-': 'negative', + '@': 'meta' + }; + + return { + token: function(stream) { + var tw_pos = stream.string.search(/[\t ]+?$/); + + if (!stream.sol() || tw_pos === 0) { + stream.skipToEnd(); + return ("error " + ( + TOKEN_NAMES[stream.string.charAt(0)] || '')).replace(/ $/, ''); + } + + var token_name = TOKEN_NAMES[stream.peek()] || stream.skipToEnd(); + + if (tw_pos === -1) { + stream.skipToEnd(); + } else { + stream.pos = tw_pos; + } + + return token_name; + } + }; +}); + +CodeMirror.defineMIME("text/x-diff", "diff"); diff --git a/codemirror/mode/diff/index.html b/codemirror/mode/diff/index.html new file mode 100644 index 0000000..5560252 --- /dev/null +++ b/codemirror/mode/diff/index.html @@ -0,0 +1,105 @@ + + + + + CodeMirror: Diff mode + + + + + + + +

CodeMirror: Diff mode

+
+ + +

MIME types defined: text/x-diff.

+ + + diff --git a/codemirror/mode/ecl/ecl.js b/codemirror/mode/ecl/ecl.js new file mode 100644 index 0000000..3ee7a68 --- /dev/null +++ b/codemirror/mode/ecl/ecl.js @@ -0,0 +1,192 @@ +CodeMirror.defineMode("ecl", function(config) { + + function words(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + + function metaHook(stream, state) { + if (!state.startOfLine) return false; + stream.skipToEnd(); + return "meta"; + } + + var indentUnit = config.indentUnit; + var keyword = words("abs acos allnodes ascii asin asstring atan atan2 ave case choose choosen choosesets clustersize combine correlation cos cosh count covariance cron dataset dedup define denormalize distribute distributed distribution ebcdic enth error evaluate event eventextra eventname exists exp failcode failmessage fetch fromunicode getisvalid global graph group hash hash32 hash64 hashcrc hashmd5 having if index intformat isvalid iterate join keyunicode length library limit ln local log loop map matched matchlength matchposition matchtext matchunicode max merge mergejoin min nolocal nonempty normalize parse pipe power preload process project pull random range rank ranked realformat recordof regexfind regexreplace regroup rejected rollup round roundup row rowdiff sample set sin sinh sizeof soapcall sort sorted sqrt stepped stored sum table tan tanh thisnode topn tounicode transfer trim truncate typeof ungroup unicodeorder variance which workunit xmldecode xmlencode xmltext xmlunicode"); + var variable = words("apply assert build buildindex evaluate fail keydiff keypatch loadxml nothor notify output parallel sequential soapcall wait"); + var variable_2 = words("__compressed__ all and any as atmost before beginc++ best between case const counter csv descend encrypt end endc++ endmacro except exclusive expire export extend false few first flat from full function group header heading hole ifblock import in interface joined keep keyed last left limit load local locale lookup macro many maxcount maxlength min skew module named nocase noroot noscan nosort not of only opt or outer overwrite packed partition penalty physicallength pipe quote record relationship repeat return right scan self separator service shared skew skip sql store terminator thor threshold token transform trim true type unicodeorder unsorted validate virtual whole wild within xml xpath"); + var variable_3 = words("ascii big_endian boolean data decimal ebcdic integer pattern qstring real record rule set of string token udecimal unicode unsigned varstring varunicode"); + var builtin = words("checkpoint deprecated failcode failmessage failure global independent onwarning persist priority recovery stored success wait when"); + var blockKeywords = words("catch class do else finally for if switch try while"); + var atoms = words("true false null"); + var hooks = {"#": metaHook}; + var multiLineStrings; + var isOperatorChar = /[+\-*&%=<>!?|\/]/; + + var curPunc; + + function tokenBase(stream, state) { + var ch = stream.next(); + if (hooks[ch]) { + var result = hooks[ch](stream, state); + if (result !== false) return result; + } + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + curPunc = ch; + return null; + } + if (/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/); + return "number"; + } + if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } + if (stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } + } + if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return "operator"; + } + stream.eatWhile(/[\w\$_]/); + var cur = stream.current().toLowerCase(); + if (keyword.propertyIsEnumerable(cur)) { + if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; + return "keyword"; + } else if (variable.propertyIsEnumerable(cur)) { + if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; + return "variable"; + } else if (variable_2.propertyIsEnumerable(cur)) { + if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; + return "variable-2"; + } else if (variable_3.propertyIsEnumerable(cur)) { + if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; + return "variable-3"; + } else if (builtin.propertyIsEnumerable(cur)) { + if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; + return "builtin"; + } else { //Data types are of from KEYWORD## + var i = cur.length - 1; + while(i >= 0 && (!isNaN(cur[i]) || cur[i] == '_')) + --i; + + if (i > 0) { + var cur2 = cur.substr(0, i + 1); + if (variable_3.propertyIsEnumerable(cur2)) { + if (blockKeywords.propertyIsEnumerable(cur2)) curPunc = "newstatement"; + return "variable-3"; + } + } + } + if (atoms.propertyIsEnumerable(cur)) return "atom"; + return null; + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) {end = true; break;} + escaped = !escaped && next == "\\"; + } + if (end || !(escaped || multiLineStrings)) + state.tokenize = tokenBase; + return "string"; + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + + function Context(indented, column, type, align, prev) { + this.indented = indented; + this.column = column; + this.type = type; + this.align = align; + this.prev = prev; + } + function pushContext(state, col, type) { + return state.context = new Context(state.indented, col, type, null, state.context); + } + function popContext(state) { + var t = state.context.type; + if (t == ")" || t == "]" || t == "}") + state.indented = state.context.indented; + return state.context = state.context.prev; + } + + // Interface + + return { + startState: function(basecolumn) { + return { + tokenize: null, + context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), + indented: 0, + startOfLine: true + }; + }, + + token: function(stream, state) { + var ctx = state.context; + if (stream.sol()) { + if (ctx.align == null) ctx.align = false; + state.indented = stream.indentation(); + state.startOfLine = true; + } + if (stream.eatSpace()) return null; + curPunc = null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style == "comment" || style == "meta") return style; + if (ctx.align == null) ctx.align = true; + + if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state); + else if (curPunc == "{") pushContext(state, stream.column(), "}"); + else if (curPunc == "[") pushContext(state, stream.column(), "]"); + else if (curPunc == "(") pushContext(state, stream.column(), ")"); + else if (curPunc == "}") { + while (ctx.type == "statement") ctx = popContext(state); + if (ctx.type == "}") ctx = popContext(state); + while (ctx.type == "statement") ctx = popContext(state); + } + else if (curPunc == ctx.type) popContext(state); + else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement")) + pushContext(state, stream.column(), "statement"); + state.startOfLine = false; + return style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase && state.tokenize != null) return 0; + var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); + if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev; + var closing = firstChar == ctx.type; + if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit); + else if (ctx.align) return ctx.column + (closing ? 0 : 1); + else return ctx.indented + (closing ? 0 : indentUnit); + }, + + electricChars: "{}" + }; +}); + +CodeMirror.defineMIME("text/x-ecl", "ecl"); diff --git a/codemirror/mode/ecl/index.html b/codemirror/mode/ecl/index.html new file mode 100644 index 0000000..0ba88c3 --- /dev/null +++ b/codemirror/mode/ecl/index.html @@ -0,0 +1,39 @@ + + + + CodeMirror: ECL mode + + + + + + + +

CodeMirror: ECL mode

+
+ + +

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

+

MIME types defined: text/x-ecl.

+ + + diff --git a/codemirror/mode/erlang/erlang.js b/codemirror/mode/erlang/erlang.js new file mode 100644 index 0000000..accf24e --- /dev/null +++ b/codemirror/mode/erlang/erlang.js @@ -0,0 +1,463 @@ +// block; "begin", "case", "fun", "if", "receive", "try": closed by "end" +// block internal; "after", "catch", "of" +// guard; "when", closed by "->" +// "->" opens a clause, closed by ";" or "." +// "<<" opens a binary, closed by ">>" +// "," appears in arglists, lists, tuples and terminates lines of code +// "." resets indentation to 0 +// obsolete; "cond", "let", "query" + +CodeMirror.defineMIME("text/x-erlang", "erlang"); + +CodeMirror.defineMode("erlang", function(cmCfg) { + + function rval(state,stream,type) { + // distinguish between "." as terminator and record field operator + if (type == "record") { + state.context = "record"; + }else{ + state.context = false; + } + + // remember last significant bit on last line for indenting + if (type != "whitespace" && type != "comment") { + state.lastToken = stream.current(); + } + // erlang -> CodeMirror tag + switch (type) { + case "atom": return "atom"; + case "attribute": return "attribute"; + case "builtin": return "builtin"; + case "comment": return "comment"; + case "fun": return "meta"; + case "function": return "tag"; + case "guard": return "property"; + case "keyword": return "keyword"; + case "macro": return "variable-2"; + case "number": return "number"; + case "operator": return "operator"; + case "record": return "bracket"; + case "string": return "string"; + case "type": return "def"; + case "variable": return "variable"; + case "error": return "error"; + case "separator": return null; + case "open_paren": return null; + case "close_paren": return null; + default: return null; + } + } + + var typeWords = [ + "-type", "-spec", "-export_type", "-opaque"]; + + var keywordWords = [ + "after","begin","catch","case","cond","end","fun","if", + "let","of","query","receive","try","when"]; + + var separatorWords = [ + "->",";",":",".",","]; + + var operatorWords = [ + "and","andalso","band","bnot","bor","bsl","bsr","bxor", + "div","not","or","orelse","rem","xor"]; + + var symbolWords = [ + "+","-","*","/",">",">=","<","=<","=:=","==","=/=","/=","||","<-"]; + + var openParenWords = [ + "<<","(","[","{"]; + + var closeParenWords = [ + "}","]",")",">>"]; + + var guardWords = [ + "is_atom","is_binary","is_bitstring","is_boolean","is_float", + "is_function","is_integer","is_list","is_number","is_pid", + "is_port","is_record","is_reference","is_tuple", + "atom","binary","bitstring","boolean","function","integer","list", + "number","pid","port","record","reference","tuple"]; + + var bifWords = [ + "abs","adler32","adler32_combine","alive","apply","atom_to_binary", + "atom_to_list","binary_to_atom","binary_to_existing_atom", + "binary_to_list","binary_to_term","bit_size","bitstring_to_list", + "byte_size","check_process_code","contact_binary","crc32", + "crc32_combine","date","decode_packet","delete_module", + "disconnect_node","element","erase","exit","float","float_to_list", + "garbage_collect","get","get_keys","group_leader","halt","hd", + "integer_to_list","internal_bif","iolist_size","iolist_to_binary", + "is_alive","is_atom","is_binary","is_bitstring","is_boolean", + "is_float","is_function","is_integer","is_list","is_number","is_pid", + "is_port","is_process_alive","is_record","is_reference","is_tuple", + "length","link","list_to_atom","list_to_binary","list_to_bitstring", + "list_to_existing_atom","list_to_float","list_to_integer", + "list_to_pid","list_to_tuple","load_module","make_ref","module_loaded", + "monitor_node","node","node_link","node_unlink","nodes","notalive", + "now","open_port","pid_to_list","port_close","port_command", + "port_connect","port_control","pre_loaded","process_flag", + "process_info","processes","purge_module","put","register", + "registered","round","self","setelement","size","spawn","spawn_link", + "spawn_monitor","spawn_opt","split_binary","statistics", + "term_to_binary","time","throw","tl","trunc","tuple_size", + "tuple_to_list","unlink","unregister","whereis"]; + + // ignored for indenting purposes + var ignoreWords = [ + ",", ":", "catch", "after", "of", "cond", "let", "query"]; + + + var smallRE = /[a-z_]/; + var largeRE = /[A-Z_]/; + var digitRE = /[0-9]/; + var octitRE = /[0-7]/; + var anumRE = /[a-z_A-Z0-9]/; + var symbolRE = /[\+\-\*\/<>=\|:]/; + var openParenRE = /[<\(\[\{]/; + var closeParenRE = /[>\)\]\}]/; + var sepRE = /[\->\.,:;]/; + + function isMember(element,list) { + return (-1 < list.indexOf(element)); + } + + function isPrev(stream,string) { + var start = stream.start; + var len = string.length; + if (len <= start) { + var word = stream.string.slice(start-len,start); + return word == string; + }else{ + return false; + } + } + + function tokenize(stream, state) { + if (stream.eatSpace()) { + return rval(state,stream,"whitespace"); + } + + // attributes and type specs + if ((peekToken(state).token == "" || peekToken(state).token == ".") && + stream.peek() == '-') { + stream.next(); + if (stream.eat(smallRE) && stream.eatWhile(anumRE)) { + if (isMember(stream.current(),typeWords)) { + return rval(state,stream,"type"); + }else{ + return rval(state,stream,"attribute"); + } + } + stream.backUp(1); + } + + var ch = stream.next(); + + // comment + if (ch == '%') { + stream.skipToEnd(); + return rval(state,stream,"comment"); + } + + // macro + if (ch == '?') { + stream.eatWhile(anumRE); + return rval(state,stream,"macro"); + } + + // record + if ( ch == "#") { + stream.eatWhile(anumRE); + return rval(state,stream,"record"); + } + + // char + if ( ch == "$") { + if (stream.next() == "\\") { + if (!stream.eatWhile(octitRE)) { + stream.next(); + } + } + return rval(state,stream,"string"); + } + + // quoted atom + if (ch == '\'') { + if (singleQuote(stream)) { + return rval(state,stream,"atom"); + }else{ + return rval(state,stream,"error"); + } + } + + // string + if (ch == '"') { + if (doubleQuote(stream)) { + return rval(state,stream,"string"); + }else{ + return rval(state,stream,"error"); + } + } + + // variable + if (largeRE.test(ch)) { + stream.eatWhile(anumRE); + return rval(state,stream,"variable"); + } + + // atom/keyword/BIF/function + if (smallRE.test(ch)) { + stream.eatWhile(anumRE); + + if (stream.peek() == "/") { + stream.next(); + if (stream.eatWhile(digitRE)) { + return rval(state,stream,"fun"); // f/0 style fun + }else{ + stream.backUp(1); + return rval(state,stream,"atom"); + } + } + + var w = stream.current(); + + if (isMember(w,keywordWords)) { + pushToken(state,stream); + return rval(state,stream,"keyword"); + } + if (stream.peek() == "(") { + // 'put' and 'erlang:put' are bifs, 'foo:put' is not + if (isMember(w,bifWords) && + (!isPrev(stream,":") || isPrev(stream,"erlang:"))) { + return rval(state,stream,"builtin"); + }else{ + return rval(state,stream,"function"); + } + } + if (isMember(w,guardWords)) { + return rval(state,stream,"guard"); + } + if (isMember(w,operatorWords)) { + return rval(state,stream,"operator"); + } + if (stream.peek() == ":") { + if (w == "erlang") { + return rval(state,stream,"builtin"); + } else { + return rval(state,stream,"function"); + } + } + return rval(state,stream,"atom"); + } + + // number + if (digitRE.test(ch)) { + stream.eatWhile(digitRE); + if (stream.eat('#')) { + stream.eatWhile(digitRE); // 16#10 style integer + } else { + if (stream.eat('.')) { // float + stream.eatWhile(digitRE); + } + if (stream.eat(/[eE]/)) { + stream.eat(/[-+]/); // float with exponent + stream.eatWhile(digitRE); + } + } + return rval(state,stream,"number"); // normal integer + } + + // open parens + if (nongreedy(stream,openParenRE,openParenWords)) { + pushToken(state,stream); + return rval(state,stream,"open_paren"); + } + + // close parens + if (nongreedy(stream,closeParenRE,closeParenWords)) { + pushToken(state,stream); + return rval(state,stream,"close_paren"); + } + + // separators + if (greedy(stream,sepRE,separatorWords)) { + // distinguish between "." as terminator and record field operator + if (state.context == false) { + pushToken(state,stream); + } + return rval(state,stream,"separator"); + } + + // operators + if (greedy(stream,symbolRE,symbolWords)) { + return rval(state,stream,"operator"); + } + + return rval(state,stream,null); + } + + function nongreedy(stream,re,words) { + if (stream.current().length == 1 && re.test(stream.current())) { + stream.backUp(1); + while (re.test(stream.peek())) { + stream.next(); + if (isMember(stream.current(),words)) { + return true; + } + } + stream.backUp(stream.current().length-1); + } + return false; + } + + function greedy(stream,re,words) { + if (stream.current().length == 1 && re.test(stream.current())) { + while (re.test(stream.peek())) { + stream.next(); + } + while (0 < stream.current().length) { + if (isMember(stream.current(),words)) { + return true; + }else{ + stream.backUp(1); + } + } + stream.next(); + } + return false; + } + + function doubleQuote(stream) { + return quote(stream, '"', '\\'); + } + + function singleQuote(stream) { + return quote(stream,'\'','\\'); + } + + function quote(stream,quoteChar,escapeChar) { + while (!stream.eol()) { + var ch = stream.next(); + if (ch == quoteChar) { + return true; + }else if (ch == escapeChar) { + stream.next(); + } + } + return false; + } + + function Token(stream) { + this.token = stream ? stream.current() : ""; + this.column = stream ? stream.column() : 0; + this.indent = stream ? stream.indentation() : 0; + } + + function myIndent(state,textAfter) { + var indent = cmCfg.indentUnit; + var outdentWords = ["after","catch"]; + var token = (peekToken(state)).token; + var wordAfter = takewhile(textAfter,/[^a-z]/); + + if (isMember(token,openParenWords)) { + return (peekToken(state)).column+token.length; + }else if (token == "." || token == ""){ + return 0; + }else if (token == "->") { + if (wordAfter == "end") { + return peekToken(state,2).column; + }else if (peekToken(state,2).token == "fun") { + return peekToken(state,2).column+indent; + }else{ + return (peekToken(state)).indent+indent; + } + }else if (isMember(wordAfter,outdentWords)) { + return (peekToken(state)).indent; + }else{ + return (peekToken(state)).column+indent; + } + } + + function takewhile(str,re) { + var m = str.match(re); + return m ? str.slice(0,m.index) : str; + } + + function popToken(state) { + return state.tokenStack.pop(); + } + + function peekToken(state,depth) { + var len = state.tokenStack.length; + var dep = (depth ? depth : 1); + if (len < dep) { + return new Token; + }else{ + return state.tokenStack[len-dep]; + } + } + + function pushToken(state,stream) { + var token = stream.current(); + var prev_token = peekToken(state).token; + if (isMember(token,ignoreWords)) { + return false; + }else if (drop_both(prev_token,token)) { + popToken(state); + return false; + }else if (drop_first(prev_token,token)) { + popToken(state); + return pushToken(state,stream); + }else{ + state.tokenStack.push(new Token(stream)); + return true; + } + } + + function drop_first(open, close) { + switch (open+" "+close) { + case "when ->": return true; + case "-> end": return true; + case "-> .": return true; + case ". .": return true; + default: return false; + } + } + + function drop_both(open, close) { + switch (open+" "+close) { + case "( )": return true; + case "[ ]": return true; + case "{ }": return true; + case "<< >>": return true; + case "begin end": return true; + case "case end": return true; + case "fun end": return true; + case "if end": return true; + case "receive end": return true; + case "try end": return true; + case "-> ;": return true; + default: return false; + } + } + + return { + startState: + function() { + return {tokenStack: [], + context: false, + lastToken: null}; + }, + + token: + function(stream, state) { + return tokenize(stream, state); + }, + + indent: + function(state, textAfter) { +// console.log(state.tokenStack); + return myIndent(state,textAfter); + } + }; +}); diff --git a/codemirror/mode/erlang/index.html b/codemirror/mode/erlang/index.html new file mode 100644 index 0000000..f6bee8f --- /dev/null +++ b/codemirror/mode/erlang/index.html @@ -0,0 +1,64 @@ + + + + + CodeMirror: Erlang mode + + + + + + + + + +

CodeMirror: Erlang mode

+ +
+ + + +

MIME types defined: text/x-erlang.

+ + diff --git a/codemirror/mode/gfm/gfm.js b/codemirror/mode/gfm/gfm.js new file mode 100644 index 0000000..6ff557f --- /dev/null +++ b/codemirror/mode/gfm/gfm.js @@ -0,0 +1,94 @@ +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()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i)) { + // URLs + // Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls + return "link"; + } + stream.next(); + return null; + }, + blankLine: blankLine + }; + CodeMirror.defineMIME("gfmBase", { + name: "markdown", + underscoresBreakWords: false, + fencedCodeBlocks: true + }); + return CodeMirror.overlayMode(CodeMirror.getMode(config, "gfmBase"), gfmOverlay); +}, "markdown"); diff --git a/codemirror/mode/gfm/index.html b/codemirror/mode/gfm/index.html new file mode 100644 index 0000000..e4ea473 --- /dev/null +++ b/codemirror/mode/gfm/index.html @@ -0,0 +1,70 @@ + + + + + CodeMirror: GFM mode + + + + + + + + + + + + + + + + + + +

CodeMirror: GFM mode

+ +
+ + + +

Optionally depends on other modes for properly highlighted code blocks.

+ +

Parsing/Highlighting Tests: normal, verbose.

+ + + diff --git a/codemirror/mode/gfm/test.js b/codemirror/mode/gfm/test.js new file mode 100644 index 0000000..3a261f8 --- /dev/null +++ b/codemirror/mode/gfm/test.js @@ -0,0 +1,225 @@ +// Initiate ModeTest and set defaults +var MT = ModeTest; +MT.modeName = 'gfm'; +MT.modeOptions = {}; + +// Emphasis characters within a word +MT.testMode( + 'emInWordAsterisk', + 'foo*bar*hello', + [ + null, 'foo', + 'em', '*bar*', + null, 'hello' + ] +); +MT.testMode( + 'emInWordUnderscore', + 'foo_bar_hello', + [ + null, 'foo_bar_hello' + ] +); +MT.testMode( + 'emStrongUnderscore', + '___foo___ bar', + [ + 'strong', '__', + 'emstrong', '_foo__', + 'em', '_', + null, ' bar' + ] +); + +// Fenced code blocks +MT.testMode( + 'fencedCodeBlocks', + '```\nfoo\n\n```\nbar', + [ + 'comment', '```', + 'comment', 'foo', + 'comment', '```', + null, 'bar' + ] +); +// Fenced code block mode switching +MT.testMode( + 'fencedCodeBlockModeSwitching', + '```javascript\nfoo\n\n```\nbar', + [ + 'comment', '```javascript', + 'variable', 'foo', + 'comment', '```', + null, 'bar' + ] +); + +// SHA +MT.testMode( + 'SHA', + 'foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2 bar', + [ + null, 'foo ', + 'link', 'be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2', + null, ' bar' + ] +); +// GitHub highlights hashes 7-40 chars in length +MT.testMode( + 'shortSHA', + 'foo be6a8cc bar', + [ + null, 'foo ', + 'link', 'be6a8cc', + null, ' bar' + ] +); +// Invalid SHAs +// +// GitHub does not highlight hashes shorter than 7 chars +MT.testMode( + 'tooShortSHA', + 'foo be6a8c bar', + [ + null, 'foo be6a8c bar' + ] +); +// GitHub does not highlight hashes longer than 40 chars +MT.testMode( + 'longSHA', + 'foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd22 bar', + [ + null, 'foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd22 bar' + ] +); +MT.testMode( + 'badSHA', + 'foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cg2 bar', + [ + null, 'foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cg2 bar' + ] +); +// User@SHA +MT.testMode( + 'userSHA', + 'foo bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2 hello', + [ + null, 'foo ', + 'link', 'bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2', + null, ' hello' + ] +); +// User/Project@SHA +MT.testMode( + 'userProjectSHA', + 'foo bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2 world', + [ + null, 'foo ', + 'link', 'bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2', + null, ' world' + ] +); + +// #Num +MT.testMode( + 'num', + 'foo #1 bar', + [ + null, 'foo ', + 'link', '#1', + null, ' bar' + ] +); +// bad #Num +MT.testMode( + 'badNum', + 'foo #1bar hello', + [ + null, 'foo #1bar hello' + ] +); +// User#Num +MT.testMode( + 'userNum', + 'foo bar#1 hello', + [ + null, 'foo ', + 'link', 'bar#1', + null, ' hello' + ] +); +// User/Project#Num +MT.testMode( + 'userProjectNum', + 'foo bar/hello#1 world', + [ + null, 'foo ', + 'link', 'bar/hello#1', + null, ' world' + ] +); + +// Vanilla links +MT.testMode( + 'vanillaLink', + 'foo http://www.example.com/ bar', + [ + null, 'foo ', + 'link', 'http://www.example.com/', + null, ' bar' + ] +); +MT.testMode( + 'vanillaLinkPunctuation', + 'foo http://www.example.com/. bar', + [ + null, 'foo ', + 'link', 'http://www.example.com/', + null, '. bar' + ] +); +MT.testMode( + 'vanillaLinkExtension', + 'foo http://www.example.com/index.html bar', + [ + null, 'foo ', + 'link', 'http://www.example.com/index.html', + null, ' bar' + ] +); +// Not a link +MT.testMode( + 'notALink', + '```css\nfoo {color:black;}\n```http://www.example.com/', + [ + 'comment', '```css', + 'tag', 'foo', + null, ' {', + 'property', 'color', + 'operator', ':', + 'keyword', 'black', + null, ';}', + 'comment', '```', + 'link', 'http://www.example.com/' + ] +); +// Not a link +MT.testMode( + 'notALink', + '``foo `bar` http://www.example.com/`` hello', + [ + 'comment', '``foo `bar` http://www.example.com/``', + null, ' hello' + ] +); +// Not a link +MT.testMode( + 'notALink', + '`foo\nhttp://www.example.com/\n`foo\n\nhttp://www.example.com/', + [ + 'comment', '`foo', + 'link', 'http://www.example.com/', + 'comment', '`foo', + 'link', 'http://www.example.com/' + ] +); \ No newline at end of file diff --git a/codemirror/mode/go/go.js b/codemirror/mode/go/go.js new file mode 100644 index 0000000..8b84a5c --- /dev/null +++ b/codemirror/mode/go/go.js @@ -0,0 +1,165 @@ +CodeMirror.defineMode("go", function(config) { + var indentUnit = config.indentUnit; + + var keywords = { + "break":true, "case":true, "chan":true, "const":true, "continue":true, + "default":true, "defer":true, "else":true, "fallthrough":true, "for":true, + "func":true, "go":true, "goto":true, "if":true, "import":true, + "interface":true, "map":true, "package":true, "range":true, "return":true, + "select":true, "struct":true, "switch":true, "type":true, "var":true, + "bool":true, "byte":true, "complex64":true, "complex128":true, + "float32":true, "float64":true, "int8":true, "int16":true, "int32":true, + "int64":true, "string":true, "uint8":true, "uint16":true, "uint32":true, + "uint64":true, "int":true, "uint":true, "uintptr":true + }; + + var atoms = { + "true":true, "false":true, "iota":true, "nil":true, "append":true, + "cap":true, "close":true, "complex":true, "copy":true, "imag":true, + "len":true, "make":true, "new":true, "panic":true, "print":true, + "println":true, "real":true, "recover":true + }; + + var isOperatorChar = /[+\-*&^%:=<>!|\/]/; + + var curPunc; + + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'" || ch == "`") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + if (/[\d\.]/.test(ch)) { + if (ch == ".") { + stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/); + } else if (ch == "0") { + stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/); + } else { + stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/); + } + return "number"; + } + if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + curPunc = ch; + return null; + } + if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } + if (stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } + } + if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return "operator"; + } + stream.eatWhile(/[\w\$_]/); + var cur = stream.current(); + if (keywords.propertyIsEnumerable(cur)) { + if (cur == "case" || cur == "default") curPunc = "case"; + return "keyword"; + } + if (atoms.propertyIsEnumerable(cur)) return "atom"; + return "variable"; + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) {end = true; break;} + escaped = !escaped && next == "\\"; + } + if (end || !(escaped || quote == "`")) + state.tokenize = tokenBase; + return "string"; + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + + function Context(indented, column, type, align, prev) { + this.indented = indented; + this.column = column; + this.type = type; + this.align = align; + this.prev = prev; + } + function pushContext(state, col, type) { + return state.context = new Context(state.indented, col, type, null, state.context); + } + function popContext(state) { + var t = state.context.type; + if (t == ")" || t == "]" || t == "}") + state.indented = state.context.indented; + return state.context = state.context.prev; + } + + // Interface + + return { + startState: function(basecolumn) { + return { + tokenize: null, + context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), + indented: 0, + startOfLine: true + }; + }, + + token: function(stream, state) { + var ctx = state.context; + if (stream.sol()) { + if (ctx.align == null) ctx.align = false; + state.indented = stream.indentation(); + state.startOfLine = true; + if (ctx.type == "case") ctx.type = "}"; + } + if (stream.eatSpace()) return null; + curPunc = null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style == "comment") return style; + if (ctx.align == null) ctx.align = true; + + if (curPunc == "{") pushContext(state, stream.column(), "}"); + else if (curPunc == "[") pushContext(state, stream.column(), "]"); + else if (curPunc == "(") pushContext(state, stream.column(), ")"); + else if (curPunc == "case") ctx.type = "case"; + else if (curPunc == "}" && ctx.type == "}") ctx = popContext(state); + else if (curPunc == ctx.type) popContext(state); + state.startOfLine = false; + return style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase && state.tokenize != null) return 0; + var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); + if (ctx.type == "case" && /^(?:case|default)\b/.test(textAfter)) { + state.context.type = "}"; + return ctx.indented; + } + var closing = firstChar == ctx.type; + if (ctx.align) return ctx.column + (closing ? 0 : 1); + else return ctx.indented + (closing ? 0 : indentUnit); + }, + + electricChars: "{}:" + }; +}); + +CodeMirror.defineMIME("text/x-go", "go"); diff --git a/codemirror/mode/go/index.html b/codemirror/mode/go/index.html new file mode 100644 index 0000000..1a9ef53 --- /dev/null +++ b/codemirror/mode/go/index.html @@ -0,0 +1,74 @@ + + + + + CodeMirror: Go mode + + + + + + + + + +

CodeMirror: Go mode

+ +
+ + + +

MIME type: text/x-go

+ + diff --git a/codemirror/mode/groovy/groovy.js b/codemirror/mode/groovy/groovy.js new file mode 100644 index 0000000..92b9481 --- /dev/null +++ b/codemirror/mode/groovy/groovy.js @@ -0,0 +1,210 @@ +CodeMirror.defineMode("groovy", function(config) { + function words(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + var keywords = words( + "abstract as assert boolean break byte case catch char class const continue def default " + + "do double else enum extends final finally float for goto if implements import in " + + "instanceof int interface long native new package private protected public return " + + "short static strictfp super switch synchronized threadsafe throw throws transient " + + "try void volatile while"); + var blockKeywords = words("catch class do else finally for if switch try while enum interface def"); + var atoms = words("null true false this"); + + var curPunc; + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") { + return startString(ch, stream, state); + } + if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + curPunc = ch; + return null; + } + if (/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/); + if (stream.eat(/eE/)) { stream.eat(/\+\-/); stream.eatWhile(/\d/); } + return "number"; + } + if (ch == "/") { + if (stream.eat("*")) { + state.tokenize.push(tokenComment); + return tokenComment(stream, state); + } + if (stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } + if (expectExpression(state.lastToken)) { + return startString(ch, stream, state); + } + } + if (ch == "-" && stream.eat(">")) { + curPunc = "->"; + return null; + } + if (/[+\-*&%=<>!?|\/~]/.test(ch)) { + stream.eatWhile(/[+\-*&%=<>|~]/); + return "operator"; + } + stream.eatWhile(/[\w\$_]/); + if (ch == "@") { stream.eatWhile(/[\w\$_\.]/); return "meta"; } + if (state.lastToken == ".") return "property"; + if (stream.eat(":")) { curPunc = "proplabel"; return "property"; } + var cur = stream.current(); + if (atoms.propertyIsEnumerable(cur)) { return "atom"; } + if (keywords.propertyIsEnumerable(cur)) { + if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; + return "keyword"; + } + return "variable"; + } + tokenBase.isBase = true; + + function startString(quote, stream, state) { + var tripleQuoted = false; + if (quote != "/" && stream.eat(quote)) { + if (stream.eat(quote)) tripleQuoted = true; + else return "string"; + } + function t(stream, state) { + var escaped = false, next, end = !tripleQuoted; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) { + if (!tripleQuoted) { break; } + if (stream.match(quote + quote)) { end = true; break; } + } + if (quote == '"' && next == "$" && !escaped && stream.eat("{")) { + state.tokenize.push(tokenBaseUntilBrace()); + return "string"; + } + escaped = !escaped && next == "\\"; + } + if (end) state.tokenize.pop(); + return "string"; + } + state.tokenize.push(t); + return t(stream, state); + } + + function tokenBaseUntilBrace() { + var depth = 1; + function t(stream, state) { + if (stream.peek() == "}") { + depth--; + if (depth == 0) { + state.tokenize.pop(); + return state.tokenize[state.tokenize.length-1](stream, state); + } + } else if (stream.peek() == "{") { + depth++; + } + return tokenBase(stream, state); + } + t.isBase = true; + return t; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize.pop(); + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + + function expectExpression(last) { + return !last || last == "operator" || last == "->" || /[\.\[\{\(,;:]/.test(last) || + last == "newstatement" || last == "keyword" || last == "proplabel"; + } + + function Context(indented, column, type, align, prev) { + this.indented = indented; + this.column = column; + this.type = type; + this.align = align; + this.prev = prev; + } + function pushContext(state, col, type) { + return state.context = new Context(state.indented, col, type, null, state.context); + } + function popContext(state) { + var t = state.context.type; + if (t == ")" || t == "]" || t == "}") + state.indented = state.context.indented; + return state.context = state.context.prev; + } + + // Interface + + return { + startState: function(basecolumn) { + return { + tokenize: [tokenBase], + context: new Context((basecolumn || 0) - config.indentUnit, 0, "top", false), + indented: 0, + startOfLine: true, + lastToken: null + }; + }, + + token: function(stream, state) { + var ctx = state.context; + if (stream.sol()) { + if (ctx.align == null) ctx.align = false; + state.indented = stream.indentation(); + state.startOfLine = true; + // Automatic semicolon insertion + if (ctx.type == "statement" && !expectExpression(state.lastToken)) { + popContext(state); ctx = state.context; + } + } + if (stream.eatSpace()) return null; + curPunc = null; + var style = state.tokenize[state.tokenize.length-1](stream, state); + if (style == "comment") return style; + if (ctx.align == null) ctx.align = true; + + if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state); + // Handle indentation for {x -> \n ... } + else if (curPunc == "->" && ctx.type == "statement" && ctx.prev.type == "}") { + popContext(state); + state.context.align = false; + } + else if (curPunc == "{") pushContext(state, stream.column(), "}"); + else if (curPunc == "[") pushContext(state, stream.column(), "]"); + else if (curPunc == "(") pushContext(state, stream.column(), ")"); + else if (curPunc == "}") { + while (ctx.type == "statement") ctx = popContext(state); + if (ctx.type == "}") ctx = popContext(state); + while (ctx.type == "statement") ctx = popContext(state); + } + else if (curPunc == ctx.type) popContext(state); + else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement")) + pushContext(state, stream.column(), "statement"); + state.startOfLine = false; + state.lastToken = curPunc || style; + return style; + }, + + indent: function(state, textAfter) { + if (!state.tokenize[state.tokenize.length-1].isBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), ctx = state.context; + if (ctx.type == "statement" && !expectExpression(state.lastToken)) ctx = ctx.prev; + var closing = firstChar == ctx.type; + if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : config.indentUnit); + else if (ctx.align) return ctx.column + (closing ? 0 : 1); + else return ctx.indented + (closing ? 0 : config.indentUnit); + }, + + electricChars: "{}" + }; +}); + +CodeMirror.defineMIME("text/x-groovy", "groovy"); diff --git a/codemirror/mode/groovy/index.html b/codemirror/mode/groovy/index.html new file mode 100644 index 0000000..d0d76bf --- /dev/null +++ b/codemirror/mode/groovy/index.html @@ -0,0 +1,73 @@ + + + + + CodeMirror: Groovy mode + + + + + + + + +

CodeMirror: Groovy mode

+ +
+ + + +

MIME types defined: text/x-groovy

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

CodeMirror: Haskell mode

+ +
+ + + +

MIME types defined: text/x-haskell.

+ + diff --git a/codemirror/mode/haxe/haxe.js b/codemirror/mode/haxe/haxe.js new file mode 100644 index 0000000..c99074b --- /dev/null +++ b/codemirror/mode/haxe/haxe.js @@ -0,0 +1,429 @@ +CodeMirror.defineMode("haxe", function(config, parserConfig) { + var indentUnit = config.indentUnit; + + // Tokenizer + + var keywords = function(){ + function kw(type) {return {type: type, style: "keyword"};} + var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"); + var operator = kw("operator"), atom = {type: "atom", style: "atom"}, attribute = {type:"attribute", style: "attribute"}; + var type = kw("typedef"); + return { + "if": A, "while": A, "else": B, "do": B, "try": B, + "return": C, "break": C, "continue": C, "new": C, "throw": C, + "var": kw("var"), "inline":attribute, "static": attribute, "using":kw("import"), + "public": attribute, "private": attribute, "cast": kw("cast"), "import": kw("import"), "macro": kw("macro"), + "function": kw("function"), "catch": kw("catch"), "untyped": kw("untyped"), "callback": kw("cb"), + "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), + "in": operator, "never": kw("property_access"), "trace":kw("trace"), + "class": type, "enum":type, "interface":type, "typedef":type, "extends":type, "implements":type, "dynamic":type, + "true": atom, "false": atom, "null": atom + }; + }(); + + var isOperatorChar = /[+\-*&%=<>!?|]/; + + function chain(stream, state, f) { + state.tokenize = f; + return f(stream, state); + } + + function nextUntilUnescaped(stream, end) { + var escaped = false, next; + while ((next = stream.next()) != null) { + if (next == end && !escaped) + return false; + escaped = !escaped && next == "\\"; + } + return escaped; + } + + // Used as scratch variables to communicate multiple values without + // consing up tons of objects. + var type, content; + function ret(tp, style, cont) { + type = tp; content = cont; + return style; + } + + function haxeTokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") + return chain(stream, state, haxeTokenString(ch)); + else if (/[\[\]{}\(\),;\:\.]/.test(ch)) + return ret(ch); + else if (ch == "0" && stream.eat(/x/i)) { + stream.eatWhile(/[\da-f]/i); + return ret("number", "number"); + } + else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) { + stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); + return ret("number", "number"); + } + else if (state.reAllowed && (ch == "~" && stream.eat(/\//))) { + nextUntilUnescaped(stream, "/"); + stream.eatWhile(/[gimsu]/); + return ret("regexp", "string-2"); + } + else if (ch == "/") { + if (stream.eat("*")) { + return chain(stream, state, haxeTokenComment); + } + else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } + else { + stream.eatWhile(isOperatorChar); + return ret("operator", null, stream.current()); + } + } + else if (ch == "#") { + stream.skipToEnd(); + return ret("conditional", "meta"); + } + else if (ch == "@") { + stream.eat(/:/); + stream.eatWhile(/[\w_]/); + return ret ("metadata", "meta"); + } + else if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return ret("operator", null, stream.current()); + } + else { + var word; + if(/[A-Z]/.test(ch)) + { + stream.eatWhile(/[\w_<>]/); + word = stream.current(); + return ret("type", "variable-3", word); + } + else + { + stream.eatWhile(/[\w_]/); + var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; + return (known && state.kwAllowed) ? ret(known.type, known.style, word) : + ret("variable", "variable", word); + } + } + } + + function haxeTokenString(quote) { + return function(stream, state) { + if (!nextUntilUnescaped(stream, quote)) + state.tokenize = haxeTokenBase; + return ret("string", "string"); + }; + } + + function haxeTokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = haxeTokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return ret("comment", "comment"); + } + + // Parser + + var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true}; + + function HaxeLexical(indented, column, type, align, prev, info) { + this.indented = indented; + this.column = column; + this.type = type; + this.prev = prev; + this.info = info; + if (align != null) this.align = align; + } + + function inScope(state, varname) { + for (var v = state.localVars; v; v = v.next) + if (v.name == varname) return true; + } + + function parseHaxe(state, style, type, content, stream) { + var cc = state.cc; + // Communicate our context to the combinators. + // (Less wasteful than consing up a hundred closures on every call.) + cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; + + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = true; + + while(true) { + var combinator = cc.length ? cc.pop() : statement; + if (combinator(type, content)) { + while(cc.length && cc[cc.length - 1].lex) + cc.pop()(); + if (cx.marked) return cx.marked; + if (type == "variable" && inScope(state, content)) return "variable-2"; + if (type == "variable" && imported(state, content)) return "variable-3"; + return style; + } + } + } + + function imported(state, typename) + { + if (/[a-z]/.test(typename.charAt(0))) + return false; + var len = state.importedtypes.length; + for (var i = 0; i= 0; i--) cx.cc.push(arguments[i]); + } + function cont() { + pass.apply(null, arguments); + return true; + } + function register(varname) { + var state = cx.state; + if (state.context) { + cx.marked = "def"; + for (var v = state.localVars; v; v = v.next) + if (v.name == varname) return; + state.localVars = {name: varname, next: state.localVars}; + } + } + + // Combinators + + var defaultVars = {name: "this", next: null}; + function pushcontext() { + if (!cx.state.context) cx.state.localVars = defaultVars; + cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; + } + function popcontext() { + cx.state.localVars = cx.state.context.vars; + cx.state.context = cx.state.context.prev; + } + function pushlex(type, info) { + var result = function() { + var state = cx.state; + state.lexical = new HaxeLexical(state.indented, cx.stream.column(), type, null, state.lexical, info); + }; + result.lex = true; + return result; + } + function poplex() { + var state = cx.state; + if (state.lexical.prev) { + if (state.lexical.type == ")") + state.indented = state.lexical.indented; + state.lexical = state.lexical.prev; + } + } + poplex.lex = true; + + function expect(wanted) { + return function expecting(type) { + if (type == wanted) return cont(); + else if (wanted == ";") return pass(); + else return cont(arguments.callee); + }; + } + + function statement(type) { + if (type == "@") return cont(metadef); + if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex); + if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); + if (type == "keyword b") return cont(pushlex("form"), statement, poplex); + if (type == "{") return cont(pushlex("}"), pushcontext, block, poplex, popcontext); + if (type == ";") return cont(); + if (type == "attribute") return cont(maybeattribute); + if (type == "function") return cont(functiondef); + if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), + poplex, statement, poplex); + if (type == "variable") return cont(pushlex("stat"), maybelabel); + if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), + block, poplex, poplex); + if (type == "case") return cont(expression, expect(":")); + if (type == "default") return cont(expect(":")); + if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), + statement, poplex, popcontext); + if (type == "import") return cont(importdef, expect(";")); + if (type == "typedef") return cont(typedef); + return pass(pushlex("stat"), expression, expect(";"), poplex); + } + function expression(type) { + if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator); + if (type == "function") return cont(functiondef); + if (type == "keyword c") return cont(maybeexpression); + if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeoperator); + if (type == "operator") return cont(expression); + if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator); + if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator); + return cont(); + } + function maybeexpression(type) { + if (type.match(/[;\}\)\],]/)) return pass(); + return pass(expression); + } + + function maybeoperator(type, value) { + if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator); + if (type == "operator" || type == ":") return cont(expression); + if (type == ";") return; + if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator); + if (type == ".") return cont(property, maybeoperator); + if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator); + } + + function maybeattribute(type) { + if (type == "attribute") return cont(maybeattribute); + if (type == "function") return cont(functiondef); + if (type == "var") return cont(vardef1); + } + + function metadef(type) { + if(type == ":") return cont(metadef); + if(type == "variable") return cont(metadef); + if(type == "(") return cont(pushlex(")"), comasep(metaargs, ")"), poplex, statement); + } + function metaargs(type) { + if(type == "variable") return cont(); + } + + function importdef (type, value) { + if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); } + else if(type == "variable" || type == "property" || type == ".") return cont(importdef); + } + + function typedef (type, value) + { + if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); } + } + + function maybelabel(type) { + if (type == ":") return cont(poplex, statement); + return pass(maybeoperator, expect(";"), poplex); + } + function property(type) { + if (type == "variable") {cx.marked = "property"; return cont();} + } + function objprop(type) { + if (type == "variable") cx.marked = "property"; + if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression); + } + function commasep(what, end) { + function proceed(type) { + if (type == ",") return cont(what, proceed); + if (type == end) return cont(); + return cont(expect(end)); + } + return function commaSeparated(type) { + if (type == end) return cont(); + else return pass(what, proceed); + }; + } + function block(type) { + if (type == "}") return cont(); + return pass(statement, block); + } + function vardef1(type, value) { + if (type == "variable"){register(value); return cont(typeuse, vardef2);} + return cont(); + } + function vardef2(type, value) { + if (value == "=") return cont(expression, vardef2); + if (type == ",") return cont(vardef1); + } + function forspec1(type, value) { + if (type == "variable") { + register(value); + } + return cont(pushlex(")"), pushcontext, forin, expression, poplex, statement, popcontext); + } + function forin(_type, value) { + if (value == "in") return cont(); + } + function functiondef(type, value) { + if (type == "variable") {register(value); return cont(functiondef);} + if (value == "new") return cont(functiondef); + if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, typeuse, statement, popcontext); + } + function typeuse(type) { + if(type == ":") return cont(typestring); + } + function typestring(type) { + if(type == "type") return cont(); + if(type == "variable") return cont(); + if(type == "{") return cont(pushlex("}"), commasep(typeprop, "}"), poplex); + } + function typeprop(type) { + if(type == "variable") return cont(typeuse); + } + function funarg(type, value) { + if (type == "variable") {register(value); return cont(typeuse);} + } + + // Interface + + return { + startState: function(basecolumn) { + var defaulttypes = ["Int", "Float", "String", "Void", "Std", "Bool", "Dynamic", "Array"]; + return { + tokenize: haxeTokenBase, + reAllowed: true, + kwAllowed: true, + cc: [], + lexical: new HaxeLexical((basecolumn || 0) - indentUnit, 0, "block", false), + localVars: parserConfig.localVars, + importedtypes: defaulttypes, + context: parserConfig.localVars && {vars: parserConfig.localVars}, + indented: 0 + }; + }, + + token: function(stream, state) { + if (stream.sol()) { + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = false; + state.indented = stream.indentation(); + } + if (stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (type == "comment") return style; + state.reAllowed = !!(type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/)); + state.kwAllowed = type != '.'; + return parseHaxe(state, style, type, content, stream); + }, + + indent: function(state, textAfter) { + if (state.tokenize != haxeTokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; + if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; + var type = lexical.type, closing = firstChar == type; + if (type == "vardef") return lexical.indented + 4; + else if (type == "form" && firstChar == "{") return lexical.indented; + else if (type == "stat" || type == "form") return lexical.indented + indentUnit; + else if (lexical.info == "switch" && !closing) + return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); + else if (lexical.align) return lexical.column + (closing ? 0 : 1); + else return lexical.indented + (closing ? 0 : indentUnit); + }, + + electricChars: "{}" + }; +}); + +CodeMirror.defineMIME("text/x-haxe", "haxe"); diff --git a/codemirror/mode/haxe/index.html b/codemirror/mode/haxe/index.html new file mode 100644 index 0000000..1125741 --- /dev/null +++ b/codemirror/mode/haxe/index.html @@ -0,0 +1,90 @@ + + + + + CodeMirror: Haxe mode + + + + + + + +

CodeMirror: Haxe mode

+ +
+ + + +

MIME types defined: text/x-haxe.

+ + diff --git a/codemirror/mode/htmlembedded/htmlembedded.js b/codemirror/mode/htmlembedded/htmlembedded.js new file mode 100644 index 0000000..e183d67 --- /dev/null +++ b/codemirror/mode/htmlembedded/htmlembedded.js @@ -0,0 +1,73 @@ +CodeMirror.defineMode("htmlembedded", function(config, parserConfig) { + + //config settings + var scriptStartRegex = parserConfig.scriptStartRegex || /^<%/i, + scriptEndRegex = parserConfig.scriptEndRegex || /^%>/i; + + //inner modes + var scriptingMode, htmlMixedMode; + + //tokenizer when in html mode + function htmlDispatch(stream, state) { + if (stream.match(scriptStartRegex, false)) { + state.token=scriptingDispatch; + return scriptingMode.token(stream, state.scriptState); + } + else + return htmlMixedMode.token(stream, state.htmlState); + } + + //tokenizer when in scripting mode + function scriptingDispatch(stream, state) { + if (stream.match(scriptEndRegex, false)) { + state.token=htmlDispatch; + return htmlMixedMode.token(stream, state.htmlState); + } + else + return scriptingMode.token(stream, state.scriptState); + } + + + return { + startState: function() { + scriptingMode = scriptingMode || CodeMirror.getMode(config, parserConfig.scriptingModeSpec); + htmlMixedMode = htmlMixedMode || CodeMirror.getMode(config, "htmlmixed"); + return { + token : parserConfig.startOpen ? scriptingDispatch : htmlDispatch, + htmlState : CodeMirror.startState(htmlMixedMode), + scriptState : CodeMirror.startState(scriptingMode) + }; + }, + + token: function(stream, state) { + return state.token(stream, state); + }, + + indent: function(state, textAfter) { + if (state.token == htmlDispatch) + return htmlMixedMode.indent(state.htmlState, textAfter); + else if (scriptingMode.indent) + return scriptingMode.indent(state.scriptState, textAfter); + }, + + copyState: function(state) { + return { + token : state.token, + htmlState : CodeMirror.copyState(htmlMixedMode, state.htmlState), + scriptState : CodeMirror.copyState(scriptingMode, state.scriptState) + }; + }, + + electricChars: "/{}:", + + innerMode: function(state) { + if (state.token == scriptingDispatch) return {state: state.scriptState, mode: scriptingMode}; + else return {state: state.htmlState, mode: htmlMixedMode}; + } + }; +}, "htmlmixed"); + +CodeMirror.defineMIME("application/x-ejs", { name: "htmlembedded", scriptingModeSpec:"javascript"}); +CodeMirror.defineMIME("application/x-aspx", { name: "htmlembedded", scriptingModeSpec:"text/x-csharp"}); +CodeMirror.defineMIME("application/x-jsp", { name: "htmlembedded", scriptingModeSpec:"text/x-java"}); +CodeMirror.defineMIME("application/x-erb", { name: "htmlembedded", scriptingModeSpec:"ruby"}); diff --git a/codemirror/mode/htmlembedded/index.html b/codemirror/mode/htmlembedded/index.html new file mode 100644 index 0000000..5a37dd6 --- /dev/null +++ b/codemirror/mode/htmlembedded/index.html @@ -0,0 +1,49 @@ + + + + + CodeMirror: Html Embedded Scripts mode + + + + + + + + + + + +

CodeMirror: Html Embedded Scripts mode

+ +
+ + + +

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

+ +

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

+ + diff --git a/codemirror/mode/htmlmixed/htmlmixed.js b/codemirror/mode/htmlmixed/htmlmixed.js new file mode 100644 index 0000000..f2dd01d --- /dev/null +++ b/codemirror/mode/htmlmixed/htmlmixed.js @@ -0,0 +1,84 @@ +CodeMirror.defineMode("htmlmixed", function(config) { + var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true}); + var jsMode = CodeMirror.getMode(config, "javascript"); + var cssMode = CodeMirror.getMode(config, "css"); + + function html(stream, state) { + var style = htmlMode.token(stream, state.htmlState); + if (/(?:^|\s)tag(?:\s|$)/.test(style) && stream.current() == ">" && state.htmlState.context) { + if (/^script$/i.test(state.htmlState.context.tagName)) { + state.token = javascript; + state.localState = jsMode.startState(htmlMode.indent(state.htmlState, "")); + } + else if (/^style$/i.test(state.htmlState.context.tagName)) { + state.token = css; + 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 javascript(stream, state) { + if (stream.match(/^<\/\s*script\s*>/i, false)) { + state.token = html; + state.localState = null; + return html(stream, state); + } + return maybeBackup(stream, /<\/\s*script\s*>/, + jsMode.token(stream, state.localState)); + } + function css(stream, state) { + if (stream.match(/^<\/\s*style\s*>/i, false)) { + state.token = html; + state.localState = 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, localState: null, mode: "html", htmlState: state}; + }, + + copyState: function(state) { + if (state.localState) + var local = CodeMirror.copyState(state.token == css ? cssMode : jsMode, state.localState); + return {token: state.token, localState: local, mode: state.mode, + htmlState: CodeMirror.copyState(htmlMode, state.htmlState)}; + }, + + token: function(stream, state) { + return state.token(stream, state); + }, + + indent: function(state, textAfter) { + if (state.token == html || /^\s*<\//.test(textAfter)) + return htmlMode.indent(state.htmlState, textAfter); + else if (state.token == javascript) + return jsMode.indent(state.localState, textAfter); + else + return cssMode.indent(state.localState, textAfter); + }, + + electricChars: "/{}:", + + innerMode: function(state) { + var mode = state.token == html ? htmlMode : state.token == javascript ? jsMode : cssMode; + return {state: state.localState || state.htmlState, mode: mode}; + } + }; +}, "xml", "javascript", "css"); + +CodeMirror.defineMIME("text/html", "htmlmixed"); diff --git a/codemirror/mode/htmlmixed/index.html b/codemirror/mode/htmlmixed/index.html new file mode 100644 index 0000000..45a9c03 --- /dev/null +++ b/codemirror/mode/htmlmixed/index.html @@ -0,0 +1,52 @@ + + + + + CodeMirror: HTML mixed mode + + + + + + + + + + +

CodeMirror: HTML mixed mode

+
+ + +

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

+ +

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

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

CodeMirror: HTTP mode

+ +
+ + + +

MIME types defined: message/http.

+ + diff --git a/codemirror/mode/javascript/index.html b/codemirror/mode/javascript/index.html new file mode 100644 index 0000000..d81413c --- /dev/null +++ b/codemirror/mode/javascript/index.html @@ -0,0 +1,88 @@ + + + + + CodeMirror: JavaScript mode + + + + + + + + + +

CodeMirror: JavaScript mode

+ +
+ + + +

+ JavaScript mode supports a two configuration + options: +

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

+ +

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

+ + diff --git a/codemirror/mode/javascript/javascript.js b/codemirror/mode/javascript/javascript.js new file mode 100644 index 0000000..b66d223 --- /dev/null +++ b/codemirror/mode/javascript/javascript.js @@ -0,0 +1,419 @@ +// TODO actually recognize syntax of TypeScript constructs + +CodeMirror.defineMode("javascript", function(config, parserConfig) { + var indentUnit = config.indentUnit; + var jsonMode = parserConfig.json; + var isTS = parserConfig.typescript; + + // Tokenizer + + var keywords = function(){ + function kw(type) {return {type: type, style: "keyword"};} + var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"); + var operator = kw("operator"), atom = {type: "atom", style: "atom"}; + + var jsKeywords = { + "if": A, "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, + "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, + "var": kw("var"), "const": kw("var"), "let": kw("var"), + "function": kw("function"), "catch": kw("catch"), + "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), + "in": operator, "typeof": operator, "instanceof": operator, + "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom + }; + + // Extend the 'normal' keywords with the TypeScript language extensions + if (isTS) { + var type = {type: "variable", style: "variable-3"}; + var tsKeywords = { + // object-like things + "interface": kw("interface"), + "class": kw("class"), + "extends": kw("extends"), + "constructor": kw("constructor"), + + // scope modifiers + "public": kw("public"), + "private": kw("private"), + "protected": kw("protected"), + "static": kw("static"), + + "super": kw("super"), + + // types + "string": type, "number": type, "bool": type, "any": type + }; + + for (var attr in tsKeywords) { + jsKeywords[attr] = tsKeywords[attr]; + } + } + + return jsKeywords; + }(); + + var isOperatorChar = /[+\-*&%=<>!?|]/; + + function chain(stream, state, f) { + state.tokenize = f; + return f(stream, state); + } + + function nextUntilUnescaped(stream, end) { + var escaped = false, next; + while ((next = stream.next()) != null) { + if (next == end && !escaped) + return false; + escaped = !escaped && next == "\\"; + } + return escaped; + } + + // Used as scratch variables to communicate multiple values without + // consing up tons of objects. + var type, content; + function ret(tp, style, cont) { + type = tp; content = cont; + return style; + } + + function jsTokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") + return chain(stream, state, jsTokenString(ch)); + else if (/[\[\]{}\(\),;\:\.]/.test(ch)) + return ret(ch); + else if (ch == "0" && stream.eat(/x/i)) { + stream.eatWhile(/[\da-f]/i); + return ret("number", "number"); + } + else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) { + stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); + return ret("number", "number"); + } + else if (ch == "/") { + if (stream.eat("*")) { + return chain(stream, state, jsTokenComment); + } + else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } + else if (state.lastType == "operator" || state.lastType == "keyword c" || + /^[\[{}\(,;:]$/.test(state.lastType)) { + nextUntilUnescaped(stream, "/"); + stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla + return ret("regexp", "string-2"); + } + else { + stream.eatWhile(isOperatorChar); + return ret("operator", null, stream.current()); + } + } + else if (ch == "#") { + stream.skipToEnd(); + return ret("error", "error"); + } + else if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return ret("operator", null, stream.current()); + } + else { + stream.eatWhile(/[\w\$_]/); + var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; + return (known && state.lastType != ".") ? ret(known.type, known.style, word) : + ret("variable", "variable", word); + } + } + + function jsTokenString(quote) { + return function(stream, state) { + if (!nextUntilUnescaped(stream, quote)) + state.tokenize = jsTokenBase; + return ret("string", "string"); + }; + } + + function jsTokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = jsTokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return ret("comment", "comment"); + } + + // Parser + + var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true}; + + function JSLexical(indented, column, type, align, prev, info) { + this.indented = indented; + this.column = column; + this.type = type; + this.prev = prev; + this.info = info; + if (align != null) this.align = align; + } + + function inScope(state, varname) { + for (var v = state.localVars; v; v = v.next) + if (v.name == varname) return true; + } + + function parseJS(state, style, type, content, stream) { + var cc = state.cc; + // Communicate our context to the combinators. + // (Less wasteful than consing up a hundred closures on every call.) + cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; + + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = true; + + while(true) { + var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; + if (combinator(type, content)) { + while(cc.length && cc[cc.length - 1].lex) + cc.pop()(); + if (cx.marked) return cx.marked; + if (type == "variable" && inScope(state, content)) return "variable-2"; + return style; + } + } + } + + // Combinator utils + + var cx = {state: null, column: null, marked: null, cc: null}; + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); + } + function cont() { + pass.apply(null, arguments); + return true; + } + function register(varname) { + function inList(list) { + for (var v = list; v; v = v.next) + if (v.name == varname) return true; + return false; + } + var state = cx.state; + if (state.context) { + cx.marked = "def"; + if (inList(state.localVars)) return; + state.localVars = {name: varname, next: state.localVars}; + } else { + if (inList(state.globalVars)) return; + state.globalVars = {name: varname, next: state.globalVars}; + } + } + + // Combinators + + var defaultVars = {name: "this", next: {name: "arguments"}}; + function pushcontext() { + cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; + cx.state.localVars = defaultVars; + } + function popcontext() { + cx.state.localVars = cx.state.context.vars; + cx.state.context = cx.state.context.prev; + } + function pushlex(type, info) { + var result = function() { + var state = cx.state; + state.lexical = new JSLexical(state.indented, cx.stream.column(), type, null, state.lexical, info); + }; + result.lex = true; + return result; + } + function poplex() { + var state = cx.state; + if (state.lexical.prev) { + if (state.lexical.type == ")") + state.indented = state.lexical.indented; + state.lexical = state.lexical.prev; + } + } + poplex.lex = true; + + function expect(wanted) { + return function expecting(type) { + if (type == wanted) return cont(); + else if (wanted == ";") return pass(); + else return cont(arguments.callee); + }; + } + + function statement(type) { + if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex); + if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); + if (type == "keyword b") return cont(pushlex("form"), statement, poplex); + if (type == "{") return cont(pushlex("}"), block, poplex); + if (type == ";") return cont(); + if (type == "function") return cont(functiondef); + if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), + poplex, statement, poplex); + if (type == "variable") return cont(pushlex("stat"), maybelabel); + if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), + block, poplex, poplex); + if (type == "case") return cont(expression, expect(":")); + if (type == "default") return cont(expect(":")); + if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), + statement, poplex, popcontext); + return pass(pushlex("stat"), expression, expect(";"), poplex); + } + function expression(type) { + if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator); + if (type == "function") return cont(functiondef); + if (type == "keyword c") return cont(maybeexpression); + if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeoperator); + if (type == "operator") return cont(expression); + if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator); + if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator); + return cont(); + } + function maybeexpression(type) { + if (type.match(/[;\}\)\],]/)) return pass(); + return pass(expression); + } + + function maybeoperator(type, value) { + if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator); + if (type == "operator" && value == "?") return cont(expression, expect(":"), expression); + if (type == ";") return; + if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator); + if (type == ".") return cont(property, maybeoperator); + if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator); + } + function maybelabel(type) { + if (type == ":") return cont(poplex, statement); + return pass(maybeoperator, expect(";"), poplex); + } + function property(type) { + if (type == "variable") {cx.marked = "property"; return cont();} + } + function objprop(type) { + if (type == "variable") cx.marked = "property"; + 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 commaSeparated(type) { + if (type == end) return cont(); + else return pass(what, proceed); + }; + } + function block(type) { + if (type == "}") return cont(); + return pass(statement, block); + } + function maybetype(type) { + if (type == ":") return cont(typedef); + return pass(); + } + function typedef(type) { + if (type == "variable"){cx.marked = "variable-3"; return cont();} + return pass(); + } + function vardef1(type, value) { + if (type == "variable") { + register(value); + return isTS ? cont(maybetype, vardef2) : cont(vardef2); + } + return pass(); + } + function vardef2(type, value) { + if (value == "=") return cont(expression, vardef2); + if (type == ",") return cont(vardef1); + } + function forspec1(type) { + if (type == "var") return cont(vardef1, expect(";"), forspec2); + if (type == ";") return cont(forspec2); + if (type == "variable") return cont(formaybein); + return cont(forspec2); + } + function formaybein(_type, value) { + if (value == "in") return cont(expression); + return cont(maybeoperator, forspec2); + } + function forspec2(type, value) { + if (type == ";") return cont(forspec3); + if (value == "in") return cont(expression); + return cont(expression, expect(";"), forspec3); + } + function forspec3(type) { + if (type != ")") cont(expression); + } + function functiondef(type, value) { + if (type == "variable") {register(value); return cont(functiondef);} + if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext); + } + function funarg(type, value) { + if (type == "variable") {register(value); return isTS ? cont(maybetype) : cont();} + } + + // Interface + + return { + startState: function(basecolumn) { + return { + tokenize: jsTokenBase, + lastType: null, + cc: [], + lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), + localVars: parserConfig.localVars, + globalVars: parserConfig.globalVars, + context: parserConfig.localVars && {vars: parserConfig.localVars}, + indented: 0 + }; + }, + + token: function(stream, state) { + if (stream.sol()) { + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = false; + state.indented = stream.indentation(); + } + if (stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (type == "comment") return style; + state.lastType = type; + return parseJS(state, style, type, content, stream); + }, + + indent: function(state, textAfter) { + if (state.tokenize == jsTokenComment) return CodeMirror.Pass; + if (state.tokenize != jsTokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; + if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; + var type = lexical.type, closing = firstChar == type; + if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? 4 : 0); + else if (type == "form" && firstChar == "{") return lexical.indented; + else if (type == "form") return lexical.indented + indentUnit; + else if (type == "stat") + return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? indentUnit : 0); + else if (lexical.info == "switch" && !closing) + return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); + else if (lexical.align) return lexical.column + (closing ? 0 : 1); + else return lexical.indented + (closing ? 0 : indentUnit); + }, + + electricChars: ":{}", + + jsonMode: jsonMode + }; +}); + +CodeMirror.defineMIME("text/javascript", "javascript"); +CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); +CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); +CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); diff --git a/codemirror/mode/javascript/typescript.html b/codemirror/mode/javascript/typescript.html new file mode 100644 index 0000000..58315e7 --- /dev/null +++ b/codemirror/mode/javascript/typescript.html @@ -0,0 +1,48 @@ + + + + + CodeMirror: TypeScript mode + + + + + + + +

CodeMirror: TypeScript mode

+ +
+ + + +

This is a specialization of the JavaScript mode.

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

CodeMirror: Jinja2 mode

+
+ + + diff --git a/codemirror/mode/jinja2/jinja2.js b/codemirror/mode/jinja2/jinja2.js new file mode 100644 index 0000000..1472d39 --- /dev/null +++ b/codemirror/mode/jinja2/jinja2.js @@ -0,0 +1,42 @@ +CodeMirror.defineMode("jinja2", function() { + var keywords = ["block", "endblock", "for", "endfor", "in", "true", "false", + "loop", "none", "self", "super", "if", "as", "not", "and", + "else", "import", "with", "without", "context"]; + keywords = new RegExp("^((" + keywords.join(")|(") + "))\\b"); + + function tokenBase (stream, state) { + var ch = stream.next(); + if (ch == "{") { + if (ch = stream.eat(/\{|%|#/)) { + stream.eat("-"); + state.tokenize = inTag(ch); + return "tag"; + } + } + } + function inTag (close) { + if (close == "{") { + close = "}"; + } + return function (stream, state) { + var ch = stream.next(); + if ((ch == close || (ch == "-" && stream.eat(close))) + && stream.eat("}")) { + state.tokenize = tokenBase; + return "tag"; + } + if (stream.match(keywords)) { + return "keyword"; + } + return close == "#" ? "comment" : "string"; + }; + } + return { + startState: function () { + return {tokenize: tokenBase}; + }, + token: function (stream, state) { + return state.tokenize(stream, state); + } + }; +}); diff --git a/codemirror/mode/less/index.html b/codemirror/mode/less/index.html new file mode 100644 index 0000000..7f27cf3 --- /dev/null +++ b/codemirror/mode/less/index.html @@ -0,0 +1,741 @@ + + + + + CodeMirror: LESS mode + + + + + + + + + +

CodeMirror: LESS mode

+
+ + +

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

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

CodeMirror: Lua mode

+
+ + +

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

+

MIME types defined: text/x-lua.

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

CodeMirror: Markdown mode

+ + +
+ + + +

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

+ +

MIME types defined: text/x-markdown.

+ +

Parsing/Highlighting Tests: normal, verbose.

+ + + diff --git a/codemirror/mode/markdown/markdown.js b/codemirror/mode/markdown/markdown.js new file mode 100644 index 0000000..531c2b5 --- /dev/null +++ b/codemirror/mode/markdown/markdown.js @@ -0,0 +1,474 @@ +CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) { + + var htmlFound = CodeMirror.mimeModes.hasOwnProperty("text/html"); + var htmlMode = CodeMirror.getMode(cmCfg, htmlFound ? "text/html" : "text/plain"); + var aliases = { + html: "htmlmixed", + js: "javascript", + json: "application/json", + c: "text/x-csrc", + "c++": "text/x-c++src", + java: "text/x-java", + csharp: "text/x-csharp", + "c#": "text/x-csharp" + }; + + var getMode = (function () { + var i, modes = {}, mimes = {}, mime; + + var list = []; + for (var m in CodeMirror.modes) + if (CodeMirror.modes.propertyIsEnumerable(m)) list.push(m); + for (i = 0; i < list.length; i++) { + modes[list[i]] = list[i]; + } + var mimesList = []; + for (var m in CodeMirror.mimeModes) + if (CodeMirror.mimeModes.propertyIsEnumerable(m)) + mimesList.push({mime: m, mode: CodeMirror.mimeModes[m]}); + for (i = 0; i < mimesList.length; i++) { + mime = mimesList[i].mime; + mimes[mime] = mimesList[i].mime; + } + + for (var a in aliases) { + if (aliases[a] in modes || aliases[a] in mimes) + modes[a] = aliases[a]; + } + + return function (lang) { + return modes[lang] ? CodeMirror.getMode(cmCfg, modes[lang]) : null; + }; + }()); + + // Should underscores in words open/close em/strong? + if (modeCfg.underscoresBreakWords === undefined) + modeCfg.underscoresBreakWords = true; + + // Turn on fenced code blocks? ("```" to start/end) + if (modeCfg.fencedCodeBlocks === undefined) modeCfg.fencedCodeBlocks = false; + + var codeDepth = 0; + var prevLineHasContent = false + , thisLineHasContent = false; + + var header = 'header' + , code = 'comment' + , quote = 'quote' + , list = 'string' + , hr = 'hr' + , image = 'tag' + , linkinline = 'link' + , linkemail = 'link' + , linktext = 'link' + , linkhref = 'string' + , em = 'em' + , strong = 'strong' + , emstrong = 'emstrong'; + + var hrRE = /^([*\-=_])(?:\s*\1){2,}\s*$/ + , ulRE = /^[*\-+]\s+/ + , olRE = /^[0-9]+\.\s+/ + , headerRE = /^(?:\={1,}|-{1,})$/ + , textRE = /^[^!\[\]*_\\<>` "'(]+/; + + function switchInline(stream, state, f) { + state.f = state.inline = f; + return f(stream, state); + } + + function switchBlock(stream, state, f) { + state.f = state.block = f; + return f(stream, state); + } + + + // Blocks + + function blankLine(state) { + // Reset linkTitle state + state.linkTitle = false; + // Reset EM state + state.em = false; + // Reset STRONG state + state.strong = false; + // Reset state.quote + state.quote = false; + if (!htmlFound && state.f == htmlBlock) { + state.f = inlineNormal; + state.block = blockNormal; + } + return null; + } + + function blockNormal(stream, state) { + + if (state.list !== false && state.indentationDiff >= 0) { // Continued list + if (state.indentationDiff < 4) { // Only adjust indentation if *not* a code block + state.indentation -= state.indentationDiff; + } + state.list = null; + } else { // No longer a list + state.list = false; + } + + if (state.indentationDiff >= 4) { + state.indentation -= 4; + stream.skipToEnd(); + return code; + } else if (stream.eatSpace()) { + return null; + } else if (stream.peek() === '#' || (prevLineHasContent && stream.match(headerRE)) ) { + state.header = true; + } else if (stream.eat('>')) { + state.indentation++; + state.quote = true; + } else if (stream.peek() === '[') { + return switchInline(stream, state, footnoteLink); + } else if (stream.match(hrRE, true)) { + return hr; + } else if (stream.match(ulRE, true) || stream.match(olRE, true)) { + state.indentation += 4; + state.list = true; + } else if (modeCfg.fencedCodeBlocks && stream.match(/^```([\w+#]*)/, true)) { + // try switching mode + state.localMode = getMode(RegExp.$1); + if (state.localMode) state.localState = state.localMode.startState(); + switchBlock(stream, state, local); + return code; + } + + return switchInline(stream, state, state.inline); + } + + function htmlBlock(stream, state) { + var style = htmlMode.token(stream, state.htmlState); + if (htmlFound && style === 'tag' && state.htmlState.type !== 'openTag' && !state.htmlState.context) { + state.f = inlineNormal; + state.block = blockNormal; + } + if (state.md_inside && stream.current().indexOf(">")!=-1) { + state.f = inlineNormal; + state.block = blockNormal; + state.htmlState.context = undefined; + } + return style; + } + + function local(stream, state) { + if (stream.sol() && stream.match(/^```/, true)) { + state.localMode = state.localState = null; + state.f = inlineNormal; + state.block = blockNormal; + return code; + } else if (state.localMode) { + return state.localMode.token(stream, state.localState); + } else { + stream.skipToEnd(); + return code; + } + } + + // Inline + function getType(state) { + var styles = []; + + if (state.strong) { styles.push(state.em ? emstrong : strong); } + else if (state.em) { styles.push(em); } + + if (state.linkText) { styles.push(linktext); } + + if (state.code) { styles.push(code); } + + if (state.header) { styles.push(header); } + if (state.quote) { styles.push(quote); } + if (state.list !== false) { styles.push(list); } + + return styles.length ? styles.join(' ') : null; + } + + function handleText(stream, state) { + if (stream.match(textRE, true)) { + return getType(state); + } + return undefined; + } + + function inlineNormal(stream, state) { + var style = state.text(stream, state); + if (typeof style !== 'undefined') + return style; + + if (state.list) { // List marker (*, +, -, 1., etc) + state.list = null; + return list; + } + + var ch = stream.next(); + + if (ch === '\\') { + stream.next(); + return getType(state); + } + + // Matches link titles present on next line + if (state.linkTitle) { + state.linkTitle = false; + var matchCh = ch; + if (ch === '(') { + matchCh = ')'; + } + matchCh = (matchCh+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); + var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh; + if (stream.match(new RegExp(regex), true)) { + return linkhref; + } + } + + // If this block is changed, it may need to be updated in GFM mode + if (ch === '`') { + var t = getType(state); + var before = stream.pos; + stream.eatWhile('`'); + var difference = 1 + stream.pos - before; + if (!state.code) { + codeDepth = difference; + state.code = true; + return getType(state); + } else { + if (difference === codeDepth) { // Must be exact + state.code = false; + return t; + } + return getType(state); + } + } else if (state.code) { + return getType(state); + } + + if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) { + stream.match(/\[[^\]]*\]/); + state.inline = state.f = linkHref; + return image; + } + + if (ch === '[' && stream.match(/.*\](\(| ?\[)/, false)) { + state.linkText = true; + return getType(state); + } + + if (ch === ']' && state.linkText) { + var type = getType(state); + state.linkText = false; + state.inline = state.f = linkHref; + return type; + } + + if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, true)) { + return switchInline(stream, state, inlineElement(linkinline, '>')); + } + + if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, true)) { + return switchInline(stream, state, inlineElement(linkemail, '>')); + } + + if (ch === '<' && stream.match(/^\w/, false)) { + if (stream.string.indexOf(">")!=-1) { + var atts = stream.string.substring(1,stream.string.indexOf(">")); + if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) { + state.md_inside = true; + } + } + stream.backUp(1); + return switchBlock(stream, state, htmlBlock); + } + + if (ch === '<' && stream.match(/^\/\w*?>/)) { + state.md_inside = false; + return "tag"; + } + + var ignoreUnderscore = false; + if (!modeCfg.underscoresBreakWords) { + if (ch === '_' && stream.peek() !== '_' && stream.match(/(\w)/, false)) { + var prevPos = stream.pos - 2; + if (prevPos >= 0) { + var prevCh = stream.string.charAt(prevPos); + if (prevCh !== '_' && prevCh.match(/(\w)/, false)) { + ignoreUnderscore = true; + } + } + } + } + var t = getType(state); + if (ch === '*' || (ch === '_' && !ignoreUnderscore)) { + if (state.strong === ch && stream.eat(ch)) { // Remove STRONG + state.strong = false; + return t; + } else if (!state.strong && stream.eat(ch)) { // Add STRONG + state.strong = ch; + return getType(state); + } else if (state.em === ch) { // Remove EM + state.em = false; + return t; + } else if (!state.em) { // Add EM + state.em = ch; + return getType(state); + } + } else if (ch === ' ') { + if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces + if (stream.peek() === ' ') { // Surrounded by spaces, ignore + return getType(state); + } else { // Not surrounded by spaces, back up pointer + stream.backUp(1); + } + } + } + + return getType(state); + } + + function linkHref(stream, state) { + // Check if space, and return NULL if so (to avoid marking the space) + if(stream.eatSpace()){ + return null; + } + var ch = stream.next(); + if (ch === '(' || ch === '[') { + return switchInline(stream, state, inlineElement(linkhref, ch === '(' ? ')' : ']')); + } + return 'error'; + } + + function footnoteLink(stream, state) { + if (stream.match(/^[^\]]*\]:/, true)) { + state.f = footnoteUrl; + return linktext; + } + return switchInline(stream, state, inlineNormal); + } + + function footnoteUrl(stream, state) { + // Check if space, and return NULL if so (to avoid marking the space) + if(stream.eatSpace()){ + return null; + } + // Match URL + stream.match(/^[^\s]+/, true); + // Check for link title + if (stream.peek() === undefined) { // End of line, set flag to check next line + state.linkTitle = true; + } else { // More content on line, check if link title + stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true); + } + state.f = state.inline = inlineNormal; + return linkhref; + } + + var savedInlineRE = []; + function inlineRE(endChar) { + if (!savedInlineRE[endChar]) { + // Escape endChar for RegExp (taken from http://stackoverflow.com/a/494122/526741) + endChar = (endChar+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); + // Match any non-endChar, escaped character, as well as the closing + // endChar. + savedInlineRE[endChar] = new RegExp('^(?:[^\\\\]|\\\\.)*?(' + endChar + ')'); + } + return savedInlineRE[endChar]; + } + + function inlineElement(type, endChar, next) { + next = next || inlineNormal; + return function(stream, state) { + stream.match(inlineRE(endChar)); + state.inline = state.f = next; + return type; + }; + } + + return { + startState: function() { + prevLineHasContent = false; + thisLineHasContent = false; + return { + f: blockNormal, + + block: blockNormal, + htmlState: CodeMirror.startState(htmlMode), + indentation: 0, + + inline: inlineNormal, + text: handleText, + + linkText: false, + linkTitle: false, + em: false, + strong: false, + header: false, + list: false, + quote: false + }; + }, + + copyState: function(s) { + return { + f: s.f, + + block: s.block, + htmlState: CodeMirror.copyState(htmlMode, s.htmlState), + indentation: s.indentation, + + localMode: s.localMode, + localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null, + + inline: s.inline, + text: s.text, + linkTitle: s.linkTitle, + em: s.em, + strong: s.strong, + header: s.header, + list: s.list, + quote: s.quote, + md_inside: s.md_inside + }; + }, + + token: function(stream, state) { + if (stream.sol()) { + if (stream.match(/^\s*$/, true)) { + prevLineHasContent = false; + return blankLine(state); + } else { + if(thisLineHasContent){ + prevLineHasContent = true; + thisLineHasContent = false; + } + thisLineHasContent = true; + } + + // Reset state.header + state.header = false; + + // Reset state.code + state.code = false; + + state.f = state.block; + var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, ' ').length; + var difference = Math.floor((indentation - state.indentation) / 4) * 4; + if (difference > 4) difference = 4; + var adjustedIndentation = state.indentation + difference; + state.indentationDiff = adjustedIndentation - state.indentation; + state.indentation = adjustedIndentation; + if (indentation > 0) return null; + } + return state.f(stream, state); + }, + + blankLine: blankLine, + + getType: getType + }; + +}, "xml"); + +CodeMirror.defineMIME("text/x-markdown", "markdown"); diff --git a/codemirror/mode/markdown/test.js b/codemirror/mode/markdown/test.js new file mode 100644 index 0000000..2e06707 --- /dev/null +++ b/codemirror/mode/markdown/test.js @@ -0,0 +1,1291 @@ +// Initiate ModeTest and set defaults +var MT = ModeTest; +MT.modeName = 'markdown'; +MT.modeOptions = {}; + +MT.testMode( + 'plainText', + 'foo', + [ + null, 'foo' + ] +); + +// Code blocks using 4 spaces (regardless of CodeMirror.tabSize value) +MT.testMode( + 'codeBlocksUsing4Spaces', + ' foo', + [ + null, ' ', + 'comment', 'foo' + ] +); +// Code blocks using 4 spaces with internal indentation +MT.testMode( + 'codeBlocksUsing4SpacesIndentation', + ' bar\n hello\n world\n foo\nbar', + [ + null, ' ', + 'comment', 'bar', + null, ' ', + 'comment', 'hello', + null, ' ', + 'comment', 'world', + null, ' ', + 'comment', 'foo', + null, 'bar' + ] +); +// Code blocks using 4 spaces with internal indentation +MT.testMode( + 'codeBlocksUsing4SpacesIndentation', + ' foo\n bar\n hello\n world', + [ + null, ' foo', + null, ' ', + 'comment', 'bar', + null, ' ', + 'comment', 'hello', + null, ' ', + 'comment', 'world' + ] +); + +// Code blocks using 1 tab (regardless of CodeMirror.indentWithTabs value) +MT.testMode( + 'codeBlocksUsing1Tab', + '\tfoo', + [ + null, '\t', + 'comment', 'foo' + ] +); + +// Inline code using backticks +MT.testMode( + 'inlineCodeUsingBackticks', + 'foo `bar`', + [ + null, 'foo ', + 'comment', '`bar`' + ] +); + +// Block code using single backtick (shouldn't work) +MT.testMode( + 'blockCodeSingleBacktick', + '`\nfoo\n`', + [ + 'comment', '`', + null, '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.testMode( + 'unclosedBackticks', + 'foo `bar', + [ + null, '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.testMode( + 'doubleBackticks', + '``foo ` bar``', + [ + 'comment', '``foo ` bar``' + ] +); + +// Tests based on Dingus +// http://daringfireball.net/projects/markdown/dingus +// +// Multiple backticks within an inline code block +MT.testMode( + 'consecutiveBackticks', + '`foo```bar`', + [ + 'comment', '`foo```bar`' + ] +); +// Multiple backticks within an inline code block with a second code block +MT.testMode( + 'consecutiveBackticks', + '`foo```bar` hello `world`', + [ + 'comment', '`foo```bar`', + null, ' hello ', + 'comment', '`world`' + ] +); +// Unclosed with several different groups of backticks +MT.testMode( + 'unclosedBackticks', + '``foo ``` bar` hello', + [ + 'comment', '``foo ``` bar` hello' + ] +); +// Closed with several different groups of backticks +MT.testMode( + 'closedBackticks', + '``foo ``` bar` hello`` world', + [ + 'comment', '``foo ``` bar` hello``', + null, ' world' + ] +); + +// atx headers +// http://daringfireball.net/projects/markdown/syntax#header +// +// H1 +MT.testMode( + 'atxH1', + '# foo', + [ + 'header', '# foo' + ] +); +// H2 +MT.testMode( + 'atxH2', + '## foo', + [ + 'header', '## foo' + ] +); +// H3 +MT.testMode( + 'atxH3', + '### foo', + [ + 'header', '### foo' + ] +); +// H4 +MT.testMode( + 'atxH4', + '#### foo', + [ + 'header', '#### foo' + ] +); +// H5 +MT.testMode( + 'atxH5', + '##### foo', + [ + 'header', '##### foo' + ] +); +// H6 +MT.testMode( + 'atxH6', + '###### foo', + [ + 'header', '###### foo' + ] +); +// H6 - 7x '#' should still be H6, per Dingus +// http://daringfireball.net/projects/markdown/dingus +MT.testMode( + 'atxH6NotH7', + '####### foo', + [ + '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.testMode( + 'setextH1', + 'foo\n=', + [ + null, 'foo', + 'header', '=' + ] +); +// Check if 3+ ='s work +MT.testMode( + 'setextH1', + 'foo\n===', + [ + null, 'foo', + 'header', '===' + ] +); +// Check if single underlining - works +MT.testMode( + 'setextH2', + 'foo\n-', + [ + null, 'foo', + 'header', '-' + ] +); +// Check if 3+ -'s work +MT.testMode( + 'setextH2', + 'foo\n---', + [ + null, 'foo', + 'header', '---' + ] +); + +// Single-line blockquote with trailing space +MT.testMode( + 'blockquoteSpace', + '> foo', + [ + 'quote', '> foo' + ] +); + +// Single-line blockquote +MT.testMode( + 'blockquoteNoSpace', + '>foo', + [ + 'quote', '>foo' + ] +); + +// Single-line blockquote followed by normal paragraph +MT.testMode( + 'blockquoteThenParagraph', + '>foo\n\nbar', + [ + 'quote', '>foo', + null, 'bar' + ] +); + +// Multi-line blockquote (lazy mode) +MT.testMode( + 'multiBlockquoteLazy', + '>foo\nbar', + [ + 'quote', '>foo', + 'quote', 'bar' + ] +); + +// Multi-line blockquote followed by normal paragraph (lazy mode) +MT.testMode( + 'multiBlockquoteLazyThenParagraph', + '>foo\nbar\n\nhello', + [ + 'quote', '>foo', + 'quote', 'bar', + null, 'hello' + ] +); + +// Multi-line blockquote (non-lazy mode) +MT.testMode( + 'multiBlockquote', + '>foo\n>bar', + [ + 'quote', '>foo', + 'quote', '>bar' + ] +); + +// Multi-line blockquote followed by normal paragraph (non-lazy mode) +MT.testMode( + 'multiBlockquoteThenParagraph', + '>foo\n>bar\n\nhello', + [ + 'quote', '>foo', + 'quote', '>bar', + null, 'hello' + ] +); + +// Check list types +MT.testMode( + 'listAsterisk', + '* foo\n* bar', + [ + 'string', '* foo', + 'string', '* bar' + ] +); +MT.testMode( + 'listPlus', + '+ foo\n+ bar', + [ + 'string', '+ foo', + 'string', '+ bar' + ] +); +MT.testMode( + 'listDash', + '- foo\n- bar', + [ + 'string', '- foo', + 'string', '- bar' + ] +); +MT.testMode( + 'listNumber', + '1. foo\n2. bar', + [ + 'string', '1. foo', + 'string', '2. bar' + ] +); + +// Formatting in lists (*) +MT.testMode( + 'listAsteriskFormatting', + '* *foo* bar\n\n* **foo** bar\n\n* ***foo*** bar\n\n* `foo` bar', + [ + 'string', '* ', + 'string em', '*foo*', + 'string', ' bar', + 'string', '* ', + 'string strong', '**foo**', + 'string', ' bar', + 'string', '* ', + 'string strong', '**', + 'string emstrong', '*foo**', + 'string em', '*', + 'string', ' bar', + 'string', '* ', + 'string comment', '`foo`', + 'string', ' bar' + ] +); +// Formatting in lists (+) +MT.testMode( + 'listPlusFormatting', + '+ *foo* bar\n\n+ **foo** bar\n\n+ ***foo*** bar\n\n+ `foo` bar', + [ + 'string', '+ ', + 'string em', '*foo*', + 'string', ' bar', + 'string', '+ ', + 'string strong', '**foo**', + 'string', ' bar', + 'string', '+ ', + 'string strong', '**', + 'string emstrong', '*foo**', + 'string em', '*', + 'string', ' bar', + 'string', '+ ', + 'string comment', '`foo`', + 'string', ' bar' + ] +); +// Formatting in lists (-) +MT.testMode( + 'listDashFormatting', + '- *foo* bar\n\n- **foo** bar\n\n- ***foo*** bar\n\n- `foo` bar', + [ + 'string', '- ', + 'string em', '*foo*', + 'string', ' bar', + 'string', '- ', + 'string strong', '**foo**', + 'string', ' bar', + 'string', '- ', + 'string strong', '**', + 'string emstrong', '*foo**', + 'string em', '*', + 'string', ' bar', + 'string', '- ', + 'string comment', '`foo`', + 'string', ' bar' + ] +); +// Formatting in lists (1.) +MT.testMode( + 'listNumberFormatting', + '1. *foo* bar\n\n2. **foo** bar\n\n3. ***foo*** bar\n\n4. `foo` bar', + [ + 'string', '1. ', + 'string em', '*foo*', + 'string', ' bar', + 'string', '2. ', + 'string strong', '**foo**', + 'string', ' bar', + 'string', '3. ', + 'string strong', '**', + 'string emstrong', '*foo**', + 'string em', '*', + 'string', ' bar', + 'string', '4. ', + 'string comment', '`foo`', + 'string', ' bar' + ] +); + +// Paragraph lists +MT.testMode( + 'listParagraph', + '* foo\n\n* bar', + [ + 'string', '* foo', + 'string', '* bar' + ] +); + +// Multi-paragraph lists +// +// 4 spaces +MT.testMode( + 'listMultiParagraph', + '* foo\n\n* bar\n\n hello', + [ + 'string', '* foo', + 'string', '* bar', + null, ' ', + 'string', 'hello' + ] +); +// 4 spaces, extra blank lines (should still be list, per Dingus) +MT.testMode( + 'listMultiParagraphExtra', + '* foo\n\n* bar\n\n\n hello', + [ + 'string', '* foo', + 'string', '* bar', + null, ' ', + 'string', 'hello' + ] +); +// 4 spaces, plus 1 space (should still be list, per Dingus) +MT.testMode( + 'listMultiParagraphExtraSpace', + '* foo\n\n* bar\n\n hello\n\n world', + [ + 'string', '* foo', + 'string', '* bar', + null, ' ', + 'string', 'hello', + null, ' ', + 'string', 'world' + ] +); +// 1 tab +MT.testMode( + 'listTab', + '* foo\n\n* bar\n\n\thello', + [ + 'string', '* foo', + 'string', '* bar', + null, '\t', + 'string', 'hello' + ] +); +// No indent +MT.testMode( + 'listNoIndent', + '* foo\n\n* bar\n\nhello', + [ + 'string', '* foo', + 'string', '* bar', + null, 'hello' + ] +); +// Blockquote +MT.testMode( + 'blockquote', + '* foo\n\n* bar\n\n > hello', + [ + 'string', '* foo', + 'string', '* bar', + null, ' ', + 'string quote', '> hello' + ] +); +// Code block +MT.testMode( + 'blockquoteCode', + '* foo\n\n* bar\n\n > hello\n\n world', + [ + 'string', '* foo', + 'string', '* bar', + null, ' ', + 'comment', '> hello', + null, ' ', + 'string', 'world' + ] +); +// Code block followed by text +MT.testMode( + 'blockquoteCodeText', + '* foo\n\n bar\n\n hello\n\n world', + [ + 'string', '* foo', + null, ' ', + 'string', 'bar', + null, ' ', + 'comment', 'hello', + null, ' ', + 'string', 'world' + ] +); + +// Nested list +// +// * +MT.testMode( + 'listAsteriskNested', + '* foo\n\n * bar', + [ + 'string', '* foo', + null, ' ', + 'string', '* bar' + ] +); +// + +MT.testMode( + 'listPlusNested', + '+ foo\n\n + bar', + [ + 'string', '+ foo', + null, ' ', + 'string', '+ bar' + ] +); +// - +MT.testMode( + 'listDashNested', + '- foo\n\n - bar', + [ + 'string', '- foo', + null, ' ', + 'string', '- bar' + ] +); +// 1. +MT.testMode( + 'listNumberNested', + '1. foo\n\n 2. bar', + [ + 'string', '1. foo', + null, ' ', + 'string', '2. bar' + ] +); +// Mixed +MT.testMode( + 'listMixed', + '* foo\n\n + bar\n\n - hello\n\n 1. world', + [ + 'string', '* foo', + null, ' ', + 'string', '+ bar', + null, ' ', + 'string', '- hello', + null, ' ', + 'string', '1. world' + ] +); +// Blockquote +MT.testMode( + 'listBlockquote', + '* foo\n\n + bar\n\n > hello', + [ + 'string', '* foo', + null, ' ', + 'string', '+ bar', + null, ' ', + 'quote string', '> hello' + ] +); +// Code +MT.testMode( + 'listCode', + '* foo\n\n + bar\n\n hello', + [ + 'string', '* foo', + null, ' ', + 'string', '+ bar', + null, ' ', + 'comment', 'hello' + ] +); +// Code with internal indentation +MT.testMode( + 'listCodeIndentation', + '* foo\n\n bar\n hello\n world\n foo\n bar', + [ + 'string', '* foo', + null, ' ', + 'comment', 'bar', + null, ' ', + 'comment', 'hello', + null, ' ', + 'comment', 'world', + null, ' ', + 'comment', 'foo', + null, ' ', + 'string', 'bar' + ] +); +// Code followed by text +MT.testMode( + 'listCodeText', + '* foo\n\n bar\n\nhello', + [ + 'string', '* foo', + null, ' ', + 'comment', 'bar', + null, 'hello' + ] +); + +// Following tests directly from official Markdown documentation +// http://daringfireball.net/projects/markdown/syntax#hr +MT.testMode( + 'hrSpace', + '* * *', + [ + 'hr', '* * *' + ] +); + +MT.testMode( + 'hr', + '***', + [ + 'hr', '***' + ] +); + +MT.testMode( + 'hrLong', + '*****', + [ + 'hr', '*****' + ] +); + +MT.testMode( + 'hrSpaceDash', + '- - -', + [ + 'hr', '- - -' + ] +); + +MT.testMode( + 'hrDashLong', + '---------------------------------------', + [ + 'hr', '---------------------------------------' + ] +); + +// Inline link with title +MT.testMode( + 'linkTitle', + '[foo](http://example.com/ "bar") hello', + [ + 'link', '[foo]', + 'string', '(http://example.com/ "bar")', + null, ' hello' + ] +); + +// Inline link without title +MT.testMode( + 'linkNoTitle', + '[foo](http://example.com/) bar', + [ + 'link', '[foo]', + 'string', '(http://example.com/)', + null, ' bar' + ] +); + +// Inline link with image +MT.testMode( + 'linkImage', + '[![foo](http://example.com/)](http://example.com/) bar', + [ + 'link', '[', + 'tag', '![foo]', + 'string', '(http://example.com/)', + 'link', ']', + 'string', '(http://example.com/)', + null, ' bar' + ] +); + +// Inline link with Em +MT.testMode( + 'linkEm', + '[*foo*](http://example.com/) bar', + [ + 'link', '[', + 'link em', '*foo*', + 'link', ']', + 'string', '(http://example.com/)', + null, ' bar' + ] +); + +// Inline link with Strong +MT.testMode( + 'linkStrong', + '[**foo**](http://example.com/) bar', + [ + 'link', '[', + 'link strong', '**foo**', + 'link', ']', + 'string', '(http://example.com/)', + null, ' bar' + ] +); + +// Inline link with EmStrong +MT.testMode( + 'linkEmStrong', + '[***foo***](http://example.com/) bar', + [ + 'link', '[', + 'link strong', '**', + 'link emstrong', '*foo**', + 'link em', '*', + 'link', ']', + 'string', '(http://example.com/)', + null, ' bar' + ] +); + +// Image with title +MT.testMode( + 'imageTitle', + '![foo](http://example.com/ "bar") hello', + [ + 'tag', '![foo]', + 'string', '(http://example.com/ "bar")', + null, ' hello' + ] +); + +// Image without title +MT.testMode( + 'imageNoTitle', + '![foo](http://example.com/) bar', + [ + 'tag', '![foo]', + 'string', '(http://example.com/)', + null, ' bar' + ] +); + +// Image with asterisks +MT.testMode( + 'imageAsterisks', + '![*foo*](http://example.com/) bar', + [ + 'tag', '![*foo*]', + 'string', '(http://example.com/)', + null, ' 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.testMode( + 'notALink', + '[foo] (bar)', + [ + null, '[foo] (bar)' + ] +); + +// Reference-style links +MT.testMode( + 'linkReference', + '[foo][bar] hello', + [ + 'link', '[foo]', + 'string', '[bar]', + null, ' hello' + ] +); +// Reference-style links with Em +MT.testMode( + 'linkReferenceEm', + '[*foo*][bar] hello', + [ + 'link', '[', + 'link em', '*foo*', + 'link', ']', + 'string', '[bar]', + null, ' hello' + ] +); +// Reference-style links with Strong +MT.testMode( + 'linkReferenceStrong', + '[**foo**][bar] hello', + [ + 'link', '[', + 'link strong', '**foo**', + 'link', ']', + 'string', '[bar]', + null, ' hello' + ] +); +// Reference-style links with EmStrong +MT.testMode( + 'linkReferenceEmStrong', + '[***foo***][bar] hello', + [ + 'link', '[', + 'link strong', '**', + 'link emstrong', '*foo**', + 'link em', '*', + 'link', ']', + 'string', '[bar]', + null, ' hello' + ] +); + +// Reference-style links with optional space separator (per docuentation) +// "You can optionally use a space to separate the sets of brackets" +MT.testMode( + 'linkReferenceSpace', + '[foo] [bar] hello', + [ + 'link', '[foo]', + null, ' ', + 'string', '[bar]', + null, ' hello' + ] +); +// Should only allow a single space ("...use *a* space...") +MT.testMode( + 'linkReferenceDoubleSpace', + '[foo] [bar] hello', + [ + null, '[foo] [bar] hello' + ] +); + +// Reference-style links with implicit link name +MT.testMode( + 'linkImplicit', + '[foo][] hello', + [ + 'link', '[foo]', + 'string', '[]', + null, ' 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) +// +// No title +MT.testMode( + 'labelNoTitle', + '[foo]: http://example.com/', + [ + 'link', '[foo]:', + null, ' ', + 'string', 'http://example.com/' + ] +); +// Indented +MT.testMode( + 'labelIndented', + ' [foo]: http://example.com/', + [ + null, ' ', + 'link', '[foo]:', + null, ' ', + 'string', 'http://example.com/' + ] +); +// Space in ID and title +MT.testMode( + 'labelSpaceTitle', + '[foo bar]: http://example.com/ "hello"', + [ + 'link', '[foo bar]:', + null, ' ', + 'string', 'http://example.com/ "hello"' + ] +); +// Double title +MT.testMode( + 'labelDoubleTitle', + '[foo bar]: http://example.com/ "hello" "world"', + [ + 'link', '[foo bar]:', + null, ' ', + 'string', 'http://example.com/ "hello"', + null, ' "world"' + ] +); +// Double quotes around title +MT.testMode( + 'labelTitleDoubleQuotes', + '[foo]: http://example.com/ "bar"', + [ + 'link', '[foo]:', + null, ' ', + 'string', 'http://example.com/ "bar"' + ] +); +// Single quotes around title +MT.testMode( + 'labelTitleSingleQuotes', + '[foo]: http://example.com/ \'bar\'', + [ + 'link', '[foo]:', + null, ' ', + 'string', 'http://example.com/ \'bar\'' + ] +); +// Parentheses around title +MT.testMode( + 'labelTitleParenthese', + '[foo]: http://example.com/ (bar)', + [ + 'link', '[foo]:', + null, ' ', + 'string', 'http://example.com/ (bar)' + ] +); +// Invalid title +MT.testMode( + 'labelTitleInvalid', + '[foo]: http://example.com/ bar', + [ + 'link', '[foo]:', + null, ' ', + 'string', 'http://example.com/', + null, ' bar' + ] +); +// Angle brackets around URL +MT.testMode( + 'labelLinkAngleBrackets', + '[foo]: "bar"', + [ + 'link', '[foo]:', + null, ' ', + 'string', ' "bar"' + ] +); +// Title on next line per documentation (double quotes) +MT.testMode( + 'labelTitleNextDoubleQuotes', + '[foo]: http://example.com/\n"bar" hello', + [ + 'link', '[foo]:', + null, ' ', + 'string', 'http://example.com/', + 'string', '"bar"', + null, ' hello' + ] +); +// Title on next line per documentation (single quotes) +MT.testMode( + 'labelTitleNextSingleQuotes', + '[foo]: http://example.com/\n\'bar\' hello', + [ + 'link', '[foo]:', + null, ' ', + 'string', 'http://example.com/', + 'string', '\'bar\'', + null, ' hello' + ] +); +// Title on next line per documentation (parentheses) +MT.testMode( + 'labelTitleNextParenthese', + '[foo]: http://example.com/\n(bar) hello', + [ + 'link', '[foo]:', + null, ' ', + 'string', 'http://example.com/', + 'string', '(bar)', + null, ' hello' + ] +); +// Title on next line per documentation (mixed) +MT.testMode( + 'labelTitleNextMixed', + '[foo]: http://example.com/\n(bar" hello', + [ + 'link', '[foo]:', + null, ' ', + 'string', 'http://example.com/', + null, '(bar" hello' + ] +); + +// Automatic links +MT.testMode( + 'linkWeb', + ' foo', + [ + 'link', '', + null, ' foo' + ] +); + +// Automatic email links +MT.testMode( + 'linkEmail', + ' foo', + [ + 'link', '', + null, ' foo' + ] +); + +// Single asterisk +MT.testMode( + 'emAsterisk', + '*foo* bar', + [ + 'em', '*foo*', + null, ' bar' + ] +); + +// Single underscore +MT.testMode( + 'emUnderscore', + '_foo_ bar', + [ + 'em', '_foo_', + null, ' bar' + ] +); + +// Emphasis characters within a word +MT.testMode( + 'emInWordAsterisk', + 'foo*bar*hello', + [ + null, 'foo', + 'em', '*bar*', + null, 'hello' + ] +); +MT.testMode( + 'emInWordUnderscore', + 'foo_bar_hello', + [ + null, 'foo', + 'em', '_bar_', + null, 'hello' + ] +); +// Per documentation: "...surround an * or _ with spaces, it’ll be +// treated as a literal asterisk or underscore." +// +// Inside EM +MT.testMode( + 'emEscapedBySpaceIn', + 'foo _bar _ hello_ world', + [ + null, 'foo ', + 'em', '_bar _ hello_', + null, ' world' + ] +); +// Outside EM +MT.testMode( + 'emEscapedBySpaceOut', + 'foo _ bar_hello_world', + [ + null, 'foo _ bar', + 'em', '_hello_', + null, '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.testMode( + 'emIncompleteAsterisk', + 'foo *bar', + [ + null, 'foo ', + 'em', '*bar' + ] +); +MT.testMode( + 'emIncompleteUnderscore', + 'foo _bar', + [ + null, 'foo ', + 'em', '_bar' + ] +); + +// Double asterisk +MT.testMode( + 'strongAsterisk', + '**foo** bar', + [ + 'strong', '**foo**', + null, ' bar' + ] +); + +// Double underscore +MT.testMode( + 'strongUnderscore', + '__foo__ bar', + [ + 'strong', '__foo__', + null, ' bar' + ] +); + +// Triple asterisk +MT.testMode( + 'emStrongAsterisk', + '*foo**bar*hello** world', + [ + 'em', '*foo', + 'emstrong', '**bar*', + 'strong', 'hello**', + null, ' world' + ] +); + +// Triple underscore +MT.testMode( + 'emStrongUnderscore', + '_foo__bar_hello__ world', + [ + 'em', '_foo', + 'emstrong', '__bar_', + 'strong', 'hello__', + null, ' world' + ] +); + +// Triple mixed +// "...same character must be used to open and close an emphasis span."" +MT.testMode( + 'emStrongMixed', + '_foo**bar*hello__ world', + [ + 'em', '_foo', + 'emstrong', '**bar*hello__ world' + ] +); + +MT.testMode( + 'emStrongMixed', + '*foo__bar_hello** world', + [ + 'em', '*foo', + 'emstrong', '__bar_hello** world' + ] +); + +// These characters should be escaped: +// \ backslash +// ` backtick +// * asterisk +// _ underscore +// {} curly braces +// [] square brackets +// () parentheses +// # hash mark +// + plus sign +// - minus sign (hyphen) +// . dot +// ! exclamation mark +// +// Backtick (code) +MT.testMode( + 'escapeBacktick', + 'foo \\`bar\\`', + [ + null, 'foo \\`bar\\`' + ] +); +MT.testMode( + 'doubleEscapeBacktick', + 'foo \\\\`bar\\\\`', + [ + null, 'foo \\\\', + 'comment', '`bar\\\\`' + ] +); +// Asterisk (em) +MT.testMode( + 'escapeAsterisk', + 'foo \\*bar\\*', + [ + null, 'foo \\*bar\\*' + ] +); +MT.testMode( + 'doubleEscapeAsterisk', + 'foo \\\\*bar\\\\*', + [ + null, 'foo \\\\', + 'em', '*bar\\\\*' + ] +); +// Underscore (em) +MT.testMode( + 'escapeUnderscore', + 'foo \\_bar\\_', + [ + null, 'foo \\_bar\\_' + ] +); +MT.testMode( + 'doubleEscapeUnderscore', + 'foo \\\\_bar\\\\_', + [ + null, 'foo \\\\', + 'em', '_bar\\\\_' + ] +); +// Hash mark (headers) +MT.testMode( + 'escapeHash', + '\\# foo', + [ + null, '\\# foo' + ] +); +MT.testMode( + 'doubleEscapeHash', + '\\\\# foo', + [ + null, '\\\\# foo' + ] +); diff --git a/codemirror/mode/mysql/index.html b/codemirror/mode/mysql/index.html new file mode 100644 index 0000000..0403a96 --- /dev/null +++ b/codemirror/mode/mysql/index.html @@ -0,0 +1,41 @@ + + + + + CodeMirror: MySQL mode + + + + + + + +

CodeMirror: MySQL mode

+
+ + +

MIME types defined: text/x-mysql.

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

CodeMirror: NTriples mode

+
+ +
+ + +

MIME types defined: text/n-triples.

+ + diff --git a/codemirror/mode/ntriples/ntriples.js b/codemirror/mode/ntriples/ntriples.js new file mode 100644 index 0000000..ced8645 --- /dev/null +++ b/codemirror/mode/ntriples/ntriples.js @@ -0,0 +1,170 @@ +/********************************************************** +* This script provides syntax highlighting support for +* the Ntriples format. +* Ntriples format specification: +* http://www.w3.org/TR/rdf-testcases/#ntriples +***********************************************************/ + +/* + The following expression defines the defined ASF grammar transitions. + + pre_subject -> + { + ( writing_subject_uri | writing_bnode_uri ) + -> pre_predicate + -> writing_predicate_uri + -> pre_object + -> writing_object_uri | writing_object_bnode | + ( + writing_object_literal + -> writing_literal_lang | writing_literal_type + ) + -> post_object + -> BEGIN + } otherwise { + -> ERROR + } +*/ +CodeMirror.defineMode("ntriples", function() { + + var Location = { + PRE_SUBJECT : 0, + WRITING_SUB_URI : 1, + WRITING_BNODE_URI : 2, + PRE_PRED : 3, + WRITING_PRED_URI : 4, + PRE_OBJ : 5, + WRITING_OBJ_URI : 6, + WRITING_OBJ_BNODE : 7, + WRITING_OBJ_LITERAL : 8, + WRITING_LIT_LANG : 9, + WRITING_LIT_TYPE : 10, + POST_OBJ : 11, + ERROR : 12 + }; + function transitState(currState, c) { + var currLocation = currState.location; + var ret; + + // Opening. + if (currLocation == Location.PRE_SUBJECT && c == '<') ret = Location.WRITING_SUB_URI; + else if(currLocation == Location.PRE_SUBJECT && c == '_') ret = Location.WRITING_BNODE_URI; + else if(currLocation == Location.PRE_PRED && c == '<') ret = Location.WRITING_PRED_URI; + else if(currLocation == Location.PRE_OBJ && c == '<') ret = Location.WRITING_OBJ_URI; + else if(currLocation == Location.PRE_OBJ && c == '_') ret = Location.WRITING_OBJ_BNODE; + else if(currLocation == Location.PRE_OBJ && c == '"') ret = Location.WRITING_OBJ_LITERAL; + + // Closing. + else if(currLocation == Location.WRITING_SUB_URI && c == '>') ret = Location.PRE_PRED; + else if(currLocation == Location.WRITING_BNODE_URI && c == ' ') ret = Location.PRE_PRED; + else if(currLocation == Location.WRITING_PRED_URI && c == '>') ret = Location.PRE_OBJ; + else if(currLocation == Location.WRITING_OBJ_URI && c == '>') ret = Location.POST_OBJ; + else if(currLocation == Location.WRITING_OBJ_BNODE && c == ' ') ret = Location.POST_OBJ; + else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '"') ret = Location.POST_OBJ; + else if(currLocation == Location.WRITING_LIT_LANG && c == ' ') ret = Location.POST_OBJ; + else if(currLocation == Location.WRITING_LIT_TYPE && c == '>') ret = Location.POST_OBJ; + + // Closing typed and language literal. + else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '@') ret = Location.WRITING_LIT_LANG; + else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '^') ret = Location.WRITING_LIT_TYPE; + + // Spaces. + else if( c == ' ' && + ( + currLocation == Location.PRE_SUBJECT || + currLocation == Location.PRE_PRED || + currLocation == Location.PRE_OBJ || + currLocation == Location.POST_OBJ + ) + ) ret = currLocation; + + // Reset. + else if(currLocation == Location.POST_OBJ && c == '.') ret = Location.PRE_SUBJECT; + + // Error + else ret = Location.ERROR; + + currState.location=ret; + } + + return { + startState: function() { + return { + location : Location.PRE_SUBJECT, + uris : [], + anchors : [], + bnodes : [], + langs : [], + types : [] + }; + }, + token: function(stream, state) { + var ch = stream.next(); + if(ch == '<') { + transitState(state, ch); + var parsedURI = ''; + stream.eatWhile( function(c) { if( c != '#' && c != '>' ) { parsedURI += c; return true; } return false;} ); + state.uris.push(parsedURI); + if( stream.match('#', false) ) return 'variable'; + stream.next(); + transitState(state, '>'); + return 'variable'; + } + if(ch == '#') { + var parsedAnchor = ''; + stream.eatWhile(function(c) { if(c != '>' && c != ' ') { parsedAnchor+= c; return true; } return false;}); + state.anchors.push(parsedAnchor); + return 'variable-2'; + } + if(ch == '>') { + transitState(state, '>'); + return 'variable'; + } + if(ch == '_') { + transitState(state, ch); + var parsedBNode = ''; + stream.eatWhile(function(c) { if( c != ' ' ) { parsedBNode += c; return true; } return false;}); + state.bnodes.push(parsedBNode); + stream.next(); + transitState(state, ' '); + return 'builtin'; + } + if(ch == '"') { + transitState(state, ch); + stream.eatWhile( function(c) { return c != '"'; } ); + stream.next(); + if( stream.peek() != '@' && stream.peek() != '^' ) { + transitState(state, '"'); + } + return 'string'; + } + if( ch == '@' ) { + transitState(state, '@'); + var parsedLang = ''; + stream.eatWhile(function(c) { if( c != ' ' ) { parsedLang += c; return true; } return false;}); + state.langs.push(parsedLang); + stream.next(); + transitState(state, ' '); + return 'string-2'; + } + if( ch == '^' ) { + stream.next(); + transitState(state, '^'); + var parsedType = ''; + stream.eatWhile(function(c) { if( c != '>' ) { parsedType += c; return true; } return false;} ); + state.types.push(parsedType); + stream.next(); + transitState(state, '>'); + return 'variable'; + } + if( ch == ' ' ) { + transitState(state, ch); + } + if( ch == '.' ) { + transitState(state, ch); + } + } + }; +}); + +CodeMirror.defineMIME("text/n-triples", "ntriples"); diff --git a/codemirror/mode/ocaml/index.html b/codemirror/mode/ocaml/index.html new file mode 100644 index 0000000..962fa29 --- /dev/null +++ b/codemirror/mode/ocaml/index.html @@ -0,0 +1,131 @@ + + +CodeMirror: OCaml mode + + + + + + + + + + +

CodeMirror: OCaml mode

+ + + + + +

MIME types defined: text/x-ocaml.

diff --git a/codemirror/mode/ocaml/ocaml.js b/codemirror/mode/ocaml/ocaml.js new file mode 100644 index 0000000..2ce3fb8 --- /dev/null +++ b/codemirror/mode/ocaml/ocaml.js @@ -0,0 +1,113 @@ +CodeMirror.defineMode('ocaml', function() { + + var words = { + 'true': 'atom', + 'false': 'atom', + 'let': 'keyword', + 'rec': 'keyword', + 'in': 'keyword', + 'of': 'keyword', + 'and': 'keyword', + 'succ': 'keyword', + 'if': 'keyword', + 'then': 'keyword', + 'else': 'keyword', + 'for': 'keyword', + 'to': 'keyword', + 'while': 'keyword', + 'do': 'keyword', + 'done': 'keyword', + 'fun': 'keyword', + 'function': 'keyword', + 'val': 'keyword', + 'type': 'keyword', + 'mutable': 'keyword', + 'match': 'keyword', + 'with': 'keyword', + 'try': 'keyword', + 'raise': 'keyword', + 'begin': 'keyword', + 'end': 'keyword', + 'open': 'builtin', + 'trace': 'builtin', + 'ignore': 'builtin', + 'exit': 'builtin', + 'print_string': 'builtin', + 'print_endline': 'builtin' + }; + + function tokenBase(stream, state) { + var ch = stream.next(); + + if (ch === '"') { + state.tokenize = tokenString; + return state.tokenize(stream, state); + } + if (ch === '(') { + if (stream.eat('*')) { + state.commentLevel++; + state.tokenize = tokenComment; + return state.tokenize(stream, state); + } + } + if (ch === '~') { + stream.eatWhile(/\w/); + return 'variable-2'; + } + if (ch === '`') { + stream.eatWhile(/\w/); + return 'quote'; + } + if (/\d/.test(ch)) { + stream.eatWhile(/[\d]/); + if (stream.eat('.')) { + stream.eatWhile(/[\d]/); + } + return 'number'; + } + if ( /[+\-*&%=<>!?|]/.test(ch)) { + return 'operator'; + } + stream.eatWhile(/\w/); + var cur = stream.current(); + return words[cur] || 'variable'; + } + + function tokenString(stream, state) { + var next, end = false, escaped = false; + while ((next = stream.next()) != null) { + if (next === '"' && !escaped) { + end = true; + break; + } + escaped = !escaped && next === '\\'; + } + if (end && !escaped) { + state.tokenize = tokenBase; + } + return 'string'; + }; + + function tokenComment(stream, state) { + var prev, next; + while(state.commentLevel > 0 && (next = stream.next()) != null) { + if (prev === '(' && next === '*') state.commentLevel++; + if (prev === '*' && next === ')') state.commentLevel--; + prev = next; + } + if (state.commentLevel <= 0) { + state.tokenize = tokenBase; + } + return 'comment'; + } + + return { + startState: function() {return {tokenize: tokenBase, commentLevel: 0};}, + token: function(stream, state) { + if (stream.eatSpace()) return null; + return state.tokenize(stream, state); + } + }; +}); + +CodeMirror.defineMIME('text/x-ocaml', 'ocaml'); diff --git a/codemirror/mode/pascal/LICENSE b/codemirror/mode/pascal/LICENSE new file mode 100644 index 0000000..8e3747e --- /dev/null +++ b/codemirror/mode/pascal/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2011 souceLair + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/codemirror/mode/pascal/index.html b/codemirror/mode/pascal/index.html new file mode 100644 index 0000000..b3016af --- /dev/null +++ b/codemirror/mode/pascal/index.html @@ -0,0 +1,48 @@ + + + + + CodeMirror: Pascal mode + + + + + + + +

CodeMirror: Pascal mode

+ +
+ + + +

MIME types defined: text/x-pascal.

+ + diff --git a/codemirror/mode/pascal/pascal.js b/codemirror/mode/pascal/pascal.js new file mode 100644 index 0000000..09d9b06 --- /dev/null +++ b/codemirror/mode/pascal/pascal.js @@ -0,0 +1,94 @@ +CodeMirror.defineMode("pascal", function() { + function words(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + var keywords = words("and array begin case const div do downto else end file for forward integer " + + "boolean char function goto if in label mod nil not of or packed procedure " + + "program record repeat set string then to type until var while with"); + var atoms = {"null": true}; + + var isOperatorChar = /[+\-*&%=<>!?|\/]/; + + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == "#" && state.startOfLine) { + stream.skipToEnd(); + return "meta"; + } + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + if (ch == "(" && stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } + if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + return null; + } + if (/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/); + return "number"; + } + if (ch == "/") { + if (stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } + } + if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return "operator"; + } + stream.eatWhile(/[\w\$_]/); + var cur = stream.current(); + if (keywords.propertyIsEnumerable(cur)) return "keyword"; + if (atoms.propertyIsEnumerable(cur)) return "atom"; + return "variable"; + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) {end = true; break;} + escaped = !escaped && next == "\\"; + } + if (end || !escaped) state.tokenize = null; + return "string"; + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == ")" && maybeEnd) { + state.tokenize = null; + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + + // Interface + + return { + startState: function() { + return {tokenize: null}; + }, + + token: function(stream, state) { + if (stream.eatSpace()) return null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style == "comment" || style == "meta") return style; + return style; + }, + + electricChars: "{}" + }; +}); + +CodeMirror.defineMIME("text/x-pascal", "pascal"); diff --git a/codemirror/mode/perl/LICENSE b/codemirror/mode/perl/LICENSE new file mode 100644 index 0000000..96f4115 --- /dev/null +++ b/codemirror/mode/perl/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011 by Sabaca under the MIT license. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/codemirror/mode/perl/index.html b/codemirror/mode/perl/index.html new file mode 100644 index 0000000..13c7af6 --- /dev/null +++ b/codemirror/mode/perl/index.html @@ -0,0 +1,62 @@ + + + + + CodeMirror: Perl mode + + + + + + + +

CodeMirror: Perl mode

+ +
+ + + +

MIME types defined: text/x-perl.

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

CodeMirror: PHP mode

+ +
+ + + +

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

+ +

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

+ + diff --git a/codemirror/mode/php/php.js b/codemirror/mode/php/php.js new file mode 100644 index 0000000..ea32fda --- /dev/null +++ b/codemirror/mode/php/php.js @@ -0,0 +1,129 @@ +(function() { + function keywords(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + function heredoc(delim) { + return function(stream, state) { + if (stream.match(delim)) state.tokenize = null; + else stream.skipToEnd(); + return "string"; + }; + } + var phpConfig = { + name: "clike", + keywords: keywords("abstract and array as break case catch class clone const continue declare default " + + "do else elseif enddeclare endfor endforeach endif endswitch endwhile extends final " + + "for foreach function global goto if implements interface instanceof namespace " + + "new or private protected public static switch throw trait try use var while xor " + + "die echo empty exit eval include include_once isset list require require_once return " + + "print unset __halt_compiler self static parent"), + blockKeywords: keywords("catch do else elseif for foreach if switch try while"), + atoms: keywords("true false null TRUE FALSE NULL __CLASS__ __DIR__ __FILE__ __LINE__ __METHOD__ __FUNCTION__ __NAMESPACE__"), + builtin: keywords("func_num_args func_get_arg func_get_args strlen strcmp strncmp strcasecmp strncasecmp each error_reporting define defined trigger_error user_error set_error_handler restore_error_handler get_declared_classes get_loaded_extensions extension_loaded get_extension_funcs debug_backtrace constant bin2hex sleep usleep time mktime gmmktime strftime gmstrftime strtotime date gmdate getdate localtime checkdate flush wordwrap htmlspecialchars htmlentities html_entity_decode md5 md5_file crc32 getimagesize image_type_to_mime_type phpinfo phpversion phpcredits strnatcmp strnatcasecmp substr_count strspn strcspn strtok strtoupper strtolower strpos strrpos strrev hebrev hebrevc nl2br basename dirname pathinfo stripslashes stripcslashes strstr stristr strrchr str_shuffle str_word_count strcoll substr substr_replace quotemeta ucfirst ucwords strtr addslashes addcslashes rtrim str_replace str_repeat count_chars chunk_split trim ltrim strip_tags similar_text explode implode setlocale localeconv parse_str str_pad chop strchr sprintf printf vprintf vsprintf sscanf fscanf parse_url urlencode urldecode rawurlencode rawurldecode readlink linkinfo link unlink exec system escapeshellcmd escapeshellarg passthru shell_exec proc_open proc_close rand srand getrandmax mt_rand mt_srand mt_getrandmax base64_decode base64_encode abs ceil floor round is_finite is_nan is_infinite bindec hexdec octdec decbin decoct dechex base_convert number_format fmod ip2long long2ip getenv putenv getopt microtime gettimeofday getrusage uniqid quoted_printable_decode set_time_limit get_cfg_var magic_quotes_runtime set_magic_quotes_runtime get_magic_quotes_gpc get_magic_quotes_runtime import_request_variables error_log serialize unserialize memory_get_usage var_dump var_export debug_zval_dump print_r highlight_file show_source highlight_string ini_get ini_get_all ini_set ini_alter ini_restore get_include_path set_include_path restore_include_path setcookie header headers_sent connection_aborted connection_status ignore_user_abort parse_ini_file is_uploaded_file move_uploaded_file intval floatval doubleval strval gettype settype is_null is_resource is_bool is_long is_float is_int is_integer is_double is_real is_numeric is_string is_array is_object is_scalar ereg ereg_replace eregi eregi_replace split spliti join sql_regcase dl pclose popen readfile rewind rmdir umask fclose feof fgetc fgets fgetss fread fopen fpassthru ftruncate fstat fseek ftell fflush fwrite fputs mkdir rename copy tempnam tmpfile file file_get_contents stream_select stream_context_create stream_context_set_params stream_context_set_option stream_context_get_options stream_filter_prepend stream_filter_append fgetcsv flock get_meta_tags stream_set_write_buffer set_file_buffer set_socket_blocking stream_set_blocking socket_set_blocking stream_get_meta_data stream_register_wrapper stream_wrapper_register stream_set_timeout socket_set_timeout socket_get_status realpath fnmatch fsockopen pfsockopen pack unpack get_browser crypt opendir closedir chdir getcwd rewinddir readdir dir glob fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype file_exists is_writable is_writeable is_readable is_executable is_file is_dir is_link stat lstat chown touch clearstatcache mail ob_start ob_flush ob_clean ob_end_flush ob_end_clean ob_get_flush ob_get_clean ob_get_length ob_get_level ob_get_status ob_get_contents ob_implicit_flush ob_list_handlers ksort krsort natsort natcasesort asort arsort sort rsort usort uasort uksort shuffle array_walk count end prev next reset current key min max in_array array_search extract compact array_fill range array_multisort array_push array_pop array_shift array_unshift array_splice array_slice array_merge array_merge_recursive array_keys array_values array_count_values array_reverse array_reduce array_pad array_flip array_change_key_case array_rand array_unique array_intersect array_intersect_assoc array_diff array_diff_assoc array_sum array_filter array_map array_chunk array_key_exists pos sizeof key_exists assert assert_options version_compare ftok str_rot13 aggregate session_name session_module_name session_save_path session_id session_regenerate_id session_decode session_register session_unregister session_is_registered session_encode session_start session_destroy session_unset session_set_save_handler session_cache_limiter session_cache_expire session_set_cookie_params session_get_cookie_params session_write_close preg_match preg_match_all preg_replace preg_replace_callback preg_split preg_quote preg_grep overload ctype_alnum ctype_alpha ctype_cntrl ctype_digit ctype_lower ctype_graph ctype_print ctype_punct ctype_space ctype_upper ctype_xdigit virtual apache_request_headers apache_note apache_lookup_uri apache_child_terminate apache_setenv apache_response_headers apache_get_version getallheaders mysql_connect mysql_pconnect mysql_close mysql_select_db mysql_create_db mysql_drop_db mysql_query mysql_unbuffered_query mysql_db_query mysql_list_dbs mysql_list_tables mysql_list_fields mysql_list_processes mysql_error mysql_errno mysql_affected_rows mysql_insert_id mysql_result mysql_num_rows mysql_num_fields mysql_fetch_row mysql_fetch_array mysql_fetch_assoc mysql_fetch_object mysql_data_seek mysql_fetch_lengths mysql_fetch_field mysql_field_seek mysql_free_result mysql_field_name mysql_field_table mysql_field_len mysql_field_type mysql_field_flags mysql_escape_string mysql_real_escape_string mysql_stat mysql_thread_id mysql_client_encoding mysql_get_client_info mysql_get_host_info mysql_get_proto_info mysql_get_server_info mysql_info mysql mysql_fieldname mysql_fieldtable mysql_fieldlen mysql_fieldtype mysql_fieldflags mysql_selectdb mysql_createdb mysql_dropdb mysql_freeresult mysql_numfields mysql_numrows mysql_listdbs mysql_listtables mysql_listfields mysql_db_name mysql_dbname mysql_tablename mysql_table_name pg_connect pg_pconnect pg_close pg_connection_status pg_connection_busy pg_connection_reset pg_host pg_dbname pg_port pg_tty pg_options pg_ping pg_query pg_send_query pg_cancel_query pg_fetch_result pg_fetch_row pg_fetch_assoc pg_fetch_array pg_fetch_object pg_fetch_all pg_affected_rows pg_get_result pg_result_seek pg_result_status pg_free_result pg_last_oid pg_num_rows pg_num_fields pg_field_name pg_field_num pg_field_size pg_field_type pg_field_prtlen pg_field_is_null pg_get_notify pg_get_pid pg_result_error pg_last_error pg_last_notice pg_put_line pg_end_copy pg_copy_to pg_copy_from pg_trace pg_untrace pg_lo_create pg_lo_unlink pg_lo_open pg_lo_close pg_lo_read pg_lo_write pg_lo_read_all pg_lo_import pg_lo_export pg_lo_seek pg_lo_tell pg_escape_string pg_escape_bytea pg_unescape_bytea pg_client_encoding pg_set_client_encoding pg_meta_data pg_convert pg_insert pg_update pg_delete pg_select pg_exec pg_getlastoid pg_cmdtuples pg_errormessage pg_numrows pg_numfields pg_fieldname pg_fieldsize pg_fieldtype pg_fieldnum pg_fieldprtlen pg_fieldisnull pg_freeresult pg_result pg_loreadall pg_locreate pg_lounlink pg_loopen pg_loclose pg_loread pg_lowrite pg_loimport pg_loexport echo print global static exit array empty eval isset unset die include require include_once require_once"), + multiLineStrings: true, + hooks: { + "$": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "variable-2"; + }, + "<": function(stream, state) { + if (stream.match(/<", false)) stream.next(); + return "comment"; + }, + "/": function(stream) { + if (stream.eat("/")) { + while (!stream.eol() && !stream.match("?>", false)) stream.next(); + return "comment"; + } + return false; + } + } + }; + + CodeMirror.defineMode("php", function(config, parserConfig) { + var htmlMode = CodeMirror.getMode(config, "text/html"); + var phpMode = CodeMirror.getMode(config, phpConfig); + + function dispatch(stream, state) { + var isPHP = state.curMode == phpMode; + if (stream.sol() && state.pending != '"') state.pending = null; + if (!isPHP) { + if (stream.match(/^<\?\w*/)) { + state.curMode = phpMode; + state.curState = state.php; + return "meta"; + } + if (state.pending == '"') { + while (!stream.eol() && stream.next() != '"') {} + var style = "string"; + } else if (state.pending && stream.pos < state.pending.end) { + stream.pos = state.pending.end; + var style = state.pending.style; + } else { + var style = htmlMode.token(stream, state.curState); + } + state.pending = null; + var cur = stream.current(), openPHP = cur.search(/<\?/); + if (openPHP != -1) { + if (style == "string" && /\"$/.test(cur) && !/\?>/.test(cur)) state.pending = '"'; + else state.pending = {end: stream.pos, style: style}; + stream.backUp(cur.length - openPHP); + } + return style; + } else if (isPHP && state.php.tokenize == null && stream.match("?>")) { + state.curMode = htmlMode; + state.curState = state.html; + return "meta"; + } else { + return phpMode.token(stream, state.curState); + } + } + + return { + startState: function() { + var html = CodeMirror.startState(htmlMode), php = CodeMirror.startState(phpMode); + return {html: html, + php: php, + curMode: parserConfig.startOpen ? phpMode : htmlMode, + curState: parserConfig.startOpen ? php : html, + pending: null}; + }, + + copyState: function(state) { + var html = state.html, htmlNew = CodeMirror.copyState(htmlMode, html), + php = state.php, phpNew = CodeMirror.copyState(phpMode, php), cur; + if (state.curMode == htmlMode) cur = htmlNew; + else cur = phpNew; + return {html: htmlNew, php: phpNew, curMode: state.curMode, curState: cur, + pending: state.pending}; + }, + + token: dispatch, + + indent: function(state, textAfter) { + if ((state.curMode != phpMode && /^\s*<\//.test(textAfter)) || + (state.curMode == phpMode && /^\?>/.test(textAfter))) + return htmlMode.indent(state.html, textAfter); + return state.curMode.indent(state.curState, textAfter); + }, + + electricChars: "/{}:", + + innerMode: function(state) { return {state: state.curState, mode: state.curMode}; } + }; + }, "htmlmixed"); + + CodeMirror.defineMIME("application/x-httpd-php", "php"); + CodeMirror.defineMIME("application/x-httpd-php-open", {name: "php", startOpen: true}); + CodeMirror.defineMIME("text/x-php", phpConfig); +})(); diff --git a/codemirror/mode/pig/index.html b/codemirror/mode/pig/index.html new file mode 100644 index 0000000..1b0c602 --- /dev/null +++ b/codemirror/mode/pig/index.html @@ -0,0 +1,42 @@ + + + + + CodeMirror: Pig Latin mode + + + + + + + +

CodeMirror: Pig Latin mode

+ +
+ + + +

+ Simple mode that handles Pig Latin language. +

+ +

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

CodeMirror: Oracle PL/SQL mode

+ +
+ + + +

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

+ +

MIME type defined: text/x-plsql + (PLSQL code) + diff --git a/codemirror/mode/plsql/plsql.js b/codemirror/mode/plsql/plsql.js new file mode 100644 index 0000000..df119ba --- /dev/null +++ b/codemirror/mode/plsql/plsql.js @@ -0,0 +1,216 @@ +CodeMirror.defineMode("plsql", function(_config, parserConfig) { + var keywords = parserConfig.keywords, + functions = parserConfig.functions, + types = parserConfig.types, + sqlplus = parserConfig.sqlplus, + multiLineStrings = parserConfig.multiLineStrings; + var isOperatorChar = /[+\-*&%=<>!?:\/|]/; + function chain(stream, state, f) { + state.tokenize = f; + return f(stream, state); + } + + var type; + function ret(tp, style) { + type = tp; + return style; + } + + function tokenBase(stream, state) { + var ch = stream.next(); + // start of string? + if (ch == '"' || ch == "'") + return chain(stream, state, tokenString(ch)); + // is it one of the special signs []{}().,;? Seperator? + else if (/[\[\]{}\(\),;\.]/.test(ch)) + return ret(ch); + // start of a number value? + else if (/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/); + return ret("number", "number"); + } + // multi line comment or simple operator? + else if (ch == "/") { + if (stream.eat("*")) { + return chain(stream, state, tokenComment); + } + else { + stream.eatWhile(isOperatorChar); + return ret("operator", "operator"); + } + } + // single line comment or simple operator? + else if (ch == "-") { + if (stream.eat("-")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } + else { + stream.eatWhile(isOperatorChar); + return ret("operator", "operator"); + } + } + // pl/sql variable? + else if (ch == "@" || ch == "$") { + stream.eatWhile(/[\w\d\$_]/); + return ret("word", "variable"); + } + // is it a operator? + else if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return ret("operator", "operator"); + } + else { + // get the whole word + stream.eatWhile(/[\w\$_]/); + // is it one of the listed keywords? + if (keywords && keywords.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "keyword"); + // is it one of the listed functions? + if (functions && functions.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "builtin"); + // is it one of the listed types? + if (types && types.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "variable-2"); + // is it one of the listed sqlplus keywords? + if (sqlplus && sqlplus.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "variable-3"); + // default: just a "variable" + return ret("word", "variable"); + } + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) {end = true; break;} + escaped = !escaped && next == "\\"; + } + if (end || !(escaped || multiLineStrings)) + state.tokenize = tokenBase; + return ret("string", "plsql-string"); + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return ret("comment", "plsql-comment"); + } + + // Interface + + return { + startState: function() { + return { + tokenize: tokenBase, + startOfLine: true + }; + }, + + token: function(stream, state) { + if (stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + return style; + } + }; +}); + +(function() { + function keywords(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + var cKeywords = "abort accept access add all alter and any array arraylen as asc assert assign at attributes audit " + + "authorization avg " + + "base_table begin between binary_integer body boolean by " + + "case cast char char_base check close cluster clusters colauth column comment commit compress connect " + + "connected constant constraint crash create current currval cursor " + + "data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete " + + "desc digits dispose distinct do drop " + + "else elsif enable end entry escape exception exception_init exchange exclusive exists exit external " + + "fast fetch file for force form from function " + + "generic goto grant group " + + "having " + + "identified if immediate in increment index indexes indicator initial initrans insert interface intersect " + + "into is " + + "key " + + "level library like limited local lock log logging long loop " + + "master maxextents maxtrans member minextents minus mislabel mode modify multiset " + + "new next no noaudit nocompress nologging noparallel not nowait number_base " + + "object of off offline on online only open option or order out " + + "package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior " + + "private privileges procedure public " + + "raise range raw read rebuild record ref references refresh release rename replace resource restrict return " + + "returning reverse revoke rollback row rowid rowlabel rownum rows run " + + "savepoint schema segment select separate session set share snapshot some space split sql start statement " + + "storage subtype successful synonym " + + "tabauth table tables tablespace task terminate then to trigger truncate type " + + "union unique unlimited unrecoverable unusable update use using " + + "validate value values variable view views " + + "when whenever where while with work"; + + var cFunctions = "abs acos add_months ascii asin atan atan2 average " + + "bfilename " + + "ceil chartorowid chr concat convert cos cosh count " + + "decode deref dual dump dup_val_on_index " + + "empty error exp " + + "false floor found " + + "glb greatest " + + "hextoraw " + + "initcap instr instrb isopen " + + "last_day least lenght lenghtb ln lower lpad ltrim lub " + + "make_ref max min mod months_between " + + "new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower " + + "nls_sort nls_upper nlssort no_data_found notfound null nvl " + + "others " + + "power " + + "rawtohex reftohex round rowcount rowidtochar rpad rtrim " + + "sign sin sinh soundex sqlcode sqlerrm sqrt stddev substr substrb sum sysdate " + + "tan tanh to_char to_date to_label to_multi_byte to_number to_single_byte translate true trunc " + + "uid upper user userenv " + + "variance vsize"; + + var cTypes = "bfile blob " + + "character clob " + + "dec " + + "float " + + "int integer " + + "mlslabel " + + "natural naturaln nchar nclob number numeric nvarchar2 " + + "real rowtype " + + "signtype smallint string " + + "varchar varchar2"; + + var cSqlplus = "appinfo arraysize autocommit autoprint autorecovery autotrace " + + "blockterminator break btitle " + + "cmdsep colsep compatibility compute concat copycommit copytypecheck " + + "define describe " + + "echo editfile embedded escape exec execute " + + "feedback flagger flush " + + "heading headsep " + + "instance " + + "linesize lno loboffset logsource long longchunksize " + + "markup " + + "native newpage numformat numwidth " + + "pagesize pause pno " + + "recsep recsepchar release repfooter repheader " + + "serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber " + + "sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix " + + "tab term termout time timing trimout trimspool ttitle " + + "underline " + + "verify version " + + "wrap"; + + CodeMirror.defineMIME("text/x-plsql", { + name: "plsql", + keywords: keywords(cKeywords), + functions: keywords(cFunctions), + types: keywords(cTypes), + sqlplus: keywords(cSqlplus) + }); +}()); diff --git a/codemirror/mode/properties/index.html b/codemirror/mode/properties/index.html new file mode 100644 index 0000000..e21e02a --- /dev/null +++ b/codemirror/mode/properties/index.html @@ -0,0 +1,41 @@ + + + + + CodeMirror: Properties files mode + + + + + + + +

CodeMirror: Properties files mode

+
+ + +

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

+ + + diff --git a/codemirror/mode/properties/properties.js b/codemirror/mode/properties/properties.js new file mode 100644 index 0000000..d3a13c7 --- /dev/null +++ b/codemirror/mode/properties/properties.js @@ -0,0 +1,63 @@ +CodeMirror.defineMode("properties", function() { + return { + token: function(stream, state) { + var sol = stream.sol() || state.afterSection; + var eol = stream.eol(); + + state.afterSection = false; + + if (sol) { + if (state.nextMultiline) { + state.inMultiline = true; + state.nextMultiline = false; + } else { + state.position = "def"; + } + } + + if (eol && ! state.nextMultiline) { + state.inMultiline = false; + state.position = "def"; + } + + if (sol) { + while(stream.eatSpace()); + } + + var ch = stream.next(); + + if (sol && (ch === "#" || ch === "!" || ch === ";")) { + state.position = "comment"; + stream.skipToEnd(); + return "comment"; + } else if (sol && ch === "[") { + state.afterSection = true; + stream.skipTo("]"); stream.eat("]"); + return "header"; + } else if (ch === "=" || ch === ":") { + state.position = "quote"; + return null; + } else if (ch === "\\" && state.position === "quote") { + if (stream.next() !== "u") { // u = Unicode sequence \u1234 + // Multiline value + state.nextMultiline = true; + } + } + + return state.position; + }, + + startState: function() { + return { + position : "def", // Current position, "def", "quote" or "comment" + nextMultiline : false, // Is the next line multiline value + inMultiline : false, // Is the current line a multiline value + afterSection : false // Did we just open a section + }; + } + + }; +}); + +CodeMirror.defineMIME("text/x-properties", "properties"); +CodeMirror.defineMIME("text/x-ini", "properties"); diff --git a/codemirror/mode/python/LICENSE.txt b/codemirror/mode/python/LICENSE.txt new file mode 100644 index 0000000..918866b --- /dev/null +++ b/codemirror/mode/python/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2010 Timothy Farrell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/codemirror/mode/python/index.html b/codemirror/mode/python/index.html new file mode 100644 index 0000000..7a26d27 --- /dev/null +++ b/codemirror/mode/python/index.html @@ -0,0 +1,124 @@ + + + + + CodeMirror: Python mode + + + + + + + + +

CodeMirror: Python mode

+ +
+ +

Configuration Options:

+
    +
  • version - 2/3 - The version of Python to recognize. Default is 2.
  • +
  • singleLineStringErrors - true/false - If you have a single-line string that is not terminated at the end of the line, this will show subsequent lines as errors if true, otherwise it will consider the newline as the end of the string. Default is false.
  • +
+ +

MIME types defined: text/x-python.

+ + diff --git a/codemirror/mode/python/python.js b/codemirror/mode/python/python.js new file mode 100644 index 0000000..a12e326 --- /dev/null +++ b/codemirror/mode/python/python.js @@ -0,0 +1,340 @@ +CodeMirror.defineMode("python", function(conf, parserConf) { + var ERRORCLASS = 'error'; + + function wordRegexp(words) { + return new RegExp("^((" + words.join(")|(") + "))\\b"); + } + + var singleOperators = 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 wordOperators = wordRegexp(['and', 'or', 'not', 'is', 'in']); + var commonkeywords = ['as', 'assert', 'break', 'class', 'continue', + 'def', 'del', 'elif', 'else', 'except', 'finally', + 'for', 'from', 'global', 'if', 'import', + 'lambda', 'pass', 'raise', 'return', + 'try', 'while', 'with', 'yield']; + var commonBuiltins = ['abs', 'all', 'any', 'bin', 'bool', 'bytearray', 'callable', 'chr', + 'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod', + 'enumerate', 'eval', 'filter', 'float', 'format', 'frozenset', + 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', + 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', + 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', + 'object', 'oct', 'open', 'ord', 'pow', 'property', 'range', + 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', + 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', + 'type', 'vars', 'zip', '__import__', 'NotImplemented', + 'Ellipsis', '__debug__']; + var py2 = {'builtins': ['apply', 'basestring', 'buffer', 'cmp', 'coerce', 'execfile', + 'file', 'intern', 'long', 'raw_input', 'reduce', 'reload', + 'unichr', 'unicode', 'xrange', 'False', 'True', 'None'], + 'keywords': ['exec', 'print']}; + var py3 = {'builtins': ['ascii', 'bytes', 'exec', 'print'], + 'keywords': ['nonlocal', 'False', 'True', 'None']}; + + if (!!parserConf.version && parseInt(parserConf.version, 10) === 3) { + commonkeywords = commonkeywords.concat(py3.keywords); + commonBuiltins = commonBuiltins.concat(py3.builtins); + var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i"); + } else { + commonkeywords = commonkeywords.concat(py2.keywords); + commonBuiltins = commonBuiltins.concat(py2.builtins); + var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i"); + } + var keywords = wordRegexp(commonkeywords); + var builtins = wordRegexp(commonBuiltins); + + var indentInfo = null; + + // tokenizers + function tokenBase(stream, state) { + // Handle scope changes + if (stream.sol()) { + var scopeOffset = state.scopes[0].offset; + if (stream.eatSpace()) { + var lineOffset = stream.indentation(); + if (lineOffset > scopeOffset) { + indentInfo = 'indent'; + } else if (lineOffset < scopeOffset) { + indentInfo = 'dedent'; + } + return null; + } else { + if (scopeOffset > 0) { + dedent(stream, state); + } + } + } + if (stream.eatSpace()) { + return null; + } + + var ch = stream.peek(); + + // Handle Comments + if (ch === '#') { + stream.skipToEnd(); + return 'comment'; + } + + // Handle Number Literals + if (stream.match(/^[0-9\.]/, false)) { + var floatLiteral = false; + // Floats + if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; } + if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; } + if (stream.match(/^\.\d+/)) { floatLiteral = true; } + if (floatLiteral) { + // Float literals may be "imaginary" + stream.eat(/J/i); + return 'number'; + } + // Integers + var intLiteral = false; + // Hex + if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; } + // Binary + if (stream.match(/^0b[01]+/i)) { intLiteral = true; } + // Octal + if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; } + // Decimal + if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) { + // Decimal literals may be "imaginary" + stream.eat(/J/i); + // TODO - Can you have imaginary longs? + intLiteral = true; + } + // Zero by itself with no other piece of number. + if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; } + if (intLiteral) { + // Integer literals may be "long" + stream.eat(/L/i); + return 'number'; + } + } + + // Handle Strings + if (stream.match(stringPrefixes)) { + state.tokenize = tokenStringFactory(stream.current()); + return state.tokenize(stream, state); + } + + // Handle operators and Delimiters + if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) { + return null; + } + if (stream.match(doubleOperators) + || stream.match(singleOperators) + || stream.match(wordOperators)) { + return 'operator'; + } + if (stream.match(singleDelimiters)) { + return null; + } + + if (stream.match(keywords)) { + return 'keyword'; + } + + if (stream.match(builtins)) { + return 'builtin'; + } + + if (stream.match(identifiers)) { + return 'variable'; + } + + // Handle non-detected items + stream.next(); + return ERRORCLASS; + } + + function tokenStringFactory(delimiter) { + while ('rub'.indexOf(delimiter.charAt(0).toLowerCase()) >= 0) { + delimiter = delimiter.substr(1); + } + var singleline = delimiter.length == 1; + var OUTCLASS = 'string'; + + function tokenString(stream, state) { + while (!stream.eol()) { + stream.eatWhile(/[^'"\\]/); + if (stream.eat('\\')) { + stream.next(); + if (singleline && stream.eol()) { + return OUTCLASS; + } + } else if (stream.match(delimiter)) { + state.tokenize = tokenBase; + return OUTCLASS; + } else { + stream.eat(/['"]/); + } + } + if (singleline) { + if (parserConf.singleLineStringErrors) { + return ERRORCLASS; + } else { + state.tokenize = tokenBase; + } + } + return OUTCLASS; + } + tokenString.isString = true; + return tokenString; + } + + function indent(stream, state, type) { + type = type || 'py'; + var indentUnit = 0; + if (type === 'py') { + if (state.scopes[0].type !== 'py') { + state.scopes[0].offset = stream.indentation(); + return; + } + for (var i = 0; i < state.scopes.length; ++i) { + if (state.scopes[i].type === 'py') { + indentUnit = state.scopes[i].offset + conf.indentUnit; + break; + } + } + } else { + indentUnit = stream.column() + stream.current().length; + } + state.scopes.unshift({ + offset: indentUnit, + type: type + }); + } + + function dedent(stream, state, type) { + type = type || 'py'; + if (state.scopes.length == 1) return; + if (state.scopes[0].type === 'py') { + var _indent = stream.indentation(); + var _indent_index = -1; + for (var i = 0; i < state.scopes.length; ++i) { + if (_indent === state.scopes[i].offset) { + _indent_index = i; + break; + } + } + if (_indent_index === -1) { + return true; + } + while (state.scopes[0].offset !== _indent) { + state.scopes.shift(); + } + return false; + } else { + if (type === 'py') { + state.scopes[0].offset = stream.indentation(); + return false; + } else { + if (state.scopes[0].type != type) { + return true; + } + state.scopes.shift(); + return false; + } + } + } + + function tokenLexer(stream, state) { + indentInfo = null; + var style = state.tokenize(stream, state); + var current = stream.current(); + + // Handle '.' connected identifiers + if (current === '.') { + style = stream.match(identifiers, false) ? null : ERRORCLASS; + if (style === null && state.lastToken === 'meta') { + // Apply 'meta' style to '.' connected identifiers when + // appropriate. + style = 'meta'; + } + return style; + } + + // Handle decorators + if (current === '@') { + return stream.match(identifiers, false) ? 'meta' : ERRORCLASS; + } + + if ((style === 'variable' || style === 'builtin') + && state.lastToken === 'meta') { + style = 'meta'; + } + + // Handle scope changes. + if (current === 'pass' || current === 'return') { + state.dedent += 1; + } + if (current === 'lambda') state.lambda = true; + if ((current === ':' && !state.lambda && state.scopes[0].type == 'py') + || indentInfo === 'indent') { + indent(stream, state); + } + var delimiter_index = '[({'.indexOf(current); + if (delimiter_index !== -1) { + indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1)); + } + if (indentInfo === 'dedent') { + if (dedent(stream, state)) { + return ERRORCLASS; + } + } + delimiter_index = '])}'.indexOf(current); + if (delimiter_index !== -1) { + if (dedent(stream, state, current)) { + return ERRORCLASS; + } + } + if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') { + if (state.scopes.length > 1) state.scopes.shift(); + state.dedent -= 1; + } + + return style; + } + + var external = { + startState: function(basecolumn) { + return { + tokenize: tokenBase, + scopes: [{offset:basecolumn || 0, type:'py'}], + lastToken: null, + lambda: false, + dedent: 0 + }; + }, + + token: function(stream, state) { + var style = tokenLexer(stream, state); + + state.lastToken = style; + + if (stream.eol() && stream.lambda) { + state.lambda = false; + } + + return style; + }, + + indent: function(state) { + if (state.tokenize != tokenBase) { + return state.tokenize.isString ? CodeMirror.Pass : 0; + } + + return state.scopes[0].offset; + } + + }; + return external; +}); + +CodeMirror.defineMIME("text/x-python", "python"); diff --git a/codemirror/mode/r/LICENSE b/codemirror/mode/r/LICENSE new file mode 100644 index 0000000..2510ae1 --- /dev/null +++ b/codemirror/mode/r/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2011, Ubalo, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the Ubalo, Inc nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL UBALO, INC BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/codemirror/mode/r/index.html b/codemirror/mode/r/index.html new file mode 100644 index 0000000..1281955 --- /dev/null +++ b/codemirror/mode/r/index.html @@ -0,0 +1,74 @@ + + + + + CodeMirror: R mode + + + + + + + +

CodeMirror: R mode

+
+ + +

MIME types defined: text/x-rsrc.

+ +

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

+ + + diff --git a/codemirror/mode/r/r.js b/codemirror/mode/r/r.js new file mode 100644 index 0000000..6410efb --- /dev/null +++ b/codemirror/mode/r/r.js @@ -0,0 +1,141 @@ +CodeMirror.defineMode("r", function(config) { + function wordObj(str) { + var words = str.split(" "), res = {}; + for (var i = 0; i < words.length; ++i) res[words[i]] = true; + return res; + } + var atoms = wordObj("NULL NA Inf NaN NA_integer_ NA_real_ NA_complex_ NA_character_"); + var builtins = wordObj("list quote bquote eval return call parse deparse"); + var keywords = wordObj("if else repeat while function for in next break"); + var blockkeywords = wordObj("if else repeat while function for"); + var opChars = /[+\-*\/^<>=!&|~$:]/; + var curPunc; + + function tokenBase(stream, state) { + curPunc = null; + var ch = stream.next(); + if (ch == "#") { + stream.skipToEnd(); + return "comment"; + } else if (ch == "0" && stream.eat("x")) { + stream.eatWhile(/[\da-f]/i); + return "number"; + } else if (ch == "." && stream.eat(/\d/)) { + stream.match(/\d*(?:e[+\-]?\d+)?/); + return "number"; + } else if (/\d/.test(ch)) { + stream.match(/\d*(?:\.\d+)?(?:e[+\-]\d+)?L?/); + return "number"; + } else if (ch == "'" || ch == '"') { + state.tokenize = tokenString(ch); + return "string"; + } else if (ch == "." && stream.match(/.[.\d]+/)) { + return "keyword"; + } else if (/[\w\.]/.test(ch) && ch != "_") { + stream.eatWhile(/[\w\.]/); + var word = stream.current(); + if (atoms.propertyIsEnumerable(word)) return "atom"; + if (keywords.propertyIsEnumerable(word)) { + if (blockkeywords.propertyIsEnumerable(word)) curPunc = "block"; + return "keyword"; + } + if (builtins.propertyIsEnumerable(word)) return "builtin"; + return "variable"; + } else if (ch == "%") { + if (stream.skipTo("%")) stream.next(); + return "variable-2"; + } else if (ch == "<" && stream.eat("-")) { + return "arrow"; + } else if (ch == "=" && state.ctx.argList) { + return "arg-is"; + } else if (opChars.test(ch)) { + if (ch == "$") return "dollar"; + stream.eatWhile(opChars); + return "operator"; + } else if (/[\(\){}\[\];]/.test(ch)) { + curPunc = ch; + if (ch == ";") return "semi"; + return null; + } else { + return null; + } + } + + function tokenString(quote) { + return function(stream, state) { + if (stream.eat("\\")) { + var ch = stream.next(); + if (ch == "x") stream.match(/^[a-f0-9]{2}/i); + else if ((ch == "u" || ch == "U") && stream.eat("{") && stream.skipTo("}")) stream.next(); + else if (ch == "u") stream.match(/^[a-f0-9]{4}/i); + else if (ch == "U") stream.match(/^[a-f0-9]{8}/i); + else if (/[0-7]/.test(ch)) stream.match(/^[0-7]{1,2}/); + return "string-2"; + } else { + var next; + while ((next = stream.next()) != null) { + if (next == quote) { state.tokenize = tokenBase; break; } + if (next == "\\") { stream.backUp(1); break; } + } + return "string"; + } + }; + } + + function push(state, type, stream) { + state.ctx = {type: type, + indent: state.indent, + align: null, + column: stream.column(), + prev: state.ctx}; + } + function pop(state) { + state.indent = state.ctx.indent; + state.ctx = state.ctx.prev; + } + + return { + startState: function() { + return {tokenize: tokenBase, + ctx: {type: "top", + indent: -config.indentUnit, + align: false}, + indent: 0, + afterIdent: false}; + }, + + token: function(stream, state) { + if (stream.sol()) { + if (state.ctx.align == null) state.ctx.align = false; + state.indent = stream.indentation(); + } + if (stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (style != "comment" && state.ctx.align == null) state.ctx.align = true; + + var ctype = state.ctx.type; + if ((curPunc == ";" || curPunc == "{" || curPunc == "}") && ctype == "block") pop(state); + if (curPunc == "{") push(state, "}", stream); + else if (curPunc == "(") { + push(state, ")", stream); + if (state.afterIdent) state.ctx.argList = true; + } + else if (curPunc == "[") push(state, "]", stream); + else if (curPunc == "block") push(state, "block", stream); + else if (curPunc == ctype) pop(state); + state.afterIdent = style == "variable" || style == "keyword"; + return style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), ctx = state.ctx, + closing = firstChar == ctx.type; + if (ctx.type == "block") return ctx.indent + (firstChar == "{" ? 0 : config.indentUnit); + else if (ctx.align) return ctx.column + (closing ? 0 : 1); + else return ctx.indent + (closing ? 0 : config.indentUnit); + } + }; +}); + +CodeMirror.defineMIME("text/x-rsrc", "r"); diff --git a/codemirror/mode/rpm/changes/changes.js b/codemirror/mode/rpm/changes/changes.js new file mode 100644 index 0000000..14a08d9 --- /dev/null +++ b/codemirror/mode/rpm/changes/changes.js @@ -0,0 +1,19 @@ +CodeMirror.defineMode("changes", function() { + var headerSeperator = /^-+$/; + var headerLine = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ?\d{1,2} \d{2}:\d{2}(:\d{2})? [A-Z]{3,4} \d{4} - /; + var simpleEmail = /^[\w+.-]+@[\w.-]+/; + + return { + token: function(stream) { + if (stream.sol()) { + if (stream.match(headerSeperator)) { return 'tag'; } + if (stream.match(headerLine)) { return 'tag'; } + } + if (stream.match(simpleEmail)) { return 'string'; } + stream.next(); + return null; + } + }; +}); + +CodeMirror.defineMIME("text/x-rpm-changes", "changes"); diff --git a/codemirror/mode/rpm/changes/index.html b/codemirror/mode/rpm/changes/index.html new file mode 100644 index 0000000..e0e2d87 --- /dev/null +++ b/codemirror/mode/rpm/changes/index.html @@ -0,0 +1,53 @@ + + + + + CodeMirror: RPM changes mode + + + + + + + +

CodeMirror: RPM changes mode

+ +
+ + +

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

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

CodeMirror: RPM spec mode

+ +
+ + +

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

+ + diff --git a/codemirror/mode/rpm/spec/spec.css b/codemirror/mode/rpm/spec/spec.css new file mode 100644 index 0000000..d0a5d43 --- /dev/null +++ b/codemirror/mode/rpm/spec/spec.css @@ -0,0 +1,5 @@ +.cm-s-default span.cm-preamble {color: #b26818; font-weight: bold;} +.cm-s-default span.cm-macro {color: #b218b2;} +.cm-s-default span.cm-section {color: green; font-weight: bold;} +.cm-s-default span.cm-script {color: red;} +.cm-s-default span.cm-issue {color: yellow;} diff --git a/codemirror/mode/rpm/spec/spec.js b/codemirror/mode/rpm/spec/spec.js new file mode 100644 index 0000000..9f339c2 --- /dev/null +++ b/codemirror/mode/rpm/spec/spec.js @@ -0,0 +1,66 @@ +// Quick and dirty spec file highlighting + +CodeMirror.defineMode("spec", function() { + var arch = /^(i386|i586|i686|x86_64|ppc64|ppc|ia64|s390x|s390|sparc64|sparcv9|sparc|noarch|alphaev6|alpha|hppa|mipsel)/; + + var preamble = /^(Name|Version|Release|License|Summary|Url|Group|Source|BuildArch|BuildRequires|BuildRoot|AutoReqProv|Provides|Requires(\(\w+\))?|Obsoletes|Conflicts|Recommends|Source\d*|Patch\d*|ExclusiveArch|NoSource|Supplements):/; + var section = /^%(debug_package|package|description|prep|build|install|files|clean|changelog|preun|postun|pre|post|triggerin|triggerun|pretrans|posttrans|verifyscript|check|triggerpostun|triggerprein|trigger)/; + var control_flow_complex = /^%(ifnarch|ifarch|if)/; // rpm control flow macros + var control_flow_simple = /^%(else|endif)/; // rpm control flow macros + var operators = /^(\!|\?|\<\=|\<|\>\=|\>|\=\=|\&\&|\|\|)/; // operators in control flow macros + + return { + startState: function () { + return { + controlFlow: false, + macroParameters: false, + section: false + }; + }, + token: function (stream, state) { + var ch = stream.peek(); + if (ch == "#") { stream.skipToEnd(); return "comment"; } + + if (stream.sol()) { + if (stream.match(preamble)) { return "preamble"; } + if (stream.match(section)) { return "section"; } + } + + if (stream.match(/^\$\w+/)) { return "def"; } // Variables like '$RPM_BUILD_ROOT' + if (stream.match(/^\$\{\w+\}/)) { return "def"; } // Variables like '${RPM_BUILD_ROOT}' + + if (stream.match(control_flow_simple)) { return "keyword"; } + if (stream.match(control_flow_complex)) { + state.controlFlow = true; + return "keyword"; + } + if (state.controlFlow) { + if (stream.match(operators)) { return "operator"; } + if (stream.match(/^(\d+)/)) { return "number"; } + if (stream.eol()) { state.controlFlow = false; } + } + + if (stream.match(arch)) { return "number"; } + + // Macros like '%make_install' or '%attr(0775,root,root)' + if (stream.match(/^%[\w]+/)) { + if (stream.match(/^\(/)) { state.macroParameters = true; } + return "macro"; + } + if (state.macroParameters) { + if (stream.match(/^\d+/)) { return "number";} + if (stream.match(/^\)/)) { + state.macroParameters = false; + return "macro"; + } + } + if (stream.match(/^%\{\??[\w \-]+\}/)) { return "macro"; } // Macros like '%{defined fedora}' + + //TODO: Include bash script sub-parser (CodeMirror supports that) + stream.next(); + return null; + } + }; +}); + +CodeMirror.defineMIME("text/x-rpm-spec", "spec"); diff --git a/codemirror/mode/rst/index.html b/codemirror/mode/rst/index.html new file mode 100644 index 0000000..6e47720 --- /dev/null +++ b/codemirror/mode/rst/index.html @@ -0,0 +1,526 @@ + + + + + CodeMirror: reStructuredText mode + + + + + + + +

CodeMirror: reStructuredText mode

+ +
+ + +

The reStructuredText mode supports one configuration parameter:

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

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

MIME types defined: text/x-rst.

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

CodeMirror: Ruby mode

+
+ + +

MIME types defined: text/x-ruby.

+ +

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

+ + + diff --git a/codemirror/mode/ruby/ruby.js b/codemirror/mode/ruby/ruby.js new file mode 100644 index 0000000..d106a54 --- /dev/null +++ b/codemirror/mode/ruby/ruby.js @@ -0,0 +1,195 @@ +CodeMirror.defineMode("ruby", function(config) { + function wordObj(words) { + var o = {}; + for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true; + return o; + } + var keywords = wordObj([ + "alias", "and", "BEGIN", "begin", "break", "case", "class", "def", "defined?", "do", "else", + "elsif", "END", "end", "ensure", "false", "for", "if", "in", "module", "next", "not", "or", + "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless", + "until", "when", "while", "yield", "nil", "raise", "throw", "catch", "fail", "loop", "callcc", + "caller", "lambda", "proc", "public", "protected", "private", "require", "load", + "require_relative", "extend", "autoload" + ]); + var indentWords = wordObj(["def", "class", "case", "for", "while", "do", "module", "then", + "catch", "loop", "proc", "begin"]); + var dedentWords = wordObj(["end", "until"]); + var matching = {"[": "]", "{": "}", "(": ")"}; + var curPunc; + + function chain(newtok, stream, state) { + state.tokenize.push(newtok); + return newtok(stream, state); + } + + function tokenBase(stream, state) { + curPunc = null; + if (stream.sol() && stream.match("=begin") && stream.eol()) { + state.tokenize.push(readBlockComment); + return "comment"; + } + if (stream.eatSpace()) return null; + var ch = stream.next(), m; + if (ch == "`" || ch == "'" || ch == '"' || + (ch == "/" && !stream.eol() && stream.peek() != " ")) { + return chain(readQuoted(ch, "string", ch == '"' || ch == "`"), stream, state); + } else if (ch == "%") { + var style, embed = false; + if (stream.eat("s")) style = "atom"; + else if (stream.eat(/[WQ]/)) { style = "string"; embed = true; } + else if (stream.eat(/[wxqr]/)) style = "string"; + var delim = stream.eat(/[^\w\s]/); + if (!delim) return "operator"; + if (matching.propertyIsEnumerable(delim)) delim = matching[delim]; + return chain(readQuoted(delim, style, embed, true), stream, state); + } else if (ch == "#") { + stream.skipToEnd(); + return "comment"; + } else if (ch == "<" && (m = stream.match(/^<-?[\`\"\']?([a-zA-Z_?]\w*)[\`\"\']?(?:;|$)/))) { + return chain(readHereDoc(m[1]), stream, state); + } else if (ch == "0") { + if (stream.eat("x")) stream.eatWhile(/[\da-fA-F]/); + else if (stream.eat("b")) stream.eatWhile(/[01]/); + else stream.eatWhile(/[0-7]/); + return "number"; + } else if (/\d/.test(ch)) { + stream.match(/^[\d_]*(?:\.[\d_]+)?(?:[eE][+\-]?[\d_]+)?/); + return "number"; + } else if (ch == "?") { + while (stream.match(/^\\[CM]-/)) {} + if (stream.eat("\\")) stream.eatWhile(/\w/); + else stream.next(); + return "string"; + } else if (ch == ":") { + if (stream.eat("'")) return chain(readQuoted("'", "atom", false), stream, state); + if (stream.eat('"')) return chain(readQuoted('"', "atom", true), stream, state); + stream.eatWhile(/[\w\?]/); + return "atom"; + } else if (ch == "@") { + stream.eat("@"); + stream.eatWhile(/[\w\?]/); + return "variable-2"; + } else if (ch == "$") { + stream.next(); + stream.eatWhile(/[\w\?]/); + return "variable-3"; + } else if (/\w/.test(ch)) { + stream.eatWhile(/[\w\?]/); + if (stream.eat(":")) return "atom"; + return "ident"; + } else if (ch == "|" && (state.varList || state.lastTok == "{" || state.lastTok == "do")) { + curPunc = "|"; + return null; + } else if (/[\(\)\[\]{}\\;]/.test(ch)) { + curPunc = ch; + return null; + } else if (ch == "-" && stream.eat(">")) { + return "arrow"; + } else if (/[=+\-\/*:\.^%<>~|]/.test(ch)) { + stream.eatWhile(/[=+\-\/*:\.^%<>~|]/); + return "operator"; + } else { + return null; + } + } + + function tokenBaseUntilBrace() { + var depth = 1; + return function(stream, state) { + if (stream.peek() == "}") { + depth--; + if (depth == 0) { + state.tokenize.pop(); + return state.tokenize[state.tokenize.length-1](stream, state); + } + } else if (stream.peek() == "{") { + depth++; + } + return tokenBase(stream, state); + }; + } + function readQuoted(quote, style, embed, unescaped) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && (unescaped || !escaped)) { + state.tokenize.pop(); + break; + } + if (embed && ch == "#" && !escaped && stream.eat("{")) { + state.tokenize.push(tokenBaseUntilBrace(arguments.callee)); + break; + } + escaped = !escaped && ch == "\\"; + } + return style; + }; + } + function readHereDoc(phrase) { + return function(stream, state) { + if (stream.match(phrase)) state.tokenize.pop(); + else stream.skipToEnd(); + return "string"; + }; + } + function readBlockComment(stream, state) { + if (stream.sol() && stream.match("=end") && stream.eol()) + state.tokenize.pop(); + stream.skipToEnd(); + return "comment"; + } + + return { + startState: function() { + return {tokenize: [tokenBase], + indented: 0, + context: {type: "top", indented: -config.indentUnit}, + continuedLine: false, + lastTok: null, + varList: false}; + }, + + token: function(stream, state) { + if (stream.sol()) state.indented = stream.indentation(); + var style = state.tokenize[state.tokenize.length-1](stream, state), kwtype; + if (style == "ident") { + var word = stream.current(); + style = keywords.propertyIsEnumerable(stream.current()) ? "keyword" + : /^[A-Z]/.test(word) ? "tag" + : (state.lastTok == "def" || state.lastTok == "class" || state.varList) ? "def" + : "variable"; + if (indentWords.propertyIsEnumerable(word)) kwtype = "indent"; + else if (dedentWords.propertyIsEnumerable(word)) kwtype = "dedent"; + else if ((word == "if" || word == "unless") && stream.column() == stream.indentation()) + kwtype = "indent"; + } + if (curPunc || (style && style != "comment")) state.lastTok = word || curPunc || style; + if (curPunc == "|") state.varList = !state.varList; + + if (kwtype == "indent" || /[\(\[\{]/.test(curPunc)) + state.context = {prev: state.context, type: curPunc || style, indented: state.indented}; + else if ((kwtype == "dedent" || /[\)\]\}]/.test(curPunc)) && state.context.prev) + state.context = state.context.prev; + + if (stream.eol()) + state.continuedLine = (curPunc == "\\" || style == "operator"); + return style; + }, + + indent: function(state, textAfter) { + if (state.tokenize[state.tokenize.length-1] != tokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0); + var ct = state.context; + var closing = ct.type == matching[firstChar] || + ct.type == "keyword" && /^(?:end|until|else|elsif|when|rescue)\b/.test(textAfter); + return ct.indented + (closing ? 0 : config.indentUnit) + + (state.continuedLine ? config.indentUnit : 0); + }, + electricChars: "}de" // enD and rescuE + + }; +}); + +CodeMirror.defineMIME("text/x-ruby", "ruby"); + diff --git a/codemirror/mode/rust/index.html b/codemirror/mode/rust/index.html new file mode 100644 index 0000000..a6d47fe --- /dev/null +++ b/codemirror/mode/rust/index.html @@ -0,0 +1,48 @@ + + + + + CodeMirror: Rust mode + + + + + + + +

CodeMirror: Rust mode

+ +
+ + + +

MIME types defined: text/x-rustsrc.

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

CodeMirror: Scheme mode

+
+ + +

MIME types defined: text/x-scheme.

+ + + diff --git a/codemirror/mode/scheme/scheme.js b/codemirror/mode/scheme/scheme.js new file mode 100644 index 0000000..2ed0a24 --- /dev/null +++ b/codemirror/mode/scheme/scheme.js @@ -0,0 +1,230 @@ +/** + * Author: Koh Zi Han, based on implementation by Koh Zi Chun + */ +CodeMirror.defineMode("scheme", function () { + var BUILTIN = "builtin", COMMENT = "comment", STRING = "string", + ATOM = "atom", NUMBER = "number", BRACKET = "bracket"; + var INDENT_WORD_SKIP = 2; + + function makeKeywords(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + + var keywords = makeKeywords("λ case-lambda call/cc class define-class exit-handler field import inherit init-field interface let*-values let-values let/ec mixin opt-lambda override protect provide public rename require require-for-syntax syntax syntax-case syntax-error unit/sig unless when with-syntax and begin call-with-current-continuation call-with-input-file call-with-output-file case cond define define-syntax delay do dynamic-wind else for-each if lambda let let* let-syntax letrec letrec-syntax map or syntax-rules abs acos angle append apply asin assoc assq assv atan boolean? caar cadr call-with-input-file call-with-output-file call-with-values car cdddar cddddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char=? char>? char? close-input-port close-output-port complex? cons cos current-input-port current-output-port denominator display eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt #f floor force gcd imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lcm length list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file output-port? pair? peek-char port? positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string=? string>? string? substring symbol->string symbol? #t tan transcript-off transcript-on truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! with-input-from-file with-output-to-file write write-char zero?"); + var indentKeys = makeKeywords("define let letrec let* lambda"); + + function stateStack(indent, type, prev) { // represents a state stack object + this.indent = indent; + this.type = type; + this.prev = prev; + } + + function pushStack(state, indent, type) { + state.indentStack = new stateStack(indent, type, state.indentStack); + } + + function popStack(state) { + state.indentStack = state.indentStack.prev; + } + + var binaryMatcher = new RegExp(/^(?:[-+]i|[-+][01]+#*(?:\/[01]+#*)?i|[-+]?[01]+#*(?:\/[01]+#*)?@[-+]?[01]+#*(?:\/[01]+#*)?|[-+]?[01]+#*(?:\/[01]+#*)?[-+](?:[01]+#*(?:\/[01]+#*)?)?i|[-+]?[01]+#*(?:\/[01]+#*)?)(?=[()\s;"]|$)/i); + var octalMatcher = new RegExp(/^(?:[-+]i|[-+][0-7]+#*(?:\/[0-7]+#*)?i|[-+]?[0-7]+#*(?:\/[0-7]+#*)?@[-+]?[0-7]+#*(?:\/[0-7]+#*)?|[-+]?[0-7]+#*(?:\/[0-7]+#*)?[-+](?:[0-7]+#*(?:\/[0-7]+#*)?)?i|[-+]?[0-7]+#*(?:\/[0-7]+#*)?)(?=[()\s;"]|$)/i); + var hexMatcher = new RegExp(/^(?:[-+]i|[-+][\da-f]+#*(?:\/[\da-f]+#*)?i|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?@[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?[-+](?:[\da-f]+#*(?:\/[\da-f]+#*)?)?i|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?)(?=[()\s;"]|$)/i); + var decimalMatcher = new RegExp(/^(?:[-+]i|[-+](?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)i|[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)@[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)|[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)[-+](?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)?i|(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*))(?=[()\s;"]|$)/i); + + function isBinaryNumber (stream) { + return stream.match(binaryMatcher); + } + + function isOctalNumber (stream) { + return stream.match(octalMatcher); + } + + function isDecimalNumber (stream, backup) { + if (backup === true) { + stream.backUp(1); + } + return stream.match(decimalMatcher); + } + + function isHexNumber (stream) { + return stream.match(hexMatcher); + } + + return { + startState: function () { + return { + indentStack: null, + indentation: 0, + mode: false, + sExprComment: false + }; + }, + + token: function (stream, state) { + if (state.indentStack == null && stream.sol()) { + // update indentation, but only if indentStack is empty + state.indentation = stream.indentation(); + } + + // skip spaces + if (stream.eatSpace()) { + return null; + } + var returnType = null; + + switch(state.mode){ + case "string": // multi-line string parsing mode + var next, escaped = false; + while ((next = stream.next()) != null) { + if (next == "\"" && !escaped) { + + state.mode = false; + break; + } + escaped = !escaped && next == "\\"; + } + returnType = STRING; // continue on in scheme-string mode + break; + case "comment": // comment parsing mode + var next, maybeEnd = false; + while ((next = stream.next()) != null) { + if (next == "#" && maybeEnd) { + + state.mode = false; + break; + } + maybeEnd = (next == "|"); + } + returnType = COMMENT; + break; + case "s-expr-comment": // s-expr commenting mode + state.mode = false; + if(stream.peek() == "(" || stream.peek() == "["){ + // actually start scheme s-expr commenting mode + state.sExprComment = 0; + }else{ + // if not we just comment the entire of the next token + stream.eatWhile(/[^/s]/); // eat non spaces + returnType = COMMENT; + break; + } + default: // default parsing mode + var ch = stream.next(); + + if (ch == "\"") { + state.mode = "string"; + returnType = STRING; + + } else if (ch == "'") { + returnType = ATOM; + } else if (ch == '#') { + if (stream.eat("|")) { // Multi-line comment + state.mode = "comment"; // toggle to comment mode + returnType = COMMENT; + } else if (stream.eat(/[tf]/i)) { // #t/#f (atom) + returnType = ATOM; + } else if (stream.eat(';')) { // S-Expr comment + state.mode = "s-expr-comment"; + returnType = COMMENT; + } else { + var numTest = null, hasExactness = false, hasRadix = true; + if (stream.eat(/[ei]/i)) { + hasExactness = true; + } else { + stream.backUp(1); // must be radix specifier + } + if (stream.match(/^#b/i)) { + numTest = isBinaryNumber; + } else if (stream.match(/^#o/i)) { + numTest = isOctalNumber; + } else if (stream.match(/^#x/i)) { + numTest = isHexNumber; + } else if (stream.match(/^#d/i)) { + numTest = isDecimalNumber; + } else if (stream.match(/^[-+0-9.]/, false)) { + hasRadix = false; + numTest = isDecimalNumber; + // re-consume the intial # if all matches failed + } else if (!hasExactness) { + stream.eat('#'); + } + if (numTest != null) { + if (hasRadix && !hasExactness) { + // consume optional exactness after radix + stream.match(/^#[ei]/i); + } + if (numTest(stream)) + returnType = NUMBER; + } + } + } else if (/^[-+0-9.]/.test(ch) && isDecimalNumber(stream, true)) { // match non-prefixed number, must be decimal + returnType = NUMBER; + } else if (ch == ";") { // comment + stream.skipToEnd(); // rest of the line is a comment + returnType = COMMENT; + } else if (ch == "(" || ch == "[") { + var keyWord = ''; var indentTemp = stream.column(), letter; + /** + Either + (indent-word .. + (non-indent-word .. + (;something else, bracket, etc. + */ + + while ((letter = stream.eat(/[^\s\(\[\;\)\]]/)) != null) { + keyWord += letter; + } + + if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) { // indent-word + + pushStack(state, indentTemp + INDENT_WORD_SKIP, ch); + } else { // non-indent word + // we continue eating the spaces + stream.eatSpace(); + if (stream.eol() || stream.peek() == ";") { + // nothing significant after + // we restart indentation 1 space after + pushStack(state, indentTemp + 1, ch); + } else { + pushStack(state, indentTemp + stream.current().length, ch); // else we match + } + } + stream.backUp(stream.current().length - 1); // undo all the eating + + if(typeof state.sExprComment == "number") state.sExprComment++; + + returnType = BRACKET; + } else if (ch == ")" || ch == "]") { + returnType = BRACKET; + if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : "[")) { + popStack(state); + + if(typeof state.sExprComment == "number"){ + if(--state.sExprComment == 0){ + returnType = COMMENT; // final closing bracket + state.sExprComment = false; // turn off s-expr commenting mode + } + } + } + } else { + stream.eatWhile(/[\w\$_\-!$%&*+\.\/:<=>?@\^~]/); + + if (keywords && keywords.propertyIsEnumerable(stream.current())) { + returnType = BUILTIN; + } else returnType = "variable"; + } + } + return (typeof state.sExprComment == "number") ? COMMENT : returnType; + }, + + indent: function (state) { + if (state.indentStack == null) return state.indentation; + return state.indentStack.indent; + } + }; +}); + +CodeMirror.defineMIME("text/x-scheme", "scheme"); diff --git a/codemirror/mode/shell/index.html b/codemirror/mode/shell/index.html new file mode 100644 index 0000000..0827053 --- /dev/null +++ b/codemirror/mode/shell/index.html @@ -0,0 +1,51 @@ + + +CodeMirror: Shell mode + + + + + + + + + + +

CodeMirror: Shell mode

+ + + + + +

MIME types defined: text/x-sh.

diff --git a/codemirror/mode/shell/shell.js b/codemirror/mode/shell/shell.js new file mode 100644 index 0000000..9ce139b --- /dev/null +++ b/codemirror/mode/shell/shell.js @@ -0,0 +1,118 @@ +CodeMirror.defineMode('shell', function() { + + var words = {}; + function define(style, string) { + var split = string.split(' '); + for(var i = 0; i < split.length; i++) { + words[split[i]] = style; + } + }; + + // Atoms + define('atom', 'true false'); + + // Keywords + define('keyword', 'if then do else elif while until for in esac fi fin ' + + 'fil done exit set unset export function'); + + // Commands + define('builtin', 'ab awk bash beep cat cc cd chown chmod chroot clear cp ' + + 'curl cut diff echo find gawk gcc get git grep kill killall ln ls make ' + + 'mkdir openssl mv nc node npm ping ps restart rm rmdir sed service sh ' + + 'shopt shred source sort sleep ssh start stop su sudo tee telnet top ' + + 'touch vi vim wall wc wget who write yes zsh'); + + function tokenBase(stream, state) { + + var sol = stream.sol(); + var ch = stream.next(); + + if (ch === '\'' || ch === '"' || ch === '`') { + state.tokens.unshift(tokenString(ch)); + return tokenize(stream, state); + } + if (ch === '#') { + if (sol && stream.eat('!')) { + stream.skipToEnd(); + return 'meta'; // 'comment'? + } + stream.skipToEnd(); + return 'comment'; + } + if (ch === '$') { + state.tokens.unshift(tokenDollar); + return tokenize(stream, state); + } + if (ch === '+' || ch === '=') { + return 'operator'; + } + if (ch === '-') { + stream.eat('-'); + stream.eatWhile(/\w/); + return 'attribute'; + } + if (/\d/.test(ch)) { + stream.eatWhile(/\d/); + if(!/\w/.test(stream.peek())) { + return 'number'; + } + } + stream.eatWhile(/\w/); + var cur = stream.current(); + if (stream.peek() === '=' && /\w+/.test(cur)) return 'def'; + return words.hasOwnProperty(cur) ? words[cur] : null; + } + + function tokenString(quote) { + return function(stream, state) { + var next, end = false, escaped = false; + while ((next = stream.next()) != null) { + if (next === quote && !escaped) { + end = true; + break; + } + if (next === '$' && !escaped && quote !== '\'') { + escaped = true; + stream.backUp(1); + state.tokens.unshift(tokenDollar); + break; + } + escaped = !escaped && next === '\\'; + } + if (end || !escaped) { + state.tokens.shift(); + } + return (quote === '`' || quote === ')' ? 'quote' : 'string'); + }; + }; + + var tokenDollar = function(stream, state) { + if (state.tokens.length > 1) stream.eat('$'); + var ch = stream.next(), hungry = /\w/; + if (ch === '{') hungry = /[^}]/; + if (ch === '(') { + state.tokens[0] = tokenString(')'); + return tokenize(stream, state); + } + if (!/\d/.test(ch)) { + stream.eatWhile(hungry); + stream.eat('}'); + } + state.tokens.shift(); + return 'def'; + }; + + function tokenize(stream, state) { + return (state.tokens[0] || tokenBase) (stream, state); + }; + + return { + startState: function() {return {tokens:[]};}, + token: function(stream, state) { + if (stream.eatSpace()) return null; + return tokenize(stream, state); + } + }; +}); + +CodeMirror.defineMIME('text/x-sh', 'shell'); diff --git a/codemirror/mode/sieve/LICENSE b/codemirror/mode/sieve/LICENSE new file mode 100644 index 0000000..24e4c94 --- /dev/null +++ b/codemirror/mode/sieve/LICENSE @@ -0,0 +1,23 @@ +Copyright (C) 2012 Thomas Schmid + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Please note that some subdirectories of the CodeMirror distribution +include their own LICENSE files, and are released under different +licences. diff --git a/codemirror/mode/sieve/index.html b/codemirror/mode/sieve/index.html new file mode 100644 index 0000000..8b54981 --- /dev/null +++ b/codemirror/mode/sieve/index.html @@ -0,0 +1,81 @@ + + + + + CodeMirror: Sieve (RFC5228) mode + + + + + + + +

CodeMirror: Sieve (RFC5228) mode

+
+ + +

MIME types defined: application/sieve.

+ + + diff --git a/codemirror/mode/sieve/sieve.js b/codemirror/mode/sieve/sieve.js new file mode 100644 index 0000000..291c9c8 --- /dev/null +++ b/codemirror/mode/sieve/sieve.js @@ -0,0 +1,156 @@ +/* + * 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++; + return null; + } + + if (ch === "}") + { + state._indent--; + 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"; + } + + 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: 0}; + }, + + token: function(stream, state) { + if (stream.eatSpace()) + return null; + + return (state.tokenize || tokenBase)(stream, state);; + }, + + indent: function(state, _textAfter) { + return state.baseIndent + state._indent * indentUnit; + }, + + electricChars: "}" + }; +}); + +CodeMirror.defineMIME("application/sieve", "sieve"); diff --git a/codemirror/mode/smalltalk/index.html b/codemirror/mode/smalltalk/index.html new file mode 100644 index 0000000..690b560 --- /dev/null +++ b/codemirror/mode/smalltalk/index.html @@ -0,0 +1,57 @@ + + + + + CodeMirror: Smalltalk mode + + + + + + + + +

CodeMirror: Smalltalk mode

+ +
+ + + +

Simple Smalltalk mode.

+ +

MIME types defined: text/x-stsrc.

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

CodeMirror: Smarty mode

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

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

+ +

MIME types defined: text/x-smarty

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

CodeMirror: SPARQL mode

+
+ + +

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

+ + + diff --git a/codemirror/mode/sparql/sparql.js b/codemirror/mode/sparql/sparql.js new file mode 100644 index 0000000..0b367b2 --- /dev/null +++ b/codemirror/mode/sparql/sparql.js @@ -0,0 +1,143 @@ +CodeMirror.defineMode("sparql", function(config) { + var indentUnit = config.indentUnit; + var curPunc; + + function wordRegexp(words) { + return new RegExp("^(?:" + words.join("|") + ")$", "i"); + } + var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri", + "isblank", "isliteral", "union", "a"]); + var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe", + "ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional", + "graph", "by", "asc", "desc"]); + var operatorChars = /[*+\-<>=&|]/; + + function tokenBase(stream, state) { + var ch = stream.next(); + curPunc = null; + if (ch == "$" || ch == "?") { + stream.match(/^[\w\d]*/); + return "variable-2"; + } + else if (ch == "<" && !stream.match(/^[\s\u00a0=]/, false)) { + stream.match(/^[^\s\u00a0>]*>?/); + return "atom"; + } + else if (ch == "\"" || ch == "'") { + state.tokenize = tokenLiteral(ch); + return state.tokenize(stream, state); + } + else if (/[{}\(\),\.;\[\]]/.test(ch)) { + curPunc = ch; + return null; + } + else if (ch == "#") { + stream.skipToEnd(); + return "comment"; + } + else if (operatorChars.test(ch)) { + stream.eatWhile(operatorChars); + return null; + } + else if (ch == ":") { + stream.eatWhile(/[\w\d\._\-]/); + return "atom"; + } + else { + stream.eatWhile(/[_\w\d]/); + if (stream.eat(":")) { + stream.eatWhile(/[\w\d_\-]/); + return "atom"; + } + var word = stream.current(); + if (ops.test(word)) + return null; + else if (keywords.test(word)) + return "keyword"; + else + return "variable"; + } + } + + function tokenLiteral(quote) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) { + state.tokenize = tokenBase; + break; + } + escaped = !escaped && ch == "\\"; + } + return "string"; + }; + } + + function pushContext(state, type, col) { + state.context = {prev: state.context, indent: state.indent, col: col, type: type}; + } + function popContext(state) { + state.indent = state.context.indent; + state.context = state.context.prev; + } + + return { + startState: function() { + return {tokenize: tokenBase, + context: null, + indent: 0, + col: 0}; + }, + + token: function(stream, state) { + if (stream.sol()) { + if (state.context && state.context.align == null) state.context.align = false; + state.indent = stream.indentation(); + } + if (stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + + if (style != "comment" && state.context && state.context.align == null && state.context.type != "pattern") { + state.context.align = true; + } + + if (curPunc == "(") pushContext(state, ")", stream.column()); + else if (curPunc == "[") pushContext(state, "]", stream.column()); + else if (curPunc == "{") pushContext(state, "}", stream.column()); + else if (/[\]\}\)]/.test(curPunc)) { + while (state.context && state.context.type == "pattern") popContext(state); + if (state.context && curPunc == state.context.type) popContext(state); + } + else if (curPunc == "." && state.context && state.context.type == "pattern") popContext(state); + else if (/atom|string|variable/.test(style) && state.context) { + if (/[\}\]]/.test(state.context.type)) + pushContext(state, "pattern", stream.column()); + else if (state.context.type == "pattern" && !state.context.align) { + state.context.align = true; + state.context.col = stream.column(); + } + } + + return style; + }, + + indent: function(state, textAfter) { + var firstChar = textAfter && textAfter.charAt(0); + var context = state.context; + if (/[\]\}]/.test(firstChar)) + while (context && context.type == "pattern") context = context.prev; + + var closing = context && firstChar == context.type; + if (!context) + return 0; + else if (context.type == "pattern") + return context.col; + else if (context.align) + return context.col + (closing ? 0 : 1); + else + return context.indent + (closing ? 0 : indentUnit); + } + }; +}); + +CodeMirror.defineMIME("application/x-sparql-query", "sparql"); diff --git a/codemirror/mode/sql/index.html b/codemirror/mode/sql/index.html new file mode 100644 index 0000000..e2cdf77 --- /dev/null +++ b/codemirror/mode/sql/index.html @@ -0,0 +1,60 @@ + + + + + SQL Mode for CodeMirror + + + + + + + + +

SQL Mode for CodeMirror

+
+ +
+

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

+ + diff --git a/codemirror/mode/sql/sql.js b/codemirror/mode/sql/sql.js new file mode 100644 index 0000000..f2fd001 --- /dev/null +++ b/codemirror/mode/sql/sql.js @@ -0,0 +1,232 @@ +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 = /^[*+\-%<>!=&|~^]/, + hooks = parserConfig.hooks || {}; + + function tokenBase(stream, state) { + var ch = stream.next(); + + if (hooks[ch]) { + var result = hooks[ch](stream, state); + if (result !== false) return result; + } + + if ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/)) + || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/)) { + // hex + return "number"; + } else if (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/)) + || (ch == "0" && stream.match(/^b[01]+/))) { + // bitstring + return "number"; + } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) { + // numbers + stream.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/); + return "number"; + } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) { + // placeholders + return "variable-3"; + } else if (ch == '"' || ch == "'") { + state.tokenize = tokenLiteral(ch); + return state.tokenize(stream, state); + } else if (/^[\(\),\.;\[\]]/.test(ch)) { + return null; + } else if (ch == "#" || (ch == "-" && stream.eat("-") && stream.eat(" "))) { + stream.skipToEnd(); + return "comment"; + } else if (ch == "/" && stream.eat("*")) { + state.tokenize = tokenComment; + return state.tokenize(stream, state); + } else if (operatorChars.test(ch)) { + stream.eatWhile(operatorChars); + return false; + } else { + stream.eatWhile(/^[_\w\d]/); + var word = stream.current().toLowerCase(); + 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 "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 tokenComment(stream, state) { + while (true) { + if (stream.skipTo("*")) { + stream.next(); + if (stream.eat("/")) { + state.tokenize = tokenBase; + break; + } + } else { + stream.skipToEnd(); + break; + } + } + return "comment"; + } + + function pushContext(stream, state, type) { + state.context = { + prev: state.context, + indent: stream.indentation(), + col: stream.column(), + type: type + }; + } + + function popContext(state) { + state.indent = state.context.indent; + state.context = state.context.prev; + } + + return { + startState: function() { + return {tokenize: tokenBase, context: null}; + }, + + token: function(stream, state) { + if (stream.sol()) { + if (state.context && state.context.align == null) + state.context.align = false; + } + if (stream.eatSpace()) return null; + + var style = state.tokenize(stream, state); + if (style == "comment") return style; + + if (state.context && state.context.align == null) + state.context.align = true; + + var tok = stream.current(); + if (tok == "(") + pushContext(stream, state, ")"); + else if (tok == "[") + pushContext(stream, state, "]"); + else if (state.context && state.context.type == tok) + popContext(state); + return style; + }, + + indent: function(state, textAfter) { + var cx = state.context; + if (!cx) return CodeMirror.Pass; + if (cx.align) return cx.col + (textAfter.charAt(0) == cx.type ? 0 : 1); + else return cx.indent + config.indentUnit; + } + }; +}); + +(function() { + "use strict"; + + function hookIdentifier(stream) { + var escaped = false, ch; + + while ((ch = stream.next()) != null) { + if (ch == "`" && !escaped) return "variable-2"; + escaped = !escaped && ch == "`"; + } + return false; + } + + // variable token + function hookVar(stream) { + // variables + // @@ and prefix + if (stream.eat("@")) { + stream.match(/^session\./); + stream.match(/^local\./); + stream.match(/^global\./); + } + + if (stream.eat("'")) { + stream.match(/^.*'/); + return "variable-2"; + } else if (stream.eat('"')) { + stream.match(/^.*"/); + return "variable-2"; + } else if (stream.eat("`")) { + stream.match(/^.*`/); + return "variable-2"; + } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) { + return "variable-2"; + } + return false; + }; + + // short client keyword token + function hookClient(stream) { + // \g, etc + return stream.match(/^[a-zA-Z]\b/) ? "variable-2" : false; + } + + var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from having in insert into is join like not on or order select set table union update values where "; + + function set(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + + CodeMirror.defineMIME("text/x-sql", { + name: "sql", + keywords: set(sqlKeywords + "begin"), + builtin: set("bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric"), + atoms: set("false true null unknown") + }); + + CodeMirror.defineMIME("text/x-mysql", { + name: "sql", + client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"), + keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general global grant grants group groupby_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"), + builtin: set("bool boolean bit blob 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 date datetime year unsigned signed decimal numeric"), + atoms: set("false true null unknown"), + hooks: { + "@": hookVar, + "`": hookIdentifier, + "\\": hookClient + } + }); + + CodeMirror.defineMIME("text/x-mariadb", { + name: "sql", + client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"), + keywords: set(sqlKeywords + "accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated global grant grants group groupby_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"), + builtin: set("bool boolean bit blob 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 date datetime year unsigned signed decimal numeric"), + atoms: set("false true null unknown"), + hooks: { + "@": hookVar, + "`": hookIdentifier, + "\\": hookClient + } + }); + + // this is based on Peter Raganitsch's 'plsql' mode + CodeMirror.defineMIME("text/x-plsql", { + name: "sql", + client: set("appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap"), + keywords: set("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work"), + functions: set("abs acos add_months ascii asin atan atan2 average bfilename ceil chartorowid chr concat convert cos cosh count decode deref dual dump dup_val_on_index empty error exp false floor found glb greatest hextoraw initcap instr instrb isopen last_day least lenght lenghtb ln lower lpad ltrim lub make_ref max min mod months_between new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null nvl others power rawtohex reftohex round rowcount rowidtochar rpad rtrim sign sin sinh soundex sqlcode sqlerrm sqrt stddev substr substrb sum sysdate tan tanh to_char to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid upper user userenv variance vsize"), + builtin: set("bfile blob character clob dec float int integer mlslabel natural naturaln nchar nclob number numeric nvarchar2 real rowtype signtype smallint string varchar varchar2") + }); +}()); diff --git a/codemirror/mode/stex/index.html b/codemirror/mode/stex/index.html new file mode 100644 index 0000000..2dafe69 --- /dev/null +++ b/codemirror/mode/stex/index.html @@ -0,0 +1,98 @@ + + + + + CodeMirror: sTeX mode + + + + + + + +

CodeMirror: sTeX mode

+
+ + +

MIME types defined: text/x-stex.

+ +

Parsing/Highlighting Tests: normal, verbose.

+ + + diff --git a/codemirror/mode/stex/stex.js b/codemirror/mode/stex/stex.js new file mode 100644 index 0000000..42ed82c --- /dev/null +++ b/codemirror/mode/stex/stex.js @@ -0,0 +1,175 @@ +/* + * Author: Constantin Jucovschi (c.jucovschi@jacobs-university.de) + * Licence: MIT + */ + +CodeMirror.defineMode("stex", function() +{ + function pushCommand(state, command) { + state.cmdState.push(command); + } + + function peekCommand(state) { + if (state.cmdState.length>0) + return state.cmdState[state.cmdState.length-1]; + else + return null; + } + + function popCommand(state) { + if (state.cmdState.length>0) { + var plug = state.cmdState.pop(); + plug.closeBracket(); + } + } + + function applyMostPowerful(state) { + var context = state.cmdState; + for (var i = context.length - 1; i >= 0; i--) { + var plug = context[i]; + if (plug.name=="DEFAULT") + continue; + return plug.styleIdentifier(); + } + return null; + } + + function addPluginPattern(pluginName, cmdStyle, brackets, styles) { + return function () { + this.name=pluginName; + this.bracketNo = 0; + this.style=cmdStyle; + this.styles = styles; + this.brackets = brackets; + + this.styleIdentifier = function() { + if (this.bracketNo<=this.styles.length) + return this.styles[this.bracketNo-1]; + else + return null; + }; + this.openBracket = function() { + this.bracketNo++; + return "bracket"; + }; + this.closeBracket = function() {}; + }; + } + + var plugins = new Array(); + + plugins["importmodule"] = addPluginPattern("importmodule", "tag", "{[", ["string", "builtin"]); + plugins["documentclass"] = addPluginPattern("documentclass", "tag", "{[", ["", "atom"]); + plugins["usepackage"] = addPluginPattern("documentclass", "tag", "[", ["atom"]); + plugins["begin"] = addPluginPattern("documentclass", "tag", "[", ["atom"]); + plugins["end"] = addPluginPattern("documentclass", "tag", "[", ["atom"]); + + plugins["DEFAULT"] = function () { + this.name="DEFAULT"; + this.style="tag"; + + this.styleIdentifier = this.openBracket = this.closeBracket = function() {}; + }; + + function setState(state, f) { + state.f = f; + } + + function normal(source, state) { + if (source.match(/^\\[a-zA-Z@]+/)) { + var cmdName = source.current(); + cmdName = cmdName.substr(1, cmdName.length-1); + var plug; + if (plugins.hasOwnProperty(cmdName)) { + plug = plugins[cmdName]; + } else { + plug = plugins["DEFAULT"]; + } + plug = new plug(); + pushCommand(state, plug); + setState(state, beginParams); + return plug.style; + } + + // escape characters + if (source.match(/^\\[$&%#{}_]/)) { + return "tag"; + } + + // white space control characters + if (source.match(/^\\[,;!\/]/)) { + return "tag"; + } + + var ch = source.next(); + if (ch == "%") { + // special case: % at end of its own line; stay in same state + if (!source.eol()) { + setState(state, inCComment); + } + return "comment"; + } + else if (ch=='}' || ch==']') { + plug = peekCommand(state); + if (plug) { + plug.closeBracket(ch); + setState(state, beginParams); + } else + return "error"; + return "bracket"; + } else if (ch=='{' || ch=='[') { + plug = plugins["DEFAULT"]; + plug = new plug(); + pushCommand(state, plug); + return "bracket"; + } + else if (/\d/.test(ch)) { + source.eatWhile(/[\w.%]/); + return "atom"; + } + else { + source.eatWhile(/[\w-_]/); + return applyMostPowerful(state); + } + } + + function inCComment(source, state) { + source.skipToEnd(); + setState(state, normal); + return "comment"; + } + + function beginParams(source, state) { + var ch = source.peek(); + if (ch == '{' || ch == '[') { + var lastPlug = peekCommand(state); + lastPlug.openBracket(ch); + source.eat(ch); + setState(state, normal); + return "bracket"; + } + if (/[ \t\r]/.test(ch)) { + source.eat(ch); + return null; + } + setState(state, normal); + lastPlug = peekCommand(state); + if (lastPlug) { + popCommand(state); + } + return normal(source, state); + } + + return { + startState: function() { return { f:normal, cmdState:[] }; }, + copyState: function(s) { return { f: s.f, cmdState: s.cmdState.slice(0, s.cmdState.length) }; }, + + token: function(stream, state) { + var t = state.f(stream, state); + return t; + } + }; +}); + +CodeMirror.defineMIME("text/x-stex", "stex"); +CodeMirror.defineMIME("text/x-latex", "stex"); diff --git a/codemirror/mode/stex/test.js b/codemirror/mode/stex/test.js new file mode 100644 index 0000000..c5a34f3 --- /dev/null +++ b/codemirror/mode/stex/test.js @@ -0,0 +1,343 @@ +var MT = ModeTest; +MT.modeName = 'stex'; +MT.modeOptions = {}; + +MT.testMode( + 'word', + 'foo', + [ + null, 'foo' + ] +); + +MT.testMode( + 'twoWords', + 'foo bar', + [ + null, 'foo bar' + ] +); + +MT.testMode( + 'beginEndDocument', + '\\begin{document}\n\\end{document}', + [ + 'tag', '\\begin', + 'bracket', '{', + 'atom', 'document', + 'bracket', '}', + 'tag', '\\end', + 'bracket', '{', + 'atom', 'document', + 'bracket', '}' + ] +); + +MT.testMode( + 'beginEndEquation', + '\\begin{equation}\n E=mc^2\n\\end{equation}', + [ + 'tag', '\\begin', + 'bracket', '{', + 'atom', 'equation', + 'bracket', '}', + null, ' E=mc^2', + 'tag', '\\end', + 'bracket', '{', + 'atom', 'equation', + 'bracket', '}' + ] +); + +MT.testMode( + 'beginModule', + '\\begin{module}[]', + [ + 'tag', '\\begin', + 'bracket', '{', + 'atom', 'module', + 'bracket', '}[]' + ] +); + +MT.testMode( + 'beginModuleId', + '\\begin{module}[id=bbt-size]', + [ + 'tag', '\\begin', + 'bracket', '{', + 'atom', 'module', + 'bracket', '}[', + null, 'id=bbt-size', + 'bracket', ']' + ] +); + +MT.testMode( + 'importModule', + '\\importmodule[b-b-t]{b-b-t}', + [ + 'tag', '\\importmodule', + 'bracket', '[', + 'string', 'b-b-t', + 'bracket', ']{', + 'builtin', 'b-b-t', + 'bracket', '}' + ] +); + +MT.testMode( + 'importModulePath', + '\\importmodule[\\KWARCslides{dmath/en/cardinality}]{card}', + [ + 'tag', '\\importmodule', + 'bracket', '[', + 'tag', '\\KWARCslides', + 'bracket', '{', + 'string', 'dmath/en/cardinality', + 'bracket', '}]{', + 'builtin', 'card', + 'bracket', '}' + ] +); + +MT.testMode( + 'psForPDF', + '\\PSforPDF[1]{#1}', // could treat #1 specially + [ + 'tag', '\\PSforPDF', + 'bracket', '[', + 'atom', '1', + 'bracket', ']{', + null, '#1', + 'bracket', '}' + ] +); + +MT.testMode( + 'comment', + '% foo', + [ + 'comment', '% foo' + ] +); + +MT.testMode( + 'tagComment', + '\\item% bar', + [ + 'tag', '\\item', + 'comment', '% bar' + ] +); + +MT.testMode( + 'commentTag', + ' % \\item', + [ + null, ' ', + 'comment', '% \\item' + ] +); + +MT.testMode( + 'commentLineBreak', + '%\nfoo', + [ + 'comment', '%', + null, 'foo' + ] +); + +MT.testMode( + 'tagErrorCurly', + '\\begin}{', + [ + 'tag', '\\begin', + 'error', '}', + 'bracket', '{' + ] +); + +MT.testMode( + 'tagErrorSquare', + '\\item]{', + [ + 'tag', '\\item', + 'error', ']', + 'bracket', '{' + ] +); + +MT.testMode( + 'commentCurly', + '% }', + [ + 'comment', '% }' + ] +); + +MT.testMode( + 'tagHash', + 'the \\# key', + [ + null, 'the ', + 'tag', '\\#', + null, ' key' + ] +); + +MT.testMode( + 'tagNumber', + 'a \\$5 stetson', + [ + null, 'a ', + 'tag', '\\$', + 'atom', 5, + null, ' stetson' + ] +); + +MT.testMode( + 'tagPercent', + '100\\% beef', + [ + 'atom', '100', + 'tag', '\\%', + null, ' beef' + ] +); + +MT.testMode( + 'tagAmpersand', + 'L \\& N', + [ + null, 'L ', + 'tag', '\\&', + null, ' N' + ] +); + +MT.testMode( + 'tagUnderscore', + 'foo\\_bar', + [ + null, 'foo', + 'tag', '\\_', + null, 'bar' + ] +); + +MT.testMode( + 'tagBracketOpen', + '\\emph{\\{}', + [ + 'tag', '\\emph', + 'bracket', '{', + 'tag', '\\{', + 'bracket', '}' + ] +); + +MT.testMode( + 'tagBracketClose', + '\\emph{\\}}', + [ + 'tag', '\\emph', + 'bracket', '{', + 'tag', '\\}', + 'bracket', '}' + ] +); + +MT.testMode( + 'tagLetterNumber', + 'section \\S1', + [ + null, 'section ', + 'tag', '\\S', + 'atom', '1' + ] +); + +MT.testMode( + 'textTagNumber', + 'para \\P2', + [ + null, 'para ', + 'tag', '\\P', + 'atom', '2' + ] +); + +MT.testMode( + 'thinspace', + 'x\\,y', // thinspace + [ + null, 'x', + 'tag', '\\,', + null, 'y' + ] +); + +MT.testMode( + 'thickspace', + 'x\\;y', // thickspace + [ + null, 'x', + 'tag', '\\;', + null, 'y' + ] +); + +MT.testMode( + 'negativeThinspace', + 'x\\!y', // negative thinspace + [ + null, 'x', + 'tag', '\\!', + null, 'y' + ] +); + +MT.testMode( + 'periodNotSentence', + 'J.\\ L.\\ is', // period not ending a sentence + [ + null, 'J.\\ L.\\ is' + ] +); // maybe could be better + +MT.testMode( + 'periodSentence', + 'X\\@. The', // period ending a sentence + [ + null, 'X', + 'tag', '\\@', + null, '. The' + ] +); + +MT.testMode( + 'italicCorrection', + '{\\em If\\/} I', // italic correction + [ + 'bracket', '{', + 'tag', '\\em', + null, ' If', + 'tag', '\\/', + 'bracket', '}', + null, ' I' + ] +); + +MT.testMode( + 'tagBracket', + '\\newcommand{\\pop}', + [ + 'tag', '\\newcommand', + 'bracket', '{', + 'tag', '\\pop', + 'bracket', '}' + ] +); \ No newline at end of file diff --git a/codemirror/mode/tiddlywiki/index.html b/codemirror/mode/tiddlywiki/index.html new file mode 100644 index 0000000..89ae858 --- /dev/null +++ b/codemirror/mode/tiddlywiki/index.html @@ -0,0 +1,142 @@ + + + + + CodeMirror: TiddlyWiki mode + + + + + + + + + +

CodeMirror: TiddlyWiki mode

+ +
+ + + +

TiddlyWiki mode supports a single configuration.

+ +

MIME types defined: text/x-tiddlywiki.

+ + diff --git a/codemirror/mode/tiddlywiki/tiddlywiki.css b/codemirror/mode/tiddlywiki/tiddlywiki.css new file mode 100644 index 0000000..9a69b63 --- /dev/null +++ b/codemirror/mode/tiddlywiki/tiddlywiki.css @@ -0,0 +1,14 @@ +span.cm-underlined { + text-decoration: underline; +} +span.cm-strikethrough { + text-decoration: line-through; +} +span.cm-brace { + color: #170; + font-weight: bold; +} +span.cm-table { + color: blue; + font-weight: bold; +} diff --git a/codemirror/mode/tiddlywiki/tiddlywiki.js b/codemirror/mode/tiddlywiki/tiddlywiki.js new file mode 100644 index 0000000..0d506ee --- /dev/null +++ b/codemirror/mode/tiddlywiki/tiddlywiki.js @@ -0,0 +1,353 @@ +/*** +|''Name''|tiddlywiki.js| +|''Description''|Enables TiddlyWikiy syntax highlighting using CodeMirror| +|''Author''|PMario| +|''Version''|0.1.7| +|''Status''|''stable''| +|''Source''|[[GitHub|https://github.com/pmario/CodeMirror2/blob/tw-syntax/mode/tiddlywiki]]| +|''Documentation''|http://codemirror.tiddlyspace.com/| +|''License''|[[MIT License|http://www.opensource.org/licenses/mit-license.php]]| +|''CoreVersion''|2.5.0| +|''Requires''|codemirror.js| +|''Keywords''|syntax highlighting color code mirror codemirror| +! Info +CoreVersion parameter is needed for TiddlyWiki only! +***/ +//{{{ +CodeMirror.defineMode("tiddlywiki", function () { + // Tokenizer + var textwords = {}; + + var keywords = function () { + function kw(type) { + return { type: type, style: "macro"}; + } + return { + "allTags": kw('allTags'), "closeAll": kw('closeAll'), "list": kw('list'), + "newJournal": kw('newJournal'), "newTiddler": kw('newTiddler'), + "permaview": kw('permaview'), "saveChanges": kw('saveChanges'), + "search": kw('search'), "slider": kw('slider'), "tabs": kw('tabs'), + "tag": kw('tag'), "tagging": kw('tagging'), "tags": kw('tags'), + "tiddler": kw('tiddler'), "timeline": kw('timeline'), + "today": kw('today'), "version": kw('version'), "option": kw('option'), + + "with": kw('with'), + "filter": kw('filter') + }; + }(); + + var isSpaceName = /[\w_\-]/i, + reHR = /^\-\-\-\-+$/, //
+ reWikiCommentStart = /^\/\*\*\*$/, // /*** + reWikiCommentStop = /^\*\*\*\/$/, // ***/ + reBlockQuote = /^<<<$/, + + reJsCodeStart = /^\/\/\{\{\{$/, // //{{{ js block start + reJsCodeStop = /^\/\/\}\}\}$/, // //}}} js stop + reXmlCodeStart = /^$/, // xml block start + reXmlCodeStop = /^$/, // xml stop + + reCodeBlockStart = /^\{\{\{$/, // {{{ TW text div block start + reCodeBlockStop = /^\}\}\}$/, // }}} TW text stop + + reUntilCodeStop = /.*?\}\}\}/; + + function chain(stream, state, f) { + state.tokenize = f; + return f(stream, state); + } + + // Used as scratch variables to communicate multiple values without + // consing up tons of objects. + var type, content; + + function ret(tp, style, cont) { + type = tp; + content = cont; + return style; + } + + function jsTokenBase(stream, state) { + var sol = stream.sol(), ch; + + state.block = false; // indicates the start of a code block. + + ch = stream.peek(); // don't eat, to make matching simpler + + // check start of blocks + if (sol && /[<\/\*{}\-]/.test(ch)) { + if (stream.match(reCodeBlockStart)) { + state.block = true; + return chain(stream, state, twTokenCode); + } + if (stream.match(reBlockQuote)) { + return ret('quote', 'quote'); + } + if (stream.match(reWikiCommentStart) || stream.match(reWikiCommentStop)) { + return ret('code', 'comment'); + } + if (stream.match(reJsCodeStart) || stream.match(reJsCodeStop) || stream.match(reXmlCodeStart) || stream.match(reXmlCodeStop)) { + return ret('code', 'comment'); + } + if (stream.match(reHR)) { + return ret('hr', 'hr'); + } + } // sol + ch = stream.next(); + + if (sol && /[\/\*!#;:>|]/.test(ch)) { + if (ch == "!") { // tw header + stream.skipToEnd(); + return ret("header", "header"); + } + if (ch == "*") { // tw list + stream.eatWhile('*'); + return ret("list", "comment"); + } + if (ch == "#") { // tw numbered list + stream.eatWhile('#'); + return ret("list", "comment"); + } + if (ch == ";") { // definition list, term + stream.eatWhile(';'); + return ret("list", "comment"); + } + if (ch == ":") { // definition list, description + stream.eatWhile(':'); + return ret("list", "comment"); + } + if (ch == ">") { // single line quote + stream.eatWhile(">"); + return ret("quote", "quote"); + } + if (ch == '|') { + return ret('table', 'header'); + } + } + + if (ch == '{' && stream.match(/\{\{/)) { + return chain(stream, state, twTokenCode); + } + + // rudimentary html:// file:// link matching. TW knows much more ... + if (/[hf]/i.test(ch)) { + if (/[ti]/i.test(stream.peek()) && stream.match(/\b(ttps?|tp|ile):\/\/[\-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i)) { + return ret("link", "link"); + } + } + // just a little string indicator, don't want to have the whole string covered + if (ch == '"') { + return ret('string', 'string'); + } + if (ch == '~') { // _no_ CamelCase indicator should be bold + return ret('text', 'brace'); + } + if (/[\[\]]/.test(ch)) { // check for [[..]] + if (stream.peek() == ch) { + stream.next(); + return ret('brace', 'brace'); + } + } + if (ch == "@") { // check for space link. TODO fix @@...@@ highlighting + stream.eatWhile(isSpaceName); + return ret("link", "link"); + } + if (/\d/.test(ch)) { // numbers + stream.eatWhile(/\d/); + return ret("number", "number"); + } + if (ch == "/") { // tw invisible comment + if (stream.eat("%")) { + return chain(stream, state, twTokenComment); + } + else if (stream.eat("/")) { // + return chain(stream, state, twTokenEm); + } + } + if (ch == "_") { // tw underline + if (stream.eat("_")) { + return chain(stream, state, twTokenUnderline); + } + } + // strikethrough and mdash handling + if (ch == "-") { + if (stream.eat("-")) { + // if strikethrough looks ugly, change CSS. + if (stream.peek() != ' ') + return chain(stream, state, twTokenStrike); + // mdash + if (stream.peek() == ' ') + return ret('text', 'brace'); + } + } + if (ch == "'") { // tw bold + if (stream.eat("'")) { + return chain(stream, state, twTokenStrong); + } + } + if (ch == "<") { // tw macro + if (stream.eat("<")) { + return chain(stream, state, twTokenMacro); + } + } + else { + return ret(ch); + } + + // core macro handling + stream.eatWhile(/[\w\$_]/); + var word = stream.current(), + known = textwords.propertyIsEnumerable(word) && textwords[word]; + + return known ? ret(known.type, known.style, word) : ret("text", null, word); + + } // jsTokenBase() + + // tw invisible comment + function twTokenComment(stream, state) { + var maybeEnd = false, + ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = jsTokenBase; + break; + } + maybeEnd = (ch == "%"); + } + return ret("comment", "comment"); + } + + // tw strong / bold + function twTokenStrong(stream, state) { + var maybeEnd = false, + ch; + while (ch = stream.next()) { + if (ch == "'" && maybeEnd) { + state.tokenize = jsTokenBase; + break; + } + maybeEnd = (ch == "'"); + } + return ret("text", "strong"); + } + + // tw code + function twTokenCode(stream, state) { + var ch, sb = state.block; + + if (sb && stream.current()) { + return ret("code", "comment"); + } + + if (!sb && stream.match(reUntilCodeStop)) { + state.tokenize = jsTokenBase; + return ret("code", "comment"); + } + + if (sb && stream.sol() && stream.match(reCodeBlockStop)) { + state.tokenize = jsTokenBase; + return ret("code", "comment"); + } + + ch = stream.next(); + return (sb) ? ret("code", "comment") : ret("code", "comment"); + } + + // tw em / italic + function twTokenEm(stream, state) { + var maybeEnd = false, + ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = jsTokenBase; + break; + } + maybeEnd = (ch == "/"); + } + return ret("text", "em"); + } + + // tw underlined text + function twTokenUnderline(stream, state) { + var maybeEnd = false, + ch; + while (ch = stream.next()) { + if (ch == "_" && maybeEnd) { + state.tokenize = jsTokenBase; + break; + } + maybeEnd = (ch == "_"); + } + return ret("text", "underlined"); + } + + // tw strike through text looks ugly + // change CSS if needed + function twTokenStrike(stream, state) { + var maybeEnd = false, ch; + + while (ch = stream.next()) { + if (ch == "-" && maybeEnd) { + state.tokenize = jsTokenBase; + break; + } + maybeEnd = (ch == "-"); + } + return ret("text", "strikethrough"); + } + + // macro + function twTokenMacro(stream, state) { + var ch, word, known; + + if (stream.current() == '<<') { + return ret('brace', 'macro'); + } + + ch = stream.next(); + if (!ch) { + state.tokenize = jsTokenBase; + return ret(ch); + } + if (ch == ">") { + if (stream.peek() == '>') { + stream.next(); + state.tokenize = jsTokenBase; + return ret("brace", "macro"); + } + } + + stream.eatWhile(/[\w\$_]/); + word = stream.current(); + known = keywords.propertyIsEnumerable(word) && keywords[word]; + + if (known) { + return ret(known.type, known.style, word); + } + else { + return ret("macro", null, word); + } + } + + // Interface + return { + startState: function () { + return { + tokenize: jsTokenBase, + indented: 0, + level: 0 + }; + }, + + token: function (stream, state) { + if (stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + return style; + }, + + electricChars: "" + }; +}); + +CodeMirror.defineMIME("text/x-tiddlywiki", "tiddlywiki"); +//}}} diff --git a/codemirror/mode/tiki/index.html b/codemirror/mode/tiki/index.html new file mode 100644 index 0000000..7b85a44 --- /dev/null +++ b/codemirror/mode/tiki/index.html @@ -0,0 +1,81 @@ + + + + CodeMirror: Tiki wiki mode + + + + + + + + +

CodeMirror: Tiki wiki mode

+ +
+ + + + + diff --git a/codemirror/mode/tiki/tiki.css b/codemirror/mode/tiki/tiki.css new file mode 100644 index 0000000..e3c3c0f --- /dev/null +++ b/codemirror/mode/tiki/tiki.css @@ -0,0 +1,26 @@ +.cm-tw-syntaxerror { + color: #FFFFFF; + background-color: #990000; +} + +.cm-tw-deleted { + text-decoration: line-through; +} + +.cm-tw-header5 { + font-weight: bold; +} +.cm-tw-listitem:first-child { /*Added first child to fix duplicate padding when highlighting*/ + padding-left: 10px; +} + +.cm-tw-box { + border-top-width: 0px ! important; + border-style: solid; + border-width: 1px; + border-color: inherit; +} + +.cm-tw-underline { + text-decoration: underline; +} \ No newline at end of file diff --git a/codemirror/mode/tiki/tiki.js b/codemirror/mode/tiki/tiki.js new file mode 100644 index 0000000..81e87ab --- /dev/null +++ b/codemirror/mode/tiki/tiki.js @@ -0,0 +1,309 @@ +CodeMirror.defineMode('tiki', function(config) { + function inBlock(style, terminator, returnTokenizer) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.match(terminator)) { + state.tokenize = inText; + break; + } + stream.next(); + } + + if (returnTokenizer) state.tokenize = returnTokenizer; + + return style; + }; + } + + function inLine(style) { + return function(stream, state) { + while(!stream.eol()) { + stream.next(); + } + state.tokenize = inText; + return style; + }; + } + + function inText(stream, state) { + function chain(parser) { + state.tokenize = parser; + return parser(stream, state); + } + + var sol = stream.sol(); + var ch = stream.next(); + + //non start of line + switch (ch) { //switch is generally much faster than if, so it is used here + case "{": //plugin + stream.eat("/"); + stream.eatSpace(); + var tagName = ""; + var c; + while ((c = stream.eat(/[^\s\u00a0=\"\'\/?(}]/))) tagName += c; + state.tokenize = inPlugin; + return "tag"; + break; + case "_": //bold + if (stream.eat("_")) { + return chain(inBlock("strong", "__", inText)); + } + break; + case "'": //italics + if (stream.eat("'")) { + // Italic text + return chain(inBlock("em", "''", inText)); + } + break; + case "(":// Wiki Link + if (stream.eat("(")) { + return chain(inBlock("variable-2", "))", inText)); + } + break; + case "[":// Weblink + return chain(inBlock("variable-3", "]", inText)); + break; + case "|": //table + if (stream.eat("|")) { + return chain(inBlock("comment", "||")); + } + break; + case "-": + if (stream.eat("=")) {//titleBar + return chain(inBlock("header string", "=-", inText)); + } else if (stream.eat("-")) {//deleted + return chain(inBlock("error tw-deleted", "--", inText)); + } + break; + case "=": //underline + if (stream.match("==")) { + return chain(inBlock("tw-underline", "===", inText)); + } + break; + case ":": + if (stream.eat(":")) { + return chain(inBlock("comment", "::")); + } + break; + case "^": //box + return chain(inBlock("tw-box", "^")); + break; + case "~": //np + if (stream.match("np~")) { + return chain(inBlock("meta", "~/np~")); + } + break; + } + + //start of line types + if (sol) { + switch (ch) { + case "!": //header at start of line + if (stream.match('!!!!!')) { + return chain(inLine("header string")); + } else if (stream.match('!!!!')) { + return chain(inLine("header string")); + } else if (stream.match('!!!')) { + return chain(inLine("header string")); + } else if (stream.match('!!')) { + return chain(inLine("header string")); + } else { + return chain(inLine("header string")); + } + break; + case "*": //unordered list line item, or
  • at start of line + case "#": //ordered list line item, or
  • at start of line + case "+": //ordered list line item, or
  • at start of line + return chain(inLine("tw-listitem bracket")); + break; + } + } + + //stream.eatWhile(/[&{]/); was eating up plugins, turned off to act less like html and more like tiki + return null; + } + + var indentUnit = config.indentUnit; + + // Return variables for tokenizers + var pluginName, type; + function inPlugin(stream, state) { + var ch = stream.next(); + var peek = stream.peek(); + + if (ch == "}") { + state.tokenize = inText; + //type = ch == ")" ? "endPlugin" : "selfclosePlugin"; inPlugin + return "tag"; + } else if (ch == "(" || ch == ")") { + return "bracket"; + } else if (ch == "=") { + type = "equals"; + + if (peek == ">") { + ch = stream.next(); + peek = stream.peek(); + } + + //here we detect values directly after equal character with no quotes + if (!/[\'\"]/.test(peek)) { + state.tokenize = inAttributeNoQuote(); + } + //end detect values + + return "operator"; + } else if (/[\'\"]/.test(ch)) { + state.tokenize = inAttribute(ch); + return state.tokenize(stream, state); + } else { + stream.eatWhile(/[^\s\u00a0=\"\'\/?]/); + return "keyword"; + } + } + + function inAttribute(quote) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.next() == quote) { + state.tokenize = inPlugin; + break; + } + } + return "string"; + }; + } + + function inAttributeNoQuote() { + return function(stream, state) { + while (!stream.eol()) { + var ch = stream.next(); + var peek = stream.peek(); + if (ch == " " || ch == "," || /[ )}]/.test(peek)) { + state.tokenize = inPlugin; + break; + } + } + return "string"; + }; + } + + var curState, setStyle; + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]); + } + + function cont() { + pass.apply(null, arguments); + return true; + } + + function pushContext(pluginName, startOfLine) { + var noIndent = curState.context && curState.context.noIndent; + curState.context = { + prev: curState.context, + pluginName: pluginName, + indent: curState.indented, + startOfLine: startOfLine, + noIndent: noIndent + }; + } + + function popContext() { + if (curState.context) curState.context = curState.context.prev; + } + + function element(type) { + if (type == "openPlugin") {curState.pluginName = pluginName; return cont(attributes, endplugin(curState.startOfLine));} + else if (type == "closePlugin") { + var err = false; + if (curState.context) { + err = curState.context.pluginName != pluginName; + popContext(); + } else { + err = true; + } + if (err) setStyle = "error"; + return cont(endcloseplugin(err)); + } + else if (type == "string") { + if (!curState.context || curState.context.name != "!cdata") pushContext("!cdata"); + if (curState.tokenize == inText) popContext(); + return cont(); + } + else return cont(); + } + + function endplugin(startOfLine) { + return function(type) { + if ( + type == "selfclosePlugin" || + type == "endPlugin" + ) + return cont(); + if (type == "endPlugin") {pushContext(curState.pluginName, startOfLine); return cont();} + return cont(); + }; + } + + function endcloseplugin(err) { + return function(type) { + if (err) setStyle = "error"; + if (type == "endPlugin") return cont(); + return pass(); + }; + } + + function attributes(type) { + if (type == "keyword") {setStyle = "attribute"; return cont(attributes);} + if (type == "equals") return cont(attvalue, attributes); + return pass(); + } + function attvalue(type) { + if (type == "keyword") {setStyle = "string"; return cont();} + if (type == "string") return cont(attvaluemaybe); + return pass(); + } + function attvaluemaybe(type) { + if (type == "string") return cont(attvaluemaybe); + else return pass(); + } + return { + startState: function() { + return {tokenize: inText, cc: [], indented: 0, startOfLine: true, pluginName: null, context: null}; + }, + token: function(stream, state) { + if (stream.sol()) { + state.startOfLine = true; + state.indented = stream.indentation(); + } + if (stream.eatSpace()) return null; + + setStyle = type = pluginName = null; + var style = state.tokenize(stream, state); + if ((style || type) && style != "comment") { + curState = state; + while (true) { + var comb = state.cc.pop() || element; + if (comb(type || style)) break; + } + } + state.startOfLine = false; + return setStyle || style; + }, + indent: function(state, textAfter) { + var context = state.context; + if (context && context.noIndent) return 0; + if (context && /^{\//.test(textAfter)) + context = context.prev; + while (context && !context.startOfLine) + context = context.prev; + if (context) return context.indent + indentUnit; + else return 0; + }, + electricChars: "/" + }; +}); + +//I figure, why not +CodeMirror.defineMIME("text/tiki", "tiki"); diff --git a/codemirror/mode/vb/LICENSE.txt b/codemirror/mode/vb/LICENSE.txt new file mode 100644 index 0000000..6083970 --- /dev/null +++ b/codemirror/mode/vb/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2012 Codility Limited, 107 Cheapside, London EC2V 6DN, UK + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/codemirror/mode/vb/index.html b/codemirror/mode/vb/index.html new file mode 100644 index 0000000..1670c7d --- /dev/null +++ b/codemirror/mode/vb/index.html @@ -0,0 +1,88 @@ + + + + CodeMirror: VB.NET mode + + + + + + + + + +

    CodeMirror: VB.NET mode

    + + + +
    + +
    +
    
    +  

    MIME type defined: text/x-vb.

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

    CodeMirror: VBScript mode

    + +
    + + + +

    MIME types defined: text/vbscript.

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

    CodeMirror: Velocity mode

    +
    + + +

    MIME types defined: text/velocity.

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

    CodeMirror: Verilog mode

    + +
    + + + +

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

    + +

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

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

    CodeMirror: XML mode

    +
    + +

    The XML mode supports two configuration parameters:

    +
    +
    htmlMode (boolean)
    +
    This switches the mode to parse HTML instead of XML. This + means attributes do not have to be quoted, and some elements + (such as br) do not require a closing tag.
    +
    alignCDATA (boolean)
    +
    Setting this to true will force the opening tag of CDATA + blocks to not be indented.
    +
    + +

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

    + + diff --git a/codemirror/mode/xml/xml.js b/codemirror/mode/xml/xml.js new file mode 100644 index 0000000..7b11fd6 --- /dev/null +++ b/codemirror/mode/xml/xml.js @@ -0,0 +1,324 @@ +CodeMirror.defineMode("xml", function(config, parserConfig) { + var indentUnit = config.indentUnit; + var Kludges = parserConfig.htmlMode ? { + autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, + 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, + 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, + 'track': true, 'wbr': true}, + implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, + 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, + 'th': true, 'tr': true}, + contextGrabbers: { + 'dd': {'dd': true, 'dt': true}, + 'dt': {'dd': true, 'dt': true}, + 'li': {'li': true}, + 'option': {'option': true, 'optgroup': true}, + 'optgroup': {'optgroup': true}, + 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, + 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, + 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, + 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, + 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, + 'rp': {'rp': true, 'rt': true}, + 'rt': {'rp': true, 'rt': true}, + 'tbody': {'tbody': true, 'tfoot': true}, + 'td': {'td': true, 'th': true}, + 'tfoot': {'tbody': true}, + 'th': {'td': true, 'th': true}, + 'thead': {'tbody': true, 'tfoot': true}, + 'tr': {'tr': true} + }, + doNotIndent: {"pre": true}, + allowUnquoted: true, + allowMissing: true + } : { + autoSelfClosers: {}, + implicitlyClosed: {}, + contextGrabbers: {}, + doNotIndent: {}, + allowUnquoted: false, + allowMissing: false + }; + var alignCDATA = parserConfig.alignCDATA; + + // Return variables for tokenizers + var tagName, type; + + function inText(stream, state) { + function chain(parser) { + state.tokenize = parser; + return parser(stream, state); + } + + var ch = stream.next(); + if (ch == "<") { + if (stream.eat("!")) { + if (stream.eat("[")) { + if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); + else return null; + } + else if (stream.match("--")) return chain(inBlock("comment", "-->")); + else if (stream.match("DOCTYPE", true, true)) { + stream.eatWhile(/[\w\._\-]/); + return chain(doctype(1)); + } + else return null; + } + else if (stream.eat("?")) { + stream.eatWhile(/[\w\._\-]/); + state.tokenize = inBlock("meta", "?>"); + return "meta"; + } + else { + var isClose = stream.eat("/"); + tagName = ""; + var c; + while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c; + if (!tagName) return "error"; + type = isClose ? "closeTag" : "openTag"; + state.tokenize = inTag; + return "tag"; + } + } + else if (ch == "&") { + var ok; + if (stream.eat("#")) { + if (stream.eat("x")) { + ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); + } else { + ok = stream.eatWhile(/[\d]/) && stream.eat(";"); + } + } else { + ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); + } + return ok ? "atom" : "error"; + } + else { + stream.eatWhile(/[^&<]/); + return null; + } + } + + function inTag(stream, state) { + var ch = stream.next(); + if (ch == ">" || (ch == "/" && stream.eat(">"))) { + state.tokenize = inText; + type = ch == ">" ? "endTag" : "selfcloseTag"; + return "tag"; + } + else if (ch == "=") { + type = "equals"; + return null; + } + else if (/[\'\"]/.test(ch)) { + state.tokenize = inAttribute(ch); + return state.tokenize(stream, state); + } + else { + stream.eatWhile(/[^\s\u00a0=<>\"\']/); + return "word"; + } + } + + function inAttribute(quote) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.next() == quote) { + state.tokenize = inTag; + break; + } + } + return "string"; + }; + } + + function inBlock(style, terminator) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.match(terminator)) { + state.tokenize = inText; + break; + } + stream.next(); + } + return style; + }; + } + function doctype(depth) { + return function(stream, state) { + var ch; + while ((ch = stream.next()) != null) { + if (ch == "<") { + state.tokenize = doctype(depth + 1); + return state.tokenize(stream, state); + } else if (ch == ">") { + if (depth == 1) { + state.tokenize = inText; + break; + } else { + state.tokenize = doctype(depth - 1); + return state.tokenize(stream, state); + } + } + } + return "meta"; + }; + } + + var curState, setStyle; + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]); + } + function cont() { + pass.apply(null, arguments); + return true; + } + + function pushContext(tagName, startOfLine) { + var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent); + curState.context = { + prev: curState.context, + tagName: tagName, + indent: curState.indented, + startOfLine: startOfLine, + noIndent: noIndent + }; + } + function popContext() { + if (curState.context) curState.context = curState.context.prev; + } + + function element(type) { + if (type == "openTag") { + curState.tagName = tagName; + return cont(attributes, endtag(curState.startOfLine)); + } else if (type == "closeTag") { + var err = false; + if (curState.context) { + if (curState.context.tagName != tagName) { + if (Kludges.implicitlyClosed.hasOwnProperty(curState.context.tagName.toLowerCase())) { + popContext(); + } + err = !curState.context || curState.context.tagName != tagName; + } + } else { + err = true; + } + if (err) setStyle = "error"; + return cont(endclosetag(err)); + } + return cont(); + } + function endtag(startOfLine) { + return function(type) { + var tagName = curState.tagName; + curState.tagName = null; + if (type == "selfcloseTag" || + (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(tagName.toLowerCase()))) { + maybePopContext(tagName.toLowerCase()); + return cont(); + } + if (type == "endTag") { + maybePopContext(tagName.toLowerCase()); + pushContext(tagName, startOfLine); + return cont(); + } + return cont(); + }; + } + function endclosetag(err) { + return function(type) { + if (err) setStyle = "error"; + if (type == "endTag") { popContext(); return cont(); } + setStyle = "error"; + return cont(arguments.callee); + }; + } + function maybePopContext(nextTagName) { + var parentTagName; + while (true) { + if (!curState.context) { + return; + } + parentTagName = curState.context.tagName.toLowerCase(); + if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) || + !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { + return; + } + popContext(); + } + } + + function attributes(type) { + if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);} + if (type == "endTag" || type == "selfcloseTag") return pass(); + setStyle = "error"; + return cont(attributes); + } + function attribute(type) { + if (type == "equals") return cont(attvalue, attributes); + if (!Kludges.allowMissing) setStyle = "error"; + else if (type == "word") setStyle = "attribute"; + return (type == "endTag" || type == "selfcloseTag") ? pass() : cont(); + } + function attvalue(type) { + if (type == "string") return cont(attvaluemaybe); + if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();} + setStyle = "error"; + return (type == "endTag" || type == "selfCloseTag") ? pass() : cont(); + } + function attvaluemaybe(type) { + if (type == "string") return cont(attvaluemaybe); + else return pass(); + } + + return { + startState: function() { + return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, context: null}; + }, + + token: function(stream, state) { + if (stream.sol()) { + state.startOfLine = true; + state.indented = stream.indentation(); + } + if (stream.eatSpace()) return null; + + setStyle = type = tagName = null; + var style = state.tokenize(stream, state); + state.type = type; + if ((style || type) && style != "comment") { + curState = state; + while (true) { + var comb = state.cc.pop() || element; + if (comb(type || style)) break; + } + } + state.startOfLine = false; + return setStyle || style; + }, + + indent: function(state, textAfter, fullLine) { + var context = state.context; + if ((state.tokenize != inTag && state.tokenize != inText) || + context && context.noIndent) + return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; + if (alignCDATA && / + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/codemirror/mode/xquery/index.html b/codemirror/mode/xquery/index.html new file mode 100644 index 0000000..27acb89 --- /dev/null +++ b/codemirror/mode/xquery/index.html @@ -0,0 +1,221 @@ + + + + + + CodeMirror: XQuery mode + + + + + + + + +

    CodeMirror: XQuery mode

    + +
    + +
    + + + +

    MIME types defined: application/xquery.

    + +

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

    + + + diff --git a/codemirror/mode/xquery/test.js b/codemirror/mode/xquery/test.js new file mode 100644 index 0000000..23ab3d1 --- /dev/null +++ b/codemirror/mode/xquery/test.js @@ -0,0 +1,77 @@ +// Initiate ModeTest and set defaults +var MT = ModeTest; +MT.modeName = "xquery"; +MT.modeOptions = {}; + +MT.testMode("eviltest", + 'xquery version "1.0-ml";\ + (: this is\ + : a \ + "comment" :)\ + let $let := <x attr="value">"test"<func>function() $var {function()} {$var}</func></x>\ + let $joe:=1\ + return element element {\ + attribute attribute { 1 },\ + element test { 'a' }, \ + attribute foo { "bar" },\ + fn:doc()[ foo/@bar eq $let ],\ + //x } \ + \ + (: a more \'evil\' test :)\ + (: Modified Blakeley example (: with nested comment :) ... :)\ + declare private function local:declare() {()};\ + declare private function local:private() {()};\ + declare private function local:function() {()};\ + declare private function local:local() {()};\ + let $let := <let>let $let := "let"</let>\ + return element element {\ + attribute attribute { try { xdmp:version() } catch($e) { xdmp:log($e) } },\ + attribute fn:doc { "bar" castable as xs:string },\ + element text { text { "text" } },\ + fn:doc()[ child::eq/(@bar | attribute::attribute) eq $let ],\ + //fn:doc\ + }', ["keyword","xquery",null," ","keyword","version",null," ","variable",""1","keyword",".","atom","0","keyword","-","variable","ml"","def variable",";",null," ","comment","(: this is : a \"comment\" :)",null," ","keyword","let",null," ","variable","$let",null," ","keyword",":=",null," ","variable","<x",null," ","variable","attr","keyword","=","variable",""value">"test"<func>","def variable",";function","","()",null," ","variable","$var",null," ","","{","keyword","function","","()}",null," ","","{","variable","$var","","}","variable","<","keyword","/","variable","func><","keyword","/","variable","x>",null," ","keyword","let",null," ","variable","$joe","keyword",":=","atom","1",null," ","keyword","return",null," ","keyword","element",null," ","variable","element",null," ","","{",null," ","keyword","attribute",null," ","variable","attribute",null," ","","{",null," ","atom","1",null," ","","},",null," ","keyword","element",null," ","variable","test",null," ","","{",null," ","variable","'a'",null," ","","},",null," ","keyword","attribute",null," ","variable","foo",null," ","","{",null," ","variable",""bar"",null," ","","},",null," ","def variable","fn:doc","","()[",null," ","variable","foo","keyword","/","variable","@bar",null," ","keyword","eq",null," ","variable","$let",null," ","","],",null," ","keyword","//","variable","x",null," ","","}",null," ","comment","(: a more 'evil' test :)",null," ","comment","(: Modified Blakeley example (: with nested comment :) ... :)",null," ","keyword","declare",null," ","keyword","private",null," ","keyword","function",null," ","def variable","local:declare","","()",null," ","","{()}","variable",";",null," ","keyword","declare",null," ","keyword","private",null," ","keyword","function",null," ","def variable","local:private","","()",null," ","","{()}","variable",";",null," ","keyword","declare",null," ","keyword","private",null," ","keyword","function",null," ","def variable","local:function","","()",null," ","","{()}","variable",";",null," ","keyword","declare",null," ","keyword","private",null," ","keyword","function",null," ","def variable","local:local","","()",null," ","","{()}","variable",";",null," ","keyword","let",null," ","variable","$let",null," ","keyword",":=",null," ","variable","<let>let",null," ","variable","$let",null," ","keyword",":=",null," ","variable",""let"<","keyword","/let","variable",">",null," ","keyword","return",null," ","keyword","element",null," ","variable","element",null," ","","{",null," ","keyword","attribute",null," ","variable","attribute",null," ","","{",null," ","keyword","try",null," ","","{",null," ","def variable","xdmp:version","","()",null," ","","}",null," ","keyword","catch","","(","variable","$e","",")",null," ","","{",null," ","def variable","xdmp:log","","(","variable","$e","",")",null," ","","}",null," ","","},",null," ","keyword","attribute",null," ","variable","fn:doc",null," ","","{",null," ","variable",""bar"",null," ","variable","castable",null," ","keyword","as",null," ","atom","xs:string",null," ","","},",null," ","keyword","element",null," ","variable","text",null," ","","{",null," ","keyword","text",null," ","","{",null," ","variable",""text"",null," ","","}",null," ","","},",null," ","def variable","fn:doc","","()[",null," ","qualifier","child::","variable","eq","keyword","/","","(","variable","@bar",null," ","keyword","|",null," ","qualifier","attribute::","variable","attribute","",")",null," ","keyword","eq",null," ","variable","$let",null," ","","],",null," ","keyword","//","variable","fn:doc",null," ","","}"]); + +MT.testMode("testEmptySequenceKeyword", + '"foo" instance of empty-sequence()', + ["string","\"foo\"",null," ","keyword","instance",null," ","keyword","of",null," ","keyword","empty-sequence","","()"]); + + +MT.testMode("testMultiAttr", + '

    hello world

    ', + ["tag","

    ","variable","hello",null," ","variable","world","tag","

    "]); + +MT.testMode("test namespaced variable", + 'declare namespace e = "http://example.com/ANamespace";\ +declare variable $e:exampleComThisVarIsNotRecognized as element(*) external;', + ["keyword","declare",null," ","keyword","namespace",null," ","variable","e",null," ","keyword","=",null," ","string","\"http://example.com/ANamespace\"","variable",";declare",null," ","keyword","variable",null," ","variable","$e:exampleComThisVarIsNotRecognized",null," ","keyword","as",null," ","keyword","element","","(","keyword","*","",")",null," ","variable","external;"]); + +MT.testMode("test EQName variable", + 'declare variable $"http://www.example.com/ns/my":var := 12;\ +{$"http://www.example.com/ns/my":var}', + ["keyword","declare",null," ","keyword","variable",null," ","variable","$\"http://www.example.com/ns/my\":var",null," ","keyword",":=",null," ","atom","12","variable",";","tag","","","{","variable","$\"http://www.example.com/ns/my\":var","","}","tag",""]); + +MT.testMode("test EQName function", + 'declare function "http://www.example.com/ns/my":fn ($a as xs:integer) as xs:integer {\ + $a + 2\ +};\ +{"http://www.example.com/ns/my":fn(12)}', + ["keyword","declare",null," ","keyword","function",null," ","def variable","\"http://www.example.com/ns/my\":fn",null," ","","(","variable","$a",null," ","keyword","as",null," ","atom","xs:integer","",")",null," ","keyword","as",null," ","atom","xs:integer",null," ","","{",null," ","variable","$a",null," ","keyword","+",null," ","atom","2","","}","variable",";","tag","","","{","def variable","\"http://www.example.com/ns/my\":fn","","(","atom","12","",")}","tag",""]); + +MT.testMode("test EQName function with single quotes", + 'declare function \'http://www.example.com/ns/my\':fn ($a as xs:integer) as xs:integer {\ + $a + 2\ +};\ +{\'http://www.example.com/ns/my\':fn(12)}', + ["keyword","declare",null," ","keyword","function",null," ","def variable","'http://www.example.com/ns/my':fn",null," ","","(","variable","$a",null," ","keyword","as",null," ","atom","xs:integer","",")",null," ","keyword","as",null," ","atom","xs:integer",null," ","","{",null," ","variable","$a",null," ","keyword","+",null," ","atom","2","","}","variable",";","tag","","","{","def variable","'http://www.example.com/ns/my':fn","","(","atom","12","",")}","tag",""]); + +MT.testMode("testProcessingInstructions", + 'data() instance of xs:string', + ["def variable","data","","(","comment meta","","",")",null," ","keyword","instance",null," ","keyword","of",null," ","atom","xs:string"]); + +MT.testMode("testQuoteEscapeDouble", + 'let $rootfolder := "c:\\builds\\winnt\\HEAD\\qa\\scripts\\"\ +let $keysfolder := concat($rootfolder, "keys\\")\ +return\ +$keysfolder', + ["keyword","let",null," ","variable","$rootfolder",null," ","keyword",":=",null," ","string","\"c:\\builds\\winnt\\HEAD\\qa\\scripts\\\"","keyword","let",null," ","variable","$keysfolder",null," ","keyword",":=",null," ","def variable","concat","","(","variable","$rootfolder","",",",null," ","string","\"keys\\\"","",")","variable","return$keysfolder"]); diff --git a/codemirror/mode/xquery/xquery.js b/codemirror/mode/xquery/xquery.js new file mode 100644 index 0000000..e4231d1 --- /dev/null +++ b/codemirror/mode/xquery/xquery.js @@ -0,0 +1,450 @@ +/* +Copyright (C) 2011 by MarkLogic Corporation +Author: Mike Brevoort + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +CodeMirror.defineMode("xquery", function() { + + // The keywords object is set to the result of this self executing + // function. Each keyword is a property of the keywords object whose + // value is {type: atype, style: astyle} + var keywords = function(){ + // conveinence functions used to build keywords object + function kw(type) {return {type: type, style: "keyword"};} + var A = kw("keyword a") + , B = kw("keyword b") + , C = kw("keyword c") + , operator = kw("operator") + , atom = {type: "atom", style: "atom"} + , punctuation = {type: "punctuation", style: ""} + , 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("", ""); + } + // end code block + else if(ch == "}") { + popStateStack(state); + return ret("", ""); + } + // 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("", ""); + } + // close paren + else if(ch === ")") { + popStateStack(state); + return ret("", ""); + } + // open paren + else if(ch === "[") { + pushStateStack(state, { type: "bracket"}); + return ret("", ""); + } + // close paren + else if(ch === "]") { + popStateStack(state); + return ret("", ""); + } + 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("", ""); + // quoted string + if (ch == '"' || ch == "'") + return chain(stream, state, tokenString(ch, tokenAttribute)); + + if(!isInXmlAttributeBlock(state)) + pushStateStack(state, { type: "attribute", name: name, tokenize: tokenAttribute}); + + stream.eat(/[a-zA-Z_:]/); + stream.eatWhile(/[-a-zA-Z0-9_:.]/); + stream.eatSpace(); + + // the case where the attribute has not value and the tag was closed + if(stream.match(">", false) || stream.match("/", false)) { + popStateStack(state); + state.tokenize = tokenBase; + } + + return ret("attribute", "attribute"); + } + + // handle comments, including nested + function tokenXMLComment(stream, state) { + var ch; + while (ch = stream.next()) { + if (ch == "-" && stream.match("->", true)) { + state.tokenize = tokenBase; + return ret("comment", "comment"); + } + } + } + + + // handle CDATA + function tokenCDATA(stream, state) { + var ch; + while (ch = stream.next()) { + if (ch == "]" && stream.match("]", true)) { + state.tokenize = tokenBase; + return ret("comment", "comment"); + } + } + } + + // handle preprocessing instructions + function tokenPreProcessing(stream, state) { + var ch; + while (ch = stream.next()) { + if (ch == "?" && stream.match(">", true)) { + state.tokenize = tokenBase; + return ret("comment", "comment meta"); + } + } + } + + + // functions to test the current context of the state + function isInXmlBlock(state) { return isIn(state, "tag"); } + function isInXmlAttributeBlock(state) { return isIn(state, "attribute"); } + function isInXmlConstructor(state) { return isIn(state, "xmlconstructor"); } + function isInString(state) { return isIn(state, "string"); } + + function isEQNameAhead(stream) { + // assume we've already eaten a quote (") + if(stream.current() === '"') + return stream.match(/^[^\"]+\"\:/, false); + else if(stream.current() === '\'') + return stream.match(/^[^\"]+\'\:/, false); + else + return false; + } + + function isIn(state, type) { + return (state.stack.length && state.stack[state.stack.length - 1].type == type); + } + + function pushStateStack(state, newState) { + state.stack.push(newState); + } + + function popStateStack(state) { + state.stack.pop(); + var reinstateTokenize = state.stack.length && state.stack[state.stack.length-1].tokenize; + state.tokenize = reinstateTokenize || tokenBase; + } + + // the interface for the mode API + return { + startState: function() { + return { + tokenize: tokenBase, + cc: [], + stack: [] + }; + }, + + token: function(stream, state) { + if (stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + return style; + } + }; + +}); + +CodeMirror.defineMIME("application/xquery", "xquery"); diff --git a/codemirror/mode/yaml/index.html b/codemirror/mode/yaml/index.html new file mode 100644 index 0000000..65e1ea7 --- /dev/null +++ b/codemirror/mode/yaml/index.html @@ -0,0 +1,68 @@ + + + + + CodeMirror: YAML mode + + + + + + + +

    CodeMirror: YAML mode

    +
    + + +

    MIME types defined: text/x-yaml.

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

    CodeMirror: Z80 assembly mode

    + +
    + + + +

    MIME type defined: text/x-z80.

    + + diff --git a/codemirror/mode/z80/z80.js b/codemirror/mode/z80/z80.js new file mode 100644 index 0000000..c026790 --- /dev/null +++ b/codemirror/mode/z80/z80.js @@ -0,0 +1,113 @@ +CodeMirror.defineMode('z80', function() +{ + var keywords1 = /^(exx?|(ld|cp|in)([di]r?)?|pop|push|ad[cd]|cpl|daa|dec|inc|neg|sbc|sub|and|bit|[cs]cf|x?or|res|set|r[lr]c?a?|r[lr]d|s[lr]a|srl|djnz|nop|rst|[de]i|halt|im|ot[di]r|out[di]?)\b/i; + var keywords2 = /^(call|j[pr]|ret[in]?)\b/i; + var keywords3 = /^b_?(call|jump)\b/i; + var variables1 = /^(af?|bc?|c|de?|e|hl?|l|i[xy]?|r|sp)\b/i; + var variables2 = /^(n?[zc]|p[oe]?|m)\b/i; + var errors = /^([hl][xy]|i[xy][hl]|slia|sll)\b/i; + var numbers = /^([\da-f]+h|[0-7]+o|[01]+b|\d+)\b/i; + + return {startState: function() + { + return {context: 0}; + }, token: function(stream, state) + { + if (!stream.column()) + state.context = 0; + + if (stream.eatSpace()) + return null; + + var w; + + if (stream.eatWhile(/\w/)) + { + w = stream.current(); + + if (stream.indentation()) + { + if (state.context == 1 && variables1.test(w)) + return 'variable-2'; + + if (state.context == 2 && variables2.test(w)) + return 'variable-3'; + + if (keywords1.test(w)) + { + state.context = 1; + return 'keyword'; + } + else if (keywords2.test(w)) + { + state.context = 2; + return 'keyword'; + } + else if (keywords3.test(w)) + { + state.context = 3; + return 'keyword'; + } + + if (errors.test(w)) + return 'error'; + } + else if (numbers.test(w)) + { + return 'number'; + } + else + { + return null; + } + } + else if (stream.eat(';')) + { + stream.skipToEnd(); + return 'comment'; + } + else if (stream.eat('"')) + { + while (w = stream.next()) + { + if (w == '"') + break; + + if (w == '\\') + stream.next(); + } + + return 'string'; + } + else if (stream.eat('\'')) + { + if (stream.match(/\\?.'/)) + return 'number'; + } + else if (stream.eat('.') || stream.sol() && stream.eat('#')) + { + state.context = 4; + + if (stream.eatWhile(/\w/)) + return 'def'; + } + else if (stream.eat('$')) + { + if (stream.eatWhile(/[\da-f]/i)) + return 'number'; + } + else if (stream.eat('%')) + { + if (stream.eatWhile(/[01]/)) + return 'number'; + } + else + { + stream.next(); + } + + return null; + }}; +}); + +CodeMirror.defineMIME("text/x-z80", "z80"); diff --git a/codemirror/package.json b/codemirror/package.json new file mode 100644 index 0000000..4a56fe6 --- /dev/null +++ b/codemirror/package.json @@ -0,0 +1,21 @@ +{ + "name": "codemirror", + "version":"3.0.21", + "main": "codemirror.js", + "description": "In-browser code editing made bearable", + "licenses": [{"type": "MIT", + "url": "http://codemirror.net/LICENSE"}], + "directories": {"lib": "./lib"}, + "scripts": {"test": "node ./test/run.js"}, + "devDependencies": {"node-static": "0.6.0"}, + "bugs": "http://github.com/marijnh/CodeMirror/issues", + "keywords": ["JavaScript", "CodeMirror", "Editor"], + "homepage": "http://codemirror.net", + "maintainers":[{"name": "Marijn Haverbeke", + "email": "marijnh@gmail.com", + "web": "http://marijnhaverbeke.nl"}], + "repositories": [{"type": "git", + "url": "http://marijnhaverbeke.nl/git/codemirror"}, + {"type": "git", + "url": "https://github.com/marijnh/CodeMirror.git"}] +} diff --git a/codemirror/test/driver.js b/codemirror/test/driver.js new file mode 100644 index 0000000..6306991 --- /dev/null +++ b/codemirror/test/driver.js @@ -0,0 +1,134 @@ +var tests = [], debug = null, debugUsed = new Array(), allNames = []; + +function Failure(why) {this.message = why;} +Failure.prototype.toString = function() { return this.message; }; + +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 test(name, run, expectedFail) { + // Force unique names + var originalName = name; + var i = 2; // Second function would be NAME_2 + while (indexOf(allNames, name) !== -1){ + name = originalName + "_" + i; + i++; + } + allNames.push(name); + // Add test + tests.push({name: name, func: run, expectedFail: expectedFail}); + return name; +} +function testCM(name, run, opts, expectedFail) { + return test("core_" + name, function() { + var place = document.getElementById("testground"), cm = CodeMirror(place, opts); + var successful = false; + try { + run(cm); + successful = true; + } finally { + if ((debug && !successful) || verbose) { + place.style.visibility = "visible"; + } else { + place.removeChild(cm.getWrapperElement()); + } + } + }, expectedFail); +} + +function runTests(callback) { + if (debug) { + if (indexOf(debug, "verbose") === 0) { + verbose = true; + debug.splice(0, 1); + } + if (debug.length < 1) { + debug = null; + } else { + if (totalTests > debug.length) { + totalTests = debug.length; + } + } + } + var totalTime = 0; + function step(i) { + if (i === tests.length){ + running = false; + return callback("done"); + } + var test = tests[i], expFail = test.expectedFail, startTime = +new Date; + if (debug !== null) { + var debugIndex = indexOf(debug, test.name); + if (debugIndex !== -1) { + // Remove from array for reporting incorrect tests later + debug.splice(debugIndex, 1); + } else { + var wildcardName = test.name.split("_").shift() + "_*"; + debugIndex = indexOf(debug, wildcardName); + if (debugIndex !== -1) { + // Remove from array for reporting incorrect tests later + debug.splice(debugIndex, 1); + debugUsed.push(wildcardName); + } else { + debugIndex = indexOf(debugUsed, wildcardName); + if (debugIndex !== -1) { + totalTests++; + } else { + return step(i + 1); + } + } + } + } + var threw = false; + try { + var message = test.func(); + } catch(e) { + threw = true; + if (expFail) callback("expected", test.name); + else if (e instanceof Failure) callback("fail", test.name, e.message); + else { + var pos = /\bat .*?([^\/:]+):(\d+):/.exec(e.stack); + callback("error", test.name, e.toString() + (pos ? " (" + pos[1] + ":" + pos[2] + ")" : "")); + } + } + if (!threw) { + if (expFail) callback("fail", test.name, message || "expected failure, but succeeded"); + else callback("ok", test.name, message); + } + if (!quit) { // Run next test + var delay = 0; + totalTime += (+new Date) - startTime; + if (totalTime > 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))); + if (b == null) throw new Failure(label("comparing " + str(a) + " to null")); + 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)); +} diff --git a/codemirror/test/index.html b/codemirror/test/index.html new file mode 100644 index 0000000..9634ac2 --- /dev/null +++ b/codemirror/test/index.html @@ -0,0 +1,186 @@ + + + + + CodeMirror: Test Suite + + + + + + + + + + + + + +

    CodeMirror: Test Suite

    + +

    A limited set of programmatic sanity tests for CodeMirror.

    + +
    +
    Ran 0 of 0 tests
    +
    +

    Please enable JavaScript...

    +
    + +
    + + + + + + + + + + + + + + + + + + diff --git a/codemirror/test/lint/acorn.js b/codemirror/test/lint/acorn.js new file mode 100644 index 0000000..6323b1f --- /dev/null +++ b/codemirror/test/lint/acorn.js @@ -0,0 +1,1593 @@ +// Acorn is a tiny, fast JavaScript parser written in JavaScript. +// +// Acorn was written by Marijn Haverbeke and released under an MIT +// license. The Unicode regexps (for identifiers and whitespace) were +// taken from [Esprima](http://esprima.org) by Ariya Hidayat. +// +// Git repositories for Acorn are available at +// +// http://marijnhaverbeke.nl/git/acorn +// https://github.com/marijnh/acorn.git +// +// Please use the [github bug tracker][ghbt] to report issues. +// +// [ghbt]: https://github.com/marijnh/acorn/issues + +(function(exports) { + "use strict"; + + exports.version = "0.0.1"; + + // The main exported interface (under `window.acorn` when in the + // browser) is a `parse` function that takes a code string and + // returns an abstract syntax tree as specified by [Mozilla parser + // API][api], with the caveat that the SpiderMonkey-specific syntax + // (`let`, `yield`, inline XML, etc) is not recognized. + // + // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API + + var options, input, inputLen, sourceFile; + + exports.parse = function(inpt, opts) { + input = String(inpt); inputLen = input.length; + options = opts || {}; + for (var opt in defaultOptions) if (!options.hasOwnProperty(opt)) + options[opt] = defaultOptions[opt]; + sourceFile = options.sourceFile || null; + return parseTopLevel(options.program); + }; + + // A second optional argument can be given to further configure + // the parser process. These options are recognized: + + var defaultOptions = exports.defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must + // be either 3 or 5. This + // influences support for strict mode, the set of reserved words, and + // support for getters and setter. + ecmaVersion: 5, + // Turn on `strictSemicolons` to prevent the parser from doing + // automatic semicolon insertion. + strictSemicolons: false, + // When `allowTrailingCommas` is false, the parser will not allow + // trailing commas in array and object literals. + allowTrailingCommas: true, + // By default, reserved words are not enforced. Enable + // `forbidReserved` to enforce them. + forbidReserved: false, + // When `trackComments` is turned on, the parser will attach + // `commentsBefore` and `commentsAfter` properties to AST nodes + // holding arrays of strings. A single comment may appear in both + // a `commentsBefore` and `commentsAfter` array (of the nodes + // after and before it), but never twice in the before (or after) + // array of different nodes. + trackComments: false, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `location` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null + }; + + // The `getLineInfo` function is mostly useful when the + // `locations` option is off (for performance reasons) and you + // want to find the line/column position for a given character + // offset. `input` should be the code string that the offset refers + // into. + + var getLineInfo = exports.getLineInfo = function(input, offset) { + for (var line = 1, cur = 0;;) { + lineBreak.lastIndex = cur; + var match = lineBreak.exec(input); + if (match && match.index < offset) { + ++line; + cur = match.index + match[0].length; + } else break; + } + return {line: line, column: offset - cur}; + }; + + // Acorn is organized as a tokenizer and a recursive-descent parser. + // Both use (closure-)global variables to keep their state and + // communicate. We already saw the `options`, `input`, and + // `inputLen` variables above (set in `parse`). + + // The current position of the tokenizer in the input. + + var tokPos; + + // The start and end offsets of the current token. + + var tokStart, tokEnd; + + // When `options.locations` is true, these hold objects + // containing the tokens start and end line/column pairs. + + var tokStartLoc, tokEndLoc; + + // The type and value of the current token. Token types are objects, + // named by variables against which they can be compared, and + // holding properties that describe them (indicating, for example, + // the precedence of an infix operator, and the original name of a + // keyword token). The kind of value that's held in `tokVal` depends + // on the type of the token. For literals, it is the literal value, + // for operators, the operator name, and so on. + + var tokType, tokVal; + + // These are used to hold arrays of comments when + // `options.trackComments` is true. + + var tokCommentsBefore, tokCommentsAfter; + + // Interal state for the tokenizer. To distinguish between division + // operators and regular expressions, it remembers whether the last + // token was one that is allowed to be followed by an expression. + // (If it is, a slash is probably a regexp, if it isn't it's a + // division operator. See the `parseStatement` function for a + // caveat.) + + var tokRegexpAllowed, tokComments; + + // When `options.locations` is true, these are used to keep + // track of the current line, and know when a new line has been + // entered. See the `curLineLoc` function. + + var tokCurLine, tokLineStart, tokLineStartNext; + + // These store the position of the previous token, which is useful + // when finishing a node and assigning its `end` position. + + var lastStart, lastEnd, lastEndLoc; + + // This is the parser's state. `inFunction` is used to reject + // `return` statements outside of functions, `labels` to verify that + // `break` and `continue` have somewhere to jump to, and `strict` + // indicates whether strict mode is on. + + var inFunction, labels, strict; + + // This function is used to raise exceptions on parse errors. It + // takes either a `{line, column}` object or an offset integer (into + // the current `input`) as `pos` argument. It attaches the position + // to the end of the error message, and then raises a `SyntaxError` + // with that message. + + function raise(pos, message) { + if (typeof pos == "number") pos = getLineInfo(input, pos); + message += " (" + pos.line + ":" + pos.column + ")"; + throw new SyntaxError(message); + } + + // ## Token types + + // The assignment of fine-grained, information-carrying type objects + // allows the tokenizer to store the information it has about a + // token in a way that is very cheap for the parser to look up. + + // All token type variables start with an underscore, to make them + // easy to recognize. + + // These are the general types. The `type` property is only used to + // make them recognizeable when debugging. + + var _num = {type: "num"}, _regexp = {type: "regexp"}, _string = {type: "string"}; + var _name = {type: "name"}, _eof = {type: "eof"}; + + // Keyword tokens. The `keyword` property (also used in keyword-like + // operators) indicates that the token originated from an + // identifier-like word, which is used when parsing property names. + // + // The `beforeExpr` property is used to disambiguate between regular + // expressions and divisions. It is set on all token types that can + // be followed by an expression (thus, a slash after them would be a + // regular expression). + // + // `isLoop` marks a keyword as starting a loop, which is important + // to know when parsing a label, in order to allow or disallow + // continue jumps to that label. + + var _break = {keyword: "break"}, _case = {keyword: "case", beforeExpr: true}, _catch = {keyword: "catch"}; + var _continue = {keyword: "continue"}, _debugger = {keyword: "debugger"}, _default = {keyword: "default"}; + var _do = {keyword: "do", isLoop: true}, _else = {keyword: "else", beforeExpr: true}; + var _finally = {keyword: "finally"}, _for = {keyword: "for", isLoop: true}, _function = {keyword: "function"}; + var _if = {keyword: "if"}, _return = {keyword: "return", beforeExpr: true}, _switch = {keyword: "switch"}; + var _throw = {keyword: "throw", beforeExpr: true}, _try = {keyword: "try"}, _var = {keyword: "var"}; + var _while = {keyword: "while", isLoop: true}, _with = {keyword: "with"}, _new = {keyword: "new", beforeExpr: true}; + var _this = {keyword: "this"}; + + // The keywords that denote values. + + var _null = {keyword: "null", atomValue: null}, _true = {keyword: "true", atomValue: true}; + var _false = {keyword: "false", atomValue: false}; + + // Some keywords are treated as regular operators. `in` sometimes + // (when parsing `for`) needs to be tested against specifically, so + // we assign a variable name to it for quick comparing. + + var _in = {keyword: "in", binop: 7, beforeExpr: true}; + + // Map keyword names to token types. + + var keywordTypes = {"break": _break, "case": _case, "catch": _catch, + "continue": _continue, "debugger": _debugger, "default": _default, + "do": _do, "else": _else, "finally": _finally, "for": _for, + "function": _function, "if": _if, "return": _return, "switch": _switch, + "throw": _throw, "try": _try, "var": _var, "while": _while, "with": _with, + "null": _null, "true": _true, "false": _false, "new": _new, "in": _in, + "instanceof": {keyword: "instanceof", binop: 7}, "this": _this, + "typeof": {keyword: "typeof", prefix: true}, + "void": {keyword: "void", prefix: true}, + "delete": {keyword: "delete", prefix: true}}; + + // Punctuation token types. Again, the `type` property is purely for debugging. + + var _bracketL = {type: "[", beforeExpr: true}, _bracketR = {type: "]"}, _braceL = {type: "{", beforeExpr: true}; + var _braceR = {type: "}"}, _parenL = {type: "(", beforeExpr: true}, _parenR = {type: ")"}; + var _comma = {type: ",", beforeExpr: true}, _semi = {type: ";", beforeExpr: true}; + var _colon = {type: ":", beforeExpr: true}, _dot = {type: "."}, _question = {type: "?", beforeExpr: true}; + + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. `isUpdate` specifies that the node produced by + // the operator should be of type UpdateExpression rather than + // simply UnaryExpression (`++` and `--`). + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + + var _slash = {binop: 10, beforeExpr: true}, _eq = {isAssign: true, beforeExpr: true}; + var _assign = {isAssign: true, beforeExpr: true}, _plusmin = {binop: 9, prefix: true, beforeExpr: true}; + var _incdec = {postfix: true, prefix: true, isUpdate: true}, _prefix = {prefix: true, beforeExpr: true}; + var _bin1 = {binop: 1, beforeExpr: true}, _bin2 = {binop: 2, beforeExpr: true}; + var _bin3 = {binop: 3, beforeExpr: true}, _bin4 = {binop: 4, beforeExpr: true}; + var _bin5 = {binop: 5, beforeExpr: true}, _bin6 = {binop: 6, beforeExpr: true}; + var _bin7 = {binop: 7, beforeExpr: true}, _bin8 = {binop: 8, beforeExpr: true}; + var _bin10 = {binop: 10, beforeExpr: true}; + + // This is a trick taken from Esprima. It turns out that, on + // non-Chrome browsers, to check whether a string is in a set, a + // predicate containing a big ugly `switch` statement is faster than + // a regular expression, and on Chrome the two are about on par. + // This function uses `eval` (non-lexical) to produce such a + // predicate from a space-separated string of words. + // + // It starts by sorting the words by length. + + function makePredicate(words) { + words = words.split(" "); + var f = "", cats = []; + out: for (var i = 0; i < words.length; ++i) { + for (var j = 0; j < cats.length; ++j) + if (cats[j][0].length == words[i].length) { + cats[j].push(words[i]); + continue out; + } + cats.push([words[i]]); + } + function compareTo(arr) { + if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";"; + f += "switch(str){"; + for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":"; + f += "return true}return false;"; + } + + // When there are more than three length categories, an outer + // switch first dispatches on the lengths, to save on comparisons. + + if (cats.length > 3) { + cats.sort(function(a, b) {return b.length - a.length;}); + f += "switch(str.length){"; + for (var i = 0; i < cats.length; ++i) { + var cat = cats[i]; + f += "case " + cat[0].length + ":"; + compareTo(cat); + } + f += "}"; + + // Otherwise, simply generate a flat `switch` statement. + + } else { + compareTo(words); + } + return new Function("str", f); + } + + // The ECMAScript 3 reserved word list. + + var isReservedWord3 = makePredicate("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile"); + + // ECMAScript 5 reserved words. + + var isReservedWord5 = makePredicate("class enum extends super const export import"); + + // The additional reserved words in strict mode. + + var isStrictReservedWord = makePredicate("implements interface let package private protected public static yield"); + + // The forbidden variable names in strict mode. + + var isStrictBadIdWord = makePredicate("eval arguments"); + + // And the keywords. + + var isKeyword = makePredicate("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"); + + // ## Character categories + + // Big ugly regular expressions that match characters in the + // whitespace, identifier, and identifier-start categories. These + // are only applied when a character is found to actually have a + // code point above 128. + + var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/; + var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; + var nonASCIIidentifierChars = "\u0371-\u0374\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; + var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); + var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + + // Whether a single character denotes a newline. + + var newline = /[\n\r\u2028\u2029]/; + + // Matches a whole line break (where CRLF is considered a single + // line break). Used to count lines. + + var lineBreak = /\r\n|[\n\r\u2028\u2029]/g; + + // Test whether a given character code starts an identifier. + + function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code < 91) return true; + if (code < 97) return code === 95; + if (code < 123)return true; + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + + // Test whether a given character is part of an identifier. + + function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code < 91) return true; + if (code < 97) return code === 95; + if (code < 123)return true; + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + + // ## Tokenizer + + // These are used when `options.locations` is on, in order to track + // the current line number and start of line offset, in order to set + // `tokStartLoc` and `tokEndLoc`. + + function nextLineStart() { + lineBreak.lastIndex = tokLineStart; + var match = lineBreak.exec(input); + return match ? match.index + match[0].length : input.length + 1; + } + + function curLineLoc() { + while (tokLineStartNext <= tokPos) { + ++tokCurLine; + tokLineStart = tokLineStartNext; + tokLineStartNext = nextLineStart(); + } + return {line: tokCurLine, column: tokPos - tokLineStart}; + } + + // Reset the token state. Used at the start of a parse. + + function initTokenState() { + tokCurLine = 1; + tokPos = tokLineStart = 0; + tokLineStartNext = nextLineStart(); + tokRegexpAllowed = true; + tokComments = null; + skipSpace(); + } + + // Called at the end of every token. Sets `tokEnd`, `tokVal`, + // `tokCommentsAfter`, and `tokRegexpAllowed`, and skips the space + // after the token, so that the next one's `tokStart` will point at + // the right position. + + function finishToken(type, val) { + tokEnd = tokPos; + if (options.locations) tokEndLoc = curLineLoc(); + tokType = type; + skipSpace(); + tokVal = val; + tokCommentsAfter = tokComments; + tokRegexpAllowed = type.beforeExpr; + } + + function skipBlockComment() { + var end = input.indexOf("*/", tokPos += 2); + if (end === -1) raise(tokPos - 2, "Unterminated comment"); + if (options.trackComments) + (tokComments || (tokComments = [])).push(input.slice(tokPos, end)); + tokPos = end + 2; + } + + function skipLineComment() { + var start = tokPos; + var ch = input.charCodeAt(tokPos+=2); + while (tokPos < inputLen && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8329) { + ++tokPos; + ch = input.charCodeAt(tokPos); + } + (tokComments || (tokComments = [])).push(input.slice(start, tokPos)); + } + + // Called at the start of the parse and after every token. Skips + // whitespace and comments, and, if `options.trackComments` is on, + // will store all skipped comments in `tokComments`. + + function skipSpace() { + tokComments = null; + while (tokPos < inputLen) { + var ch = input.charCodeAt(tokPos); + if (ch === 47) { // '/' + var next = input.charCodeAt(tokPos+1); + if (next === 42) { // '*' + skipBlockComment(); + } else if (next === 47) { // '/' + skipLineComment(); + } else break; + } else if (ch < 14 && ch > 8) { + ++tokPos; + } else if (ch === 32 || ch === 160) { // ' ', '\xa0' + ++tokPos; + } else if (ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++tokPos; + } else { + break; + } + } + } + + // ### Token reading + + // This is the function that is called to fetch the next token. It + // is somewhat obscure, because it works in character codes rather + // than characters, and because operator parsing has been inlined + // into it. + // + // All in the name of speed. + // + // The `forceRegexp` parameter is used in the one case where the + // `tokRegexpAllowed` trick does not work. See `parseStatement`. + + function readToken(forceRegexp) { + tokStart = tokPos; + if (options.locations) tokStartLoc = curLineLoc(); + tokCommentsBefore = tokComments; + if (forceRegexp) return readRegexp(); + if (tokPos >= inputLen) return finishToken(_eof); + + var code = input.charCodeAt(tokPos); + // Identifier or keyword. '\uXXXX' sequences are allowed in + // identifiers, so '\' also dispatches to that. + if (isIdentifierStart(code) || code === 92 /* '\' */) return readWord(); + var next = input.charCodeAt(tokPos+1); + + switch(code) { + // The interpretation of a dot depends on whether it is followed + // by a digit. + case 46: // '.' + if (next >= 48 && next <= 57) return readNumber(String.fromCharCode(code)); + ++tokPos; + return finishToken(_dot); + + // Punctuation tokens. + case 40: ++tokPos; return finishToken(_parenL); + case 41: ++tokPos; return finishToken(_parenR); + case 59: ++tokPos; return finishToken(_semi); + case 44: ++tokPos; return finishToken(_comma); + case 91: ++tokPos; return finishToken(_bracketL); + case 93: ++tokPos; return finishToken(_bracketR); + case 123: ++tokPos; return finishToken(_braceL); + case 125: ++tokPos; return finishToken(_braceR); + case 58: ++tokPos; return finishToken(_colon); + case 63: ++tokPos; return finishToken(_question); + + // '0x' is a hexadecimal number. + case 48: // '0' + if (next === 120 || next === 88) return readHexNumber(); + // Anything else beginning with a digit is an integer, octal + // number, or float. + case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9 + return readNumber(String.fromCharCode(code)); + + // Quotes produce strings. + case 34: case 39: // '"', "'" + return readString(code); + + // Operators are parsed inline in tiny state machines. '=' (61) is + // often referred to. `finishOp` simply skips the amount of + // characters it is given as second argument, and returns a token + // of the type given by its first argument. + + case 47: // '/' + if (tokRegexpAllowed) {++tokPos; return readRegexp();} + if (next === 61) return finishOp(_assign, 2); + return finishOp(_slash, 1); + + case 37: case 42: // '%*' + if (next === 61) return finishOp(_assign, 2); + return finishOp(_bin10, 1); + + case 124: case 38: // '|&' + if (next === code) return finishOp(code === 124 ? _bin1 : _bin2, 2); + if (next === 61) return finishOp(_assign, 2); + return finishOp(code === 124 ? _bin3 : _bin5, 1); + + case 94: // '^' + if (next === 61) return finishOp(_assign, 2); + return finishOp(_bin4, 1); + + case 43: case 45: // '+-' + if (next === code) return finishOp(_incdec, 2); + if (next === 61) return finishOp(_assign, 2); + return finishOp(_plusmin, 1); + + case 60: case 62: // '<>' + var size = 1; + if (next === code) { + size = code === 62 && input.charCodeAt(tokPos+2) === 62 ? 3 : 2; + if (input.charCodeAt(tokPos + size) === 61) return finishOp(_assign, size + 1); + return finishOp(_bin8, size); + } + if (next === 61) + size = input.charCodeAt(tokPos+2) === 61 ? 3 : 2; + return finishOp(_bin7, size); + + case 61: case 33: // '=!' + if (next === 61) return finishOp(_bin6, input.charCodeAt(tokPos+2) === 61 ? 3 : 2); + return finishOp(code === 61 ? _eq : _prefix, 1); + + case 126: // '~' + return finishOp(_prefix, 1); + } + + // If we are here, we either found a non-ASCII identifier + // character, or something that's entirely disallowed. + var ch = String.fromCharCode(code); + if (ch === "\\" || nonASCIIidentifierStart.test(ch)) return readWord(); + raise(tokPos, "Unexpected character '" + ch + "'"); + } + + function finishOp(type, size) { + var str = input.slice(tokPos, tokPos + size); + tokPos += size; + finishToken(type, str); + } + + // Parse a regular expression. Some context-awareness is necessary, + // since a '/' inside a '[]' set does not end the expression. + + function readRegexp() { + var content = "", escaped, inClass, start = tokPos; + for (;;) { + if (tokPos >= inputLen) raise(start, "Unterminated regular expression"); + var ch = input.charAt(tokPos); + if (newline.test(ch)) raise(start, "Unterminated regular expression"); + if (!escaped) { + if (ch === "[") inClass = true; + else if (ch === "]" && inClass) inClass = false; + else if (ch === "/" && !inClass) break; + escaped = ch === "\\"; + } else escaped = false; + ++tokPos; + } + var content = input.slice(start, tokPos); + ++tokPos; + // Need to use `readWord1` because '\uXXXX' sequences are allowed + // here (don't ask). + var mods = readWord1(); + if (mods && !/^[gmsiy]*$/.test(mods)) raise(start, "Invalid regexp flag"); + return finishToken(_regexp, new RegExp(content, mods)); + } + + // Read an integer in the given radix. Return null if zero digits + // were read, the integer value otherwise. When `len` is given, this + // will return `null` unless the integer has exactly `len` digits. + + function readInt(radix, len) { + var start = tokPos, total = 0; + for (;;) { + var code = input.charCodeAt(tokPos), val; + if (code >= 97) val = code - 97 + 10; // a + else if (code >= 65) val = code - 65 + 10; // A + else if (code >= 48 && code <= 57) val = code - 48; // 0-9 + else val = Infinity; + if (val >= radix) break; + ++tokPos; + total = total * radix + val; + } + if (tokPos === start || len != null && tokPos - start !== len) return null; + + return total; + } + + function readHexNumber() { + tokPos += 2; // 0x + var val = readInt(16); + if (val == null) raise(tokStart + 2, "Expected hexadecimal number"); + if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number"); + return finishToken(_num, val); + } + + // Read an integer, octal integer, or floating-point number. + + function readNumber(ch) { + var start = tokPos, isFloat = ch === "."; + if (!isFloat && readInt(10) == null) raise(start, "Invalid number"); + if (isFloat || input.charAt(tokPos) === ".") { + var next = input.charAt(++tokPos); + if (next === "-" || next === "+") ++tokPos; + if (readInt(10) === null && ch === ".") raise(start, "Invalid number"); + isFloat = true; + } + if (/e/i.test(input.charAt(tokPos))) { + var next = input.charAt(++tokPos); + if (next === "-" || next === "+") ++tokPos; + if (readInt(10) === null) raise(start, "Invalid number") + isFloat = true; + } + if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number"); + + var str = input.slice(start, tokPos), val; + if (isFloat) val = parseFloat(str); + else if (ch !== "0" || str.length === 1) val = parseInt(str, 10); + else if (/[89]/.test(str) || strict) raise(start, "Invalid number"); + else val = parseInt(str, 8); + return finishToken(_num, val); + } + + // Read a string value, interpreting backslash-escapes. + + function readString(quote) { + tokPos++; + var str = []; + for (;;) { + if (tokPos >= inputLen) raise(tokStart, "Unterminated string constant"); + var ch = input.charCodeAt(tokPos); + if (ch === quote) { + ++tokPos; + return finishToken(_string, String.fromCharCode.apply(null, str)); + } + if (ch === 92) { // '\' + ch = input.charCodeAt(++tokPos); + var octal = /^[0-7]+/.exec(input.slice(tokPos, tokPos + 3)); + if (octal) octal = octal[0]; + while (octal && parseInt(octal, 8) > 255) octal = octal.slice(0, octal.length - 1); + if (octal === "0") octal = null; + ++tokPos; + if (octal) { + if (strict) raise(tokPos - 2, "Octal literal in strict mode"); + str.push(parseInt(octal, 8)); + tokPos += octal.length - 1; + } else { + switch (ch) { + case 110: str.push(10); break; // 'n' -> '\n' + case 114: str.push(13); break; // 'r' -> '\r' + case 120: str.push(readHexChar(2)); break; // 'x' + case 117: str.push(readHexChar(4)); break; // 'u' + case 85: str.push(readHexChar(8)); break; // 'U' + case 116: str.push(9); break; // 't' -> '\t' + case 98: str.push(8); break; // 'b' -> '\b' + case 118: str.push(11); break; // 'v' -> '\u000b' + case 102: str.push(12); break; // 'f' -> '\f' + case 48: str.push(0); break; // 0 -> '\0' + case 13: if (input.charCodeAt(tokPos) === 10) ++tokPos; // '\r\n' + case 10: break; // ' \n' + default: str.push(ch); break; + } + } + } else { + if (ch === 13 || ch === 10 || ch === 8232 || ch === 8329) raise(tokStart, "Unterminated string constant"); + if (ch !== 92) str.push(ch); // '\' + ++tokPos; + } + } + } + + // Used to read character escape sequences ('\x', '\u', '\U'). + + function readHexChar(len) { + var n = readInt(16, len); + if (n === null) raise(tokStart, "Bad character escape sequence"); + return n; + } + + // Used to signal to callers of `readWord1` whether the word + // contained any escape sequences. This is needed because words with + // escape sequences must not be interpreted as keywords. + + var containsEsc; + + // Read an identifier, and return it as a string. Sets `containsEsc` + // to whether the word contained a '\u' escape. + // + // Only builds up the word character-by-character when it actually + // containeds an escape, as a micro-optimization. + + function readWord1() { + containsEsc = false; + var word, first = true, start = tokPos; + for (;;) { + var ch = input.charCodeAt(tokPos); + if (isIdentifierChar(ch)) { + if (containsEsc) word += input.charAt(tokPos); + ++tokPos; + } else if (ch === 92) { // "\" + if (!containsEsc) word = input.slice(start, tokPos); + containsEsc = true; + if (input.charCodeAt(++tokPos) != 117) // "u" + raise(tokPos, "Expecting Unicode escape sequence \\uXXXX"); + ++tokPos; + var esc = readHexChar(4); + var escStr = String.fromCharCode(esc); + if (!escStr) raise(tokPos - 1, "Invalid Unicode escape"); + if (!(first ? isIdentifierStart(esc) : isIdentifierChar(esc))) + raise(tokPos - 4, "Invalid Unicode escape"); + word += escStr; + } else { + break; + } + first = false; + } + return containsEsc ? word : input.slice(start, tokPos); + } + + // Read an identifier or keyword token. Will check for reserved + // words when necessary. + + function readWord() { + var word = readWord1(); + var type = _name; + if (!containsEsc) { + if (isKeyword(word)) type = keywordTypes[word]; + else if (options.forbidReserved && + (options.ecmaVersion === 3 ? isReservedWord3 : isReservedWord5)(word) || + strict && isStrictReservedWord(word)) + raise(tokStart, "The keyword '" + word + "' is reserved"); + } + return finishToken(type, word); + } + + // ## Parser + + // A recursive descent parser operates by defining functions for all + // syntactic elements, and recursively calling those, each function + // advancing the input stream and returning an AST node. Precedence + // of constructs (for example, the fact that `!x[1]` means `!(x[1])` + // instead of `(!x)[1]` is handled by the fact that the parser + // function that parses unary prefix operators is called first, and + // in turn calls the function that parses `[]` subscripts — that + // way, it'll receive the node for `x[1]` already parsed, and wraps + // *that* in the unary operator node. + // + // Acorn uses an [operator precedence parser][opp] to handle binary + // operator precedence, because it is much more compact than using + // the technique outlined above, which uses different, nesting + // functions to specify precedence, for all of the ten binary + // precedence levels that JavaScript defines. + // + // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser + + // ### Parser utilities + + // Continue to the next token. + + function next() { + lastStart = tokStart; + lastEnd = tokEnd; + lastEndLoc = tokEndLoc; + readToken(); + } + + // Enter strict mode. Re-reads the next token to please pedantic + // tests ("use strict"; 010; -- should fail). + + function setStrict(strct) { + strict = strct; + tokPos = lastEnd; + skipSpace(); + readToken(); + } + + // Start an AST node, attaching a start offset and optionally a + // `commentsBefore` property to it. + + function startNode() { + var node = {type: null, start: tokStart, end: null}; + if (options.trackComments && tokCommentsBefore) { + node.commentsBefore = tokCommentsBefore; + tokCommentsBefore = null; + } + if (options.locations) + node.loc = {start: tokStartLoc, end: null, source: sourceFile}; + if (options.ranges) + node.range = [tokStart, 0]; + return node; + } + + // Start a node whose start offset/comments information should be + // based on the start of another node. For example, a binary + // operator node is only started after its left-hand side has + // already been parsed. + + function startNodeFrom(other) { + var node = {type: null, start: other.start}; + if (other.commentsBefore) { + node.commentsBefore = other.commentsBefore; + other.commentsBefore = null; + } + if (options.locations) + node.loc = {start: other.loc.start, end: null, source: other.loc.source}; + if (options.ranges) + node.range = [other.range[0], 0]; + + return node; + } + + // Finish an AST node, adding `type`, `end`, and `commentsAfter` + // properties. + // + // We keep track of the last node that we finished, in order + // 'bubble' `commentsAfter` properties up to the biggest node. I.e. + // in '`1 + 1 // foo', the comment should be attached to the binary + // operator node, not the second literal node. + + var lastFinishedNode; + + function finishNode(node, type) { + node.type = type; + node.end = lastEnd; + if (options.trackComments) { + if (tokCommentsAfter) { + node.commentsAfter = tokCommentsAfter; + tokCommentsAfter = null; + } else if (lastFinishedNode && lastFinishedNode.end === lastEnd) { + node.commentsAfter = lastFinishedNode.commentsAfter; + lastFinishedNode.commentsAfter = null; + } + lastFinishedNode = node; + } + if (options.locations) + node.loc.end = lastEndLoc; + if (options.ranges) + node.range[1] = lastEnd; + return node; + } + + // Test whether a statement node is the string literal `"use strict"`. + + function isUseStrict(stmt) { + return options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && + stmt.expression.type === "Literal" && stmt.expression.value === "use strict"; + } + + // Predicate that tests whether the next token is of the given + // type, and if yes, consumes it as a side effect. + + function eat(type) { + if (tokType === type) { + next(); + return true; + } + } + + // Test whether a semicolon can be inserted at the current position. + + function canInsertSemicolon() { + return !options.strictSemicolons && + (tokType === _eof || tokType === _braceR || newline.test(input.slice(lastEnd, tokStart))); + } + + // Consume a semicolon, or, failing that, see if we are allowed to + // pretend that there is a semicolon at this position. + + function semicolon() { + if (!eat(_semi) && !canInsertSemicolon()) unexpected(); + } + + // Expect a token of a given type. If found, consume it, otherwise, + // raise an unexpected token error. + + function expect(type) { + if (tokType === type) next(); + else unexpected(); + } + + // Raise an unexpected token error. + + function unexpected() { + raise(tokStart, "Unexpected token"); + } + + // Verify that a node is an lval — something that can be assigned + // to. + + function checkLVal(expr) { + if (expr.type !== "Identifier" && expr.type !== "MemberExpression") + raise(expr.start, "Assigning to rvalue"); + if (strict && expr.type === "Identifier" && isStrictBadIdWord(expr.name)) + raise(expr.start, "Assigning to " + expr.name + " in strict mode"); + } + + // ### Statement parsing + + // Parse a program. Initializes the parser, reads any number of + // statements, and wraps them in a Program node. Optionally takes a + // `program` argument. If present, the statements will be appended + // to its body instead of creating a new node. + + function parseTopLevel(program) { + initTokenState(); + lastStart = lastEnd = tokPos; + if (options.locations) lastEndLoc = curLineLoc(); + inFunction = strict = null; + labels = []; + readToken(); + + var node = program || startNode(), first = true; + if (!program) node.body = []; + while (tokType !== _eof) { + var stmt = parseStatement(); + node.body.push(stmt); + if (first && isUseStrict(stmt)) setStrict(true); + first = false; + } + return finishNode(node, "Program"); + }; + + var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; + + // Parse a single statement. + // + // If expecting a statement and finding a slash operator, parse a + // regular expression literal. This is to handle cases like + // `if (foo) /blah/.exec(foo);`, where looking at the previous token + // does not help. + + function parseStatement() { + if (tokType === _slash) + readToken(true); + + var starttype = tokType, node = startNode(); + + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. + + switch (starttype) { + case _break: case _continue: + next(); + var isBreak = starttype === _break; + if (eat(_semi) || canInsertSemicolon()) node.label = null; + else if (tokType !== _name) unexpected(); + else { + node.label = parseIdent(); + semicolon(); + } + + // Verify that there is an actual destination to break or + // continue to. + for (var i = 0; i < labels.length; ++i) { + var lab = labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) break; + if (node.label && isBreak) break; + } + } + if (i === labels.length) raise(node.start, "Unsyntactic " + starttype.keyword); + return finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); + + case _debugger: + next(); + return finishNode(node, "DebuggerStatement"); + + case _do: + next(); + labels.push(loopLabel); + node.body = parseStatement(); + labels.pop(); + expect(_while); + node.test = parseParenExpression(); + semicolon(); + return finishNode(node, "DoWhileStatement"); + + // Disambiguating between a `for` and a `for`/`in` loop is + // non-trivial. Basically, we have to parse the init `var` + // statement or expression, disallowing the `in` operator (see + // the second parameter to `parseExpression`), and then check + // whether the next token is `in`. When there is no init part + // (semicolon immediately after the opening parenthesis), it is + // a regular `for` loop. + + case _for: + next(); + labels.push(loopLabel); + expect(_parenL); + if (tokType === _semi) return parseFor(node, null); + if (tokType === _var) { + var init = startNode(); + next(); + parseVar(init, true); + if (init.declarations.length === 1 && eat(_in)) + return parseForIn(node, init); + return parseFor(node, init); + } + var init = parseExpression(false, true); + if (eat(_in)) {checkLVal(init); return parseForIn(node, init);} + return parseFor(node, init); + + case _function: + next(); + return parseFunction(node, true); + + case _if: + next(); + node.test = parseParenExpression(); + node.consequent = parseStatement(); + node.alternate = eat(_else) ? parseStatement() : null; + return finishNode(node, "IfStatement"); + + case _return: + if (!inFunction) raise(tokStart, "'return' outside of function"); + next(); + + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. + + if (eat(_semi) || canInsertSemicolon()) node.argument = null; + else { node.argument = parseExpression(); semicolon(); } + return finishNode(node, "ReturnStatement"); + + case _switch: + next(); + node.discriminant = parseParenExpression(); + node.cases = []; + expect(_braceL); + labels.push(switchLabel); + + // Statements under must be grouped (by label) in SwitchCase + // nodes. `cur` is used to keep the node that we are currently + // adding statements to. + + for (var cur, sawDefault; tokType != _braceR;) { + if (tokType === _case || tokType === _default) { + var isCase = tokType === _case; + if (cur) finishNode(cur, "SwitchCase"); + node.cases.push(cur = startNode()); + cur.consequent = []; + next(); + if (isCase) cur.test = parseExpression(); + else { + if (sawDefault) raise(lastStart, "Multiple default clauses"); sawDefault = true; + cur.test = null; + } + expect(_colon); + } else { + if (!cur) unexpected(); + cur.consequent.push(parseStatement()); + } + } + if (cur) finishNode(cur, "SwitchCase"); + next(); // Closing brace + labels.pop(); + return finishNode(node, "SwitchStatement"); + + case _throw: + next(); + if (newline.test(input.slice(lastEnd, tokStart))) + raise(lastEnd, "Illegal newline after throw"); + node.argument = parseExpression(); + return finishNode(node, "ThrowStatement"); + + case _try: + next(); + node.block = parseBlock(); + node.handlers = []; + while (tokType === _catch) { + var clause = startNode(); + next(); + expect(_parenL); + clause.param = parseIdent(); + if (strict && isStrictBadIdWord(clause.param.name)) + raise(clause.param.start, "Binding " + clause.param.name + " in strict mode"); + expect(_parenR); + clause.guard = null; + clause.body = parseBlock(); + node.handlers.push(finishNode(clause, "CatchClause")); + } + node.finalizer = eat(_finally) ? parseBlock() : null; + if (!node.handlers.length && !node.finalizer) + raise(node.start, "Missing catch or finally clause"); + return finishNode(node, "TryStatement"); + + case _var: + next(); + node = parseVar(node); + semicolon(); + return node; + + case _while: + next(); + node.test = parseParenExpression(); + labels.push(loopLabel); + node.body = parseStatement(); + labels.pop(); + return finishNode(node, "WhileStatement"); + + case _with: + if (strict) raise(tokStart, "'with' in strict mode"); + next(); + node.object = parseParenExpression(); + node.body = parseStatement(); + return finishNode(node, "WithStatement"); + + case _braceL: + return parseBlock(); + + case _semi: + next(); + return finishNode(node, "EmptyStatement"); + + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + + default: + var maybeName = tokVal, expr = parseExpression(); + if (starttype === _name && expr.type === "Identifier" && eat(_colon)) { + for (var i = 0; i < labels.length; ++i) + if (labels[i].name === maybeName) raise(expr.start, "Label '" + maybeName + "' is already declared"); + var kind = tokType.isLoop ? "loop" : tokType === _switch ? "switch" : null; + labels.push({name: maybeName, kind: kind}); + node.body = parseStatement(); + node.label = expr; + return finishNode(node, "LabeledStatement"); + } else { + node.expression = expr; + semicolon(); + return finishNode(node, "ExpressionStatement"); + } + } + } + + // Used for constructs like `switch` and `if` that insist on + // parentheses around their expression. + + function parseParenExpression() { + expect(_parenL); + var val = parseExpression(); + expect(_parenR); + return val; + } + + // Parse a semicolon-enclosed block of statements, handling `"use + // strict"` declarations when `allowStrict` is true (used for + // function bodies). + + function parseBlock(allowStrict) { + var node = startNode(), first = true, strict = false, oldStrict; + node.body = []; + expect(_braceL); + while (!eat(_braceR)) { + var stmt = parseStatement(); + node.body.push(stmt); + if (first && isUseStrict(stmt)) { + oldStrict = strict; + setStrict(strict = true); + } + first = false + } + if (strict && !oldStrict) setStrict(false); + return finishNode(node, "BlockStatement"); + } + + // Parse a regular `for` loop. The disambiguation code in + // `parseStatement` will already have parsed the init statement or + // expression. + + function parseFor(node, init) { + node.init = init; + expect(_semi); + node.test = tokType === _semi ? null : parseExpression(); + expect(_semi); + node.update = tokType === _parenR ? null : parseExpression(); + expect(_parenR); + node.body = parseStatement(); + labels.pop(); + return finishNode(node, "ForStatement"); + } + + // Parse a `for`/`in` loop. + + function parseForIn(node, init) { + node.left = init; + node.right = parseExpression(); + expect(_parenR); + node.body = parseStatement(); + labels.pop(); + return finishNode(node, "ForInStatement"); + } + + // Parse a list of variable declarations. + + function parseVar(node, noIn) { + node.declarations = []; + node.kind = "var"; + for (;;) { + var decl = startNode(); + decl.id = parseIdent(); + if (strict && isStrictBadIdWord(decl.id.name)) + raise(decl.id.start, "Binding " + decl.id.name + " in strict mode"); + decl.init = eat(_eq) ? parseExpression(true, noIn) : null; + node.declarations.push(finishNode(decl, "VariableDeclarator")); + if (!eat(_comma)) break; + } + return finishNode(node, "VariableDeclaration"); + } + + // ### Expression parsing + + // These nest, from the most general expression type at the top to + // 'atomic', nondivisible expression types at the bottom. Most of + // the functions will simply let the function(s) below them parse, + // and, *if* the syntactic construct they handle is present, wrap + // the AST node that the inner parser gave them in another node. + + // Parse a full expression. The arguments are used to forbid comma + // sequences (in argument lists, array literals, or object literals) + // or the `in` operator (in for loops initalization expressions). + + function parseExpression(noComma, noIn) { + var expr = parseMaybeAssign(noIn); + if (!noComma && tokType === _comma) { + var node = startNodeFrom(expr); + node.expressions = [expr]; + while (eat(_comma)) node.expressions.push(parseMaybeAssign(noIn)); + return finishNode(node, "SequenceExpression"); + } + return expr; + } + + // Parse an assignment expression. This includes applications of + // operators like `+=`. + + function parseMaybeAssign(noIn) { + var left = parseMaybeConditional(noIn); + if (tokType.isAssign) { + var node = startNodeFrom(left); + node.operator = tokVal; + node.left = left; + next(); + node.right = parseMaybeAssign(noIn); + checkLVal(left); + return finishNode(node, "AssignmentExpression"); + } + return left; + } + + // Parse a ternary conditional (`?:`) operator. + + function parseMaybeConditional(noIn) { + var expr = parseExprOps(noIn); + if (eat(_question)) { + var node = startNodeFrom(expr); + node.test = expr; + node.consequent = parseExpression(true); + expect(_colon); + node.alternate = parseExpression(true, noIn); + return finishNode(node, "ConditionalExpression"); + } + return expr; + } + + // Start the precedence parser. + + function parseExprOps(noIn) { + return parseExprOp(parseMaybeUnary(noIn), -1, noIn); + } + + // Parse binary operators with the operator precedence parsing + // algorithm. `left` is the left-hand side of the operator. + // `minPrec` provides context that allows the function to stop and + // defer further parser to one of its callers when it encounters an + // operator that has a lower precedence than the set it is parsing. + + function parseExprOp(left, minPrec, noIn) { + var prec = tokType.binop; + if (prec != null && (!noIn || tokType !== _in)) { + if (prec > minPrec) { + var node = startNodeFrom(left); + node.left = left; + node.operator = tokVal; + next(); + node.right = parseExprOp(parseMaybeUnary(noIn), prec, noIn); + var node = finishNode(node, /&&|\|\|/.test(node.operator) ? "LogicalExpression" : "BinaryExpression"); + return parseExprOp(node, minPrec, noIn); + } + } + return left; + } + + // Parse unary operators, both prefix and postfix. + + function parseMaybeUnary(noIn) { + if (tokType.prefix) { + var node = startNode(), update = tokType.isUpdate; + node.operator = tokVal; + node.prefix = true; + next(); + node.argument = parseMaybeUnary(noIn); + if (update) checkLVal(node.argument); + else if (strict && node.operator === "delete" && + node.argument.type === "Identifier") + raise(node.start, "Deleting local variable in strict mode"); + return finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } + var expr = parseExprSubscripts(); + while (tokType.postfix && !canInsertSemicolon()) { + var node = startNodeFrom(expr); + node.operator = tokVal; + node.prefix = false; + node.argument = expr; + checkLVal(expr); + next(); + expr = finishNode(node, "UpdateExpression"); + } + return expr; + } + + // Parse call, dot, and `[]`-subscript expressions. + + function parseExprSubscripts() { + return parseSubscripts(parseExprAtom()); + } + + function parseSubscripts(base, noCalls) { + if (eat(_dot)) { + var node = startNodeFrom(base); + node.object = base; + node.property = parseIdent(true); + node.computed = false; + return parseSubscripts(finishNode(node, "MemberExpression"), noCalls); + } else if (eat(_bracketL)) { + var node = startNodeFrom(base); + node.object = base; + node.property = parseExpression(); + node.computed = true; + expect(_bracketR); + return parseSubscripts(finishNode(node, "MemberExpression"), noCalls); + } else if (!noCalls && eat(_parenL)) { + var node = startNodeFrom(base); + node.callee = base; + node.arguments = parseExprList(_parenR, false); + return parseSubscripts(finishNode(node, "CallExpression"), noCalls); + } else return base; + } + + // Parse an atomic expression — either a single token that is an + // expression, an expression started by a keyword like `function` or + // `new`, or an expression wrapped in punctuation like `()`, `[]`, + // or `{}`. + + function parseExprAtom() { + switch (tokType) { + case _this: + var node = startNode(); + next(); + return finishNode(node, "ThisExpression"); + case _name: + return parseIdent(); + case _num: case _string: case _regexp: + var node = startNode(); + node.value = tokVal; + node.raw = input.slice(tokStart, tokEnd); + next(); + return finishNode(node, "Literal"); + + case _null: case _true: case _false: + var node = startNode(); + node.value = tokType.atomValue; + next(); + return finishNode(node, "Literal"); + + case _parenL: + next(); + var val = parseExpression(); + expect(_parenR); + return val; + + case _bracketL: + var node = startNode(); + next(); + node.elements = parseExprList(_bracketR, true, true); + return finishNode(node, "ArrayExpression"); + + case _braceL: + return parseObj(); + + case _function: + var node = startNode(); + next(); + return parseFunction(node, false); + + case _new: + return parseNew(); + + default: + unexpected(); + } + } + + // New's precedence is slightly tricky. It must allow its argument + // to be a `[]` or dot subscript expression, but not a call — at + // least, not without wrapping it in parentheses. Thus, it uses the + + function parseNew() { + var node = startNode(); + next(); + node.callee = parseSubscripts(parseExprAtom(false), true); + if (eat(_parenL)) node.arguments = parseExprList(_parenR, false); + else node.arguments = []; + return finishNode(node, "NewExpression"); + } + + // Parse an object literal. + + function parseObj() { + var node = startNode(), first = true, sawGetSet = false; + node.properties = []; + next(); + while (!eat(_braceR)) { + if (!first) { + expect(_comma); + if (options.allowTrailingCommas && eat(_braceR)) break; + } else first = false; + + var prop = {key: parsePropertyName()}, isGetSet = false, kind; + if (eat(_colon)) { + prop.value = parseExpression(true); + kind = prop.kind = "init"; + } else if (options.ecmaVersion >= 5 && prop.key.type === "Identifier" && + (prop.key.name === "get" || prop.key.name === "set")) { + isGetSet = sawGetSet = true; + kind = prop.kind = prop.key.name; + prop.key = parsePropertyName(); + if (!tokType === _parenL) unexpected(); + prop.value = parseFunction(startNode(), false); + } else unexpected(); + + // getters and setters are not allowed to clash — either with + // each other or with an init property — and in strict mode, + // init properties are also not allowed to be repeated. + + if (prop.key.type === "Identifier" && (strict || sawGetSet)) { + for (var i = 0; i < node.properties.length; ++i) { + var other = node.properties[i]; + if (other.key.name === prop.key.name) { + var conflict = kind == other.kind || isGetSet && other.kind === "init" || + kind === "init" && (other.kind === "get" || other.kind === "set"); + if (conflict && !strict && kind === "init" && other.kind === "init") conflict = false; + if (conflict) raise(prop.key.start, "Redefinition of property"); + } + } + } + node.properties.push(prop); + } + return finishNode(node, "ObjectExpression"); + } + + function parsePropertyName() { + if (tokType === _num || tokType === _string) return parseExprAtom(); + return parseIdent(true); + } + + // Parse a function declaration or literal (depending on the + // `isStatement` parameter). + + function parseFunction(node, isStatement) { + if (tokType === _name) node.id = parseIdent(); + else if (isStatement) unexpected(); + else node.id = null; + node.params = []; + var first = true; + expect(_parenL); + while (!eat(_parenR)) { + if (!first) expect(_comma); else first = false; + node.params.push(parseIdent()); + } + + // Start a new scope with regard to labels and the `inFunction` + // flag (restore them to their old value afterwards). + var oldInFunc = inFunction, oldLabels = labels; + inFunction = true; labels = []; + node.body = parseBlock(true); + inFunction = oldInFunc; labels = oldLabels; + + // If this is a strict mode function, verify that argument names + // are not repeated, and it does not try to bind the words `eval` + // or `arguments`. + if (strict || node.body.body.length && isUseStrict(node.body.body[0])) { + for (var i = node.id ? -1 : 0; i < node.params.length; ++i) { + var id = i < 0 ? node.id : node.params[i]; + if (isStrictReservedWord(id.name) || isStrictBadIdWord(id.name)) + raise(id.start, "Defining '" + id.name + "' in strict mode"); + if (i >= 0) for (var j = 0; j < i; ++j) if (id.name === node.params[j].name) + raise(id.start, "Argument name clash in strict mode"); + } + } + + return finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression"); + } + + // Parses a comma-separated list of expressions, and returns them as + // an array. `close` is the token type that ends the list, and + // `allowEmpty` can be turned on to allow subsequent commas with + // nothing in between them to be parsed as `null` (which is needed + // for array literals). + + function parseExprList(close, allowTrailingComma, allowEmpty) { + var elts = [], first = true; + while (!eat(close)) { + if (!first) { + expect(_comma); + if (allowTrailingComma && options.allowTrailingCommas && eat(close)) break; + } else first = false; + + if (allowEmpty && tokType === _comma) elts.push(null); + else elts.push(parseExpression(true)); + } + return elts; + } + + // Parse the next token as an identifier. If `liberal` is true (used + // when parsing properties), it will also convert keywords into + // identifiers. + + function parseIdent(liberal) { + var node = startNode(); + node.name = tokType === _name ? tokVal : (liberal && !options.forbidReserved && tokType.keyword) || unexpected(); + next(); + return finishNode(node, "Identifier"); + } + +})(typeof exports === "undefined" ? (window.acorn = {}) : exports); diff --git a/codemirror/test/lint/lint.js b/codemirror/test/lint/lint.js new file mode 100644 index 0000000..01a9d01 --- /dev/null +++ b/codemirror/test/lint/lint.js @@ -0,0 +1,104 @@ +/* + Simple linter, based on the Acorn [1] parser module + + All of the existing linters either cramp my style or have huge + dependencies (Closure). So here's a very simple, non-invasive one + that only spots + + - missing semicolons and trailing commas + - variables or properties that are reserved words + - assigning to a variable you didn't declare + + [1]: https://github.com/marijnh/acorn/ +*/ + +var fs = require("fs"), acorn = require("./acorn.js"), walk = require("./walk.js"); + +var scopePasser = walk.make({ + ScopeBody: function(node, prev, c) { c(node, node.scope); } +}); + +function checkFile(fileName) { + var file = fs.readFileSync(fileName, "utf8"); + var badChar = file.match(/[\x00-\x08\x0b\x0c\x0e-\x19\uFEFF]/); + if (badChar) + fail("Undesirable character " + badChar[0].charCodeAt(0) + " at position " + badChar.index, + {source: fileName}); + + try { + var parsed = acorn.parse(file, { + locations: true, + ecmaVersion: 3, + strictSemicolons: true, + forbidReserved: true, + sourceFile: fileName + }); + } catch (e) { + fail(e.message, {source: fileName}); + return; + } + + var scopes = []; + + walk.simple(parsed, { + ScopeBody: function(node, scope) { + node.scope = scope; + scopes.push(scope); + } + }, walk.scopeVisitor, {vars: Object.create(null)}); + + var ignoredGlobals = Object.create(null); + + function inScope(name, scope) { + for (var cur = scope; cur; cur = cur.prev) + if (name in cur.vars) return true; + } + function checkLHS(node, scope) { + if (node.type == "Identifier" && !(node.name in ignoredGlobals) && + !inScope(node.name, scope)) { + ignoredGlobals[node.name] = true; + fail("Assignment to global variable", node.loc); + } + } + + walk.simple(parsed, { + UpdateExpression: function(node, scope) {checkLHS(node.argument, scope);}, + AssignmentExpression: function(node, scope) {checkLHS(node.left, scope);}, + Identifier: function(node, scope) { + // Mark used identifiers + for (var cur = scope; cur; cur = cur.prev) + if (node.name in cur.vars) { + cur.vars[node.name].used = true; + return; + } + } + }, scopePasser); + + for (var i = 0; i < scopes.length; ++i) { + var scope = scopes[i]; + for (var name in scope.vars) { + var info = scope.vars[name]; + if (!info.used && info.type != "catch clause" && info.type != "function name" && name.charAt(0) != "_") + fail("Unused " + info.type + " " + name, info.node.loc); + } + } +} + +var failed = false; +function fail(msg, pos) { + if (pos.start) msg += " (" + pos.start.line + ":" + pos.start.column + ")"; + console.log(pos.source.match(/[^\/]+$/)[0] + ": " + msg); + failed = true; +} + +function checkDir(dir) { + fs.readdirSync(dir).forEach(function(file) { + var fname = dir + "/" + file; + if (/\.js$/.test(file)) checkFile(fname); + else if (fs.lstatSync(fname).isDirectory()) checkDir(fname); + }); +} + +exports.checkDir = checkDir; +exports.checkFile = checkFile; +exports.success = function() { return !failed; }; diff --git a/codemirror/test/lint/parse-js.js b/codemirror/test/lint/parse-js.js new file mode 100644 index 0000000..c165a27 --- /dev/null +++ b/codemirror/test/lint/parse-js.js @@ -0,0 +1,1372 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + + This version is suitable for Node.js. With minimal changes (the + exports stuff) it should work on any JS platform. + + This file contains the tokenizer/parser. It is a port to JavaScript + of parse-js [1], a JavaScript parser library written in Common Lisp + by Marijn Haverbeke. Thank you Marijn! + + [1] http://marijn.haverbeke.nl/parse-js/ + + Exported functions: + + - tokenizer(code) -- returns a function. Call the returned + function to fetch the next token. + + - parse(code) -- returns an AST of the given JavaScript code. + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2010 (c) Mihai Bazon + Based on parse-js (http://marijn.haverbeke.nl/parse-js/). + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +/* -----[ Tokenizer (constants) ]----- */ + +var KEYWORDS = array_to_hash([ + "break", + "case", + "catch", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "finally", + "for", + "function", + "if", + "in", + "instanceof", + "new", + "return", + "switch", + "throw", + "try", + "typeof", + "var", + "void", + "while", + "with" +]); + +var RESERVED_WORDS = array_to_hash([ + "abstract", + "boolean", + "byte", + "char", + "class", + "double", + "enum", + "export", + "extends", + "final", + "float", + "goto", + "implements", + "import", + "int", + "interface", + "long", + "native", + "package", + "private", + "protected", + "public", + "short", + "static", + "super", + "synchronized", + "throws", + "transient", + "volatile" +]); + +var KEYWORDS_BEFORE_EXPRESSION = array_to_hash([ + "return", + "new", + "delete", + "throw", + "else", + "case" +]); + +var KEYWORDS_ATOM = array_to_hash([ + "false", + "null", + "true", + "undefined" +]); + +var OPERATOR_CHARS = array_to_hash(characters("+-*&%=<>!?|~^")); + +var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i; +var RE_OCT_NUMBER = /^0[0-7]+$/; +var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i; + +var OPERATORS = array_to_hash([ + "in", + "instanceof", + "typeof", + "new", + "void", + "delete", + "++", + "--", + "+", + "-", + "!", + "~", + "&", + "|", + "^", + "*", + "/", + "%", + ">>", + "<<", + ">>>", + "<", + ">", + "<=", + ">=", + "==", + "===", + "!=", + "!==", + "?", + "=", + "+=", + "-=", + "/=", + "*=", + "%=", + ">>=", + "<<=", + ">>>=", + "|=", + "^=", + "&=", + "&&", + "||" +]); + +var WHITESPACE_CHARS = array_to_hash(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000")); + +var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{(,.;:")); + +var PUNC_CHARS = array_to_hash(characters("[]{}(),;:")); + +var REGEXP_MODIFIERS = array_to_hash(characters("gmsiy")); + +/* -----[ Tokenizer ]----- */ + +var UNICODE = { // Unicode 6.1 + letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F0\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"), + combining_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065F\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0859-\\u085B\\u08E4-\\u08FE\\u0900-\\u0903\\u093A-\\u093C\\u093E-\\u094F\\u0951-\\u0957\\u0962\\u0963\\u0981-\\u0983\\u09BC\\u09BE-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CD\\u09D7\\u09E2\\u09E3\\u0A01-\\u0A03\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81-\\u0A83\\u0ABC\\u0ABE-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AE2\\u0AE3\\u0B01-\\u0B03\\u0B3C\\u0B3E-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B62\\u0B63\\u0B82\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD7\\u0C01-\\u0C03\\u0C3E-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0C82\\u0C83\\u0CBC\\u0CBE-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CE2\\u0CE3\\u0D02\\u0D03\\u0D3E-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4D\\u0D57\\u0D62\\u0D63\\u0D82\\u0D83\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F3E\\u0F3F\\u0F71-\\u0F84\\u0F86\\u0F87\\u0F8D-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102B-\\u103E\\u1056-\\u1059\\u105E-\\u1060\\u1062-\\u1064\\u1067-\\u106D\\u1071-\\u1074\\u1082-\\u108D\\u108F\\u109A-\\u109D\\u135D-\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B4-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u192B\\u1930-\\u193B\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A17-\\u1A1B\\u1A55-\\u1A5E\\u1A60-\\u1A7C\\u1A7F\\u1B00-\\u1B04\\u1B34-\\u1B44\\u1B6B-\\u1B73\\u1B80-\\u1B82\\u1BA1-\\u1BAD\\u1BE6-\\u1BF3\\u1C24-\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE8\\u1CED\\u1CF2-\\u1CF4\\u1DC0-\\u1DE6\\u1DFC-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2D7F\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA674-\\uA67D\\uA69F\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA823-\\uA827\\uA880\\uA881\\uA8B4-\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA953\\uA980-\\uA983\\uA9B3-\\uA9C0\\uAA29-\\uAA36\\uAA43\\uAA4C\\uAA4D\\uAA7B\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uAAEB-\\uAAEF\\uAAF5\\uAAF6\\uABE3-\\uABEA\\uABEC\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"), + connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]"), + digit: new RegExp("[\\u0030-\\u0039\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]") +}; + +function is_letter(ch) { + return UNICODE.letter.test(ch); +}; + +function is_digit(ch) { + ch = ch.charCodeAt(0); + return ch >= 48 && ch <= 57; +}; + +function is_unicode_digit(ch) { + return UNICODE.digit.test(ch); +} + +function is_alphanumeric_char(ch) { + return is_digit(ch) || is_letter(ch); +}; + +function is_unicode_combining_mark(ch) { + return UNICODE.combining_mark.test(ch); +}; + +function is_unicode_connector_punctuation(ch) { + return UNICODE.connector_punctuation.test(ch); +}; + +function is_identifier_start(ch) { + return ch == "$" || ch == "_" || is_letter(ch); +}; + +function is_identifier_char(ch) { + return is_identifier_start(ch) + || is_unicode_combining_mark(ch) + || is_unicode_digit(ch) + || is_unicode_connector_punctuation(ch) + || ch == "\u200c" // zero-width non-joiner + || ch == "\u200d" // zero-width joiner (in my ECMA-262 PDF, this is also 200c) + ; +}; + +function parse_js_number(num) { + if (RE_HEX_NUMBER.test(num)) { + return parseInt(num.substr(2), 16); + } else if (RE_OCT_NUMBER.test(num)) { + return parseInt(num.substr(1), 8); + } else if (RE_DEC_NUMBER.test(num)) { + return parseFloat(num); + } +}; + +function JS_Parse_Error(message, line, col, pos) { + this.message = message; + this.line = line + 1; + this.col = col + 1; + this.pos = pos + 1; + this.stack = new Error().stack; +}; + +JS_Parse_Error.prototype.toString = function() { + return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack; +}; + +function js_error(message, line, col, pos) { + throw new JS_Parse_Error(message, line, col, pos); +}; + +function is_token(token, type, val) { + return token.type == type && (val == null || token.value == val); +}; + +var EX_EOF = {}; + +function tokenizer($TEXT) { + + var S = { + text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''), + pos : 0, + tokpos : 0, + line : 0, + tokline : 0, + col : 0, + tokcol : 0, + newline_before : false, + regex_allowed : false, + comments_before : [] + }; + + function peek() { return S.text.charAt(S.pos); }; + + function next(signal_eof, in_string) { + var ch = S.text.charAt(S.pos++); + if (signal_eof && !ch) + throw EX_EOF; + if (ch == "\n") { + S.newline_before = S.newline_before || !in_string; + ++S.line; + S.col = 0; + } else { + ++S.col; + } + return ch; + }; + + function eof() { + return !S.peek(); + }; + + function find(what, signal_eof) { + var pos = S.text.indexOf(what, S.pos); + if (signal_eof && pos == -1) throw EX_EOF; + return pos; + }; + + function start_token() { + S.tokline = S.line; + S.tokcol = S.col; + S.tokpos = S.pos; + }; + + function token(type, value, is_comment) { + S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) || + (type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) || + (type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value))); + var ret = { + type : type, + value : value, + line : S.tokline, + col : S.tokcol, + pos : S.tokpos, + endpos : S.pos, + nlb : S.newline_before + }; + if (!is_comment) { + ret.comments_before = S.comments_before; + S.comments_before = []; + // make note of any newlines in the comments that came before + for (var i = 0, len = ret.comments_before.length; i < len; i++) { + ret.nlb = ret.nlb || ret.comments_before[i].nlb; + } + } + S.newline_before = false; + return ret; + }; + + function skip_whitespace() { + while (HOP(WHITESPACE_CHARS, peek())) + next(); + }; + + function read_while(pred) { + var ret = "", ch = peek(), i = 0; + while (ch && pred(ch, i++)) { + ret += next(); + ch = peek(); + } + return ret; + }; + + function parse_error(err) { + js_error(err, S.tokline, S.tokcol, S.tokpos); + }; + + function read_num(prefix) { + var has_e = false, after_e = false, has_x = false, has_dot = prefix == "."; + var num = read_while(function(ch, i){ + if (ch == "x" || ch == "X") { + if (has_x) return false; + return has_x = true; + } + if (!has_x && (ch == "E" || ch == "e")) { + if (has_e) return false; + return has_e = after_e = true; + } + if (ch == "-") { + if (after_e || (i == 0 && !prefix)) return true; + return false; + } + if (ch == "+") return after_e; + after_e = false; + if (ch == ".") { + if (!has_dot && !has_x && !has_e) + return has_dot = true; + return false; + } + return is_alphanumeric_char(ch); + }); + if (prefix) + num = prefix + num; + var valid = parse_js_number(num); + if (!isNaN(valid)) { + return token("num", valid); + } else { + parse_error("Invalid syntax: " + num); + } + }; + + function read_escaped_char(in_string) { + var ch = next(true, in_string); + switch (ch) { + case "n" : return "\n"; + case "r" : return "\r"; + case "t" : return "\t"; + case "b" : return "\b"; + case "v" : return "\u000b"; + case "f" : return "\f"; + case "0" : return "\0"; + case "x" : return String.fromCharCode(hex_bytes(2)); + case "u" : return String.fromCharCode(hex_bytes(4)); + case "\n": return ""; + default : return ch; + } + }; + + function hex_bytes(n) { + var num = 0; + for (; n > 0; --n) { + var digit = parseInt(next(true), 16); + if (isNaN(digit)) + parse_error("Invalid hex-character pattern in string"); + num = (num << 4) | digit; + } + return num; + }; + + function read_string() { + return with_eof_error("Unterminated string constant", function(){ + var quote = next(), ret = ""; + for (;;) { + var ch = next(true); + if (ch == "\\") { + // read OctalEscapeSequence (XXX: deprecated if "strict mode") + // https://github.com/mishoo/UglifyJS/issues/178 + var octal_len = 0, first = null; + ch = read_while(function(ch){ + if (ch >= "0" && ch <= "7") { + if (!first) { + first = ch; + return ++octal_len; + } + else if (first <= "3" && octal_len <= 2) return ++octal_len; + else if (first >= "4" && octal_len <= 1) return ++octal_len; + } + return false; + }); + if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8)); + else ch = read_escaped_char(true); + } + else if (ch == quote) break; + ret += ch; + } + return token("string", ret); + }); + }; + + function read_line_comment() { + next(); + var i = find("\n"), ret; + if (i == -1) { + ret = S.text.substr(S.pos); + S.pos = S.text.length; + } else { + ret = S.text.substring(S.pos, i); + S.pos = i; + } + return token("comment1", ret, true); + }; + + function read_multiline_comment() { + next(); + return with_eof_error("Unterminated multiline comment", function(){ + var i = find("*/", true), + text = S.text.substring(S.pos, i); + S.pos = i + 2; + S.line += text.split("\n").length - 1; + S.newline_before = S.newline_before || text.indexOf("\n") >= 0; + + // https://github.com/mishoo/UglifyJS/issues/#issue/100 + if (/^@cc_on/i.test(text)) { + warn("WARNING: at line " + S.line); + warn("*** Found \"conditional comment\": " + text); + warn("*** UglifyJS DISCARDS ALL COMMENTS. This means your code might no longer work properly in Internet Explorer."); + } + + return token("comment2", text, true); + }); + }; + + function read_name() { + var backslash = false, name = "", ch, escaped = false, hex; + while ((ch = peek()) != null) { + if (!backslash) { + if (ch == "\\") escaped = backslash = true, next(); + else if (is_identifier_char(ch)) name += next(); + else break; + } + else { + if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX"); + ch = read_escaped_char(); + if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier"); + name += ch; + backslash = false; + } + } + if (HOP(KEYWORDS, name) && escaped) { + hex = name.charCodeAt(0).toString(16).toUpperCase(); + name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1); + } + return name; + }; + + function read_regexp(regexp) { + return with_eof_error("Unterminated regular expression", function(){ + var prev_backslash = false, ch, in_class = false; + while ((ch = next(true))) if (prev_backslash) { + regexp += "\\" + ch; + prev_backslash = false; + } else if (ch == "[") { + in_class = true; + regexp += ch; + } else if (ch == "]" && in_class) { + in_class = false; + regexp += ch; + } else if (ch == "/" && !in_class) { + break; + } else if (ch == "\\") { + prev_backslash = true; + } else { + regexp += ch; + } + var mods = read_name(); + return token("regexp", [ regexp, mods ]); + }); + }; + + function read_operator(prefix) { + function grow(op) { + if (!peek()) return op; + var bigger = op + peek(); + if (HOP(OPERATORS, bigger)) { + next(); + return grow(bigger); + } else { + return op; + } + }; + return token("operator", grow(prefix || next())); + }; + + function handle_slash() { + next(); + var regex_allowed = S.regex_allowed; + switch (peek()) { + case "/": + S.comments_before.push(read_line_comment()); + S.regex_allowed = regex_allowed; + return next_token(); + case "*": + S.comments_before.push(read_multiline_comment()); + S.regex_allowed = regex_allowed; + return next_token(); + } + return S.regex_allowed ? read_regexp("") : read_operator("/"); + }; + + function handle_dot() { + next(); + return is_digit(peek()) + ? read_num(".") + : token("punc", "."); + }; + + function read_word() { + var word = read_name(); + return !HOP(KEYWORDS, word) + ? token("name", word) + : HOP(OPERATORS, word) + ? token("operator", word) + : HOP(KEYWORDS_ATOM, word) + ? token("atom", word) + : token("keyword", word); + }; + + function with_eof_error(eof_error, cont) { + try { + return cont(); + } catch(ex) { + if (ex === EX_EOF) parse_error(eof_error); + else throw ex; + } + }; + + function next_token(force_regexp) { + if (force_regexp != null) + return read_regexp(force_regexp); + skip_whitespace(); + start_token(); + var ch = peek(); + if (!ch) return token("eof"); + if (is_digit(ch)) return read_num(); + if (ch == '"' || ch == "'") return read_string(); + if (HOP(PUNC_CHARS, ch)) return token("punc", next()); + if (ch == ".") return handle_dot(); + if (ch == "/") return handle_slash(); + if (HOP(OPERATOR_CHARS, ch)) return read_operator(); + if (ch == "\\" || is_identifier_start(ch)) return read_word(); + parse_error("Unexpected character '" + ch + "'"); + }; + + next_token.context = function(nc) { + if (nc) S = nc; + return S; + }; + + return next_token; + +}; + +/* -----[ Parser (constants) ]----- */ + +var UNARY_PREFIX = array_to_hash([ + "typeof", + "void", + "delete", + "--", + "++", + "!", + "~", + "-", + "+" +]); + +var UNARY_POSTFIX = array_to_hash([ "--", "++" ]); + +var ASSIGNMENT = (function(a, ret, i){ + while (i < a.length) { + ret[a[i]] = a[i].substr(0, a[i].length - 1); + i++; + } + return ret; +})( + ["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&="], + { "=": true }, + 0 +); + +var PRECEDENCE = (function(a, ret){ + for (var i = 0, n = 1; i < a.length; ++i, ++n) { + var b = a[i]; + for (var j = 0; j < b.length; ++j) { + ret[b[j]] = n; + } + } + return ret; +})( + [ + ["||"], + ["&&"], + ["|"], + ["^"], + ["&"], + ["==", "===", "!=", "!=="], + ["<", ">", "<=", ">=", "in", "instanceof"], + [">>", "<<", ">>>"], + ["+", "-"], + ["*", "/", "%"] + ], + {} +); + +var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]); + +var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]); + +/* -----[ Parser ]----- */ + +function NodeWithToken(str, start, end) { + this.name = str; + this.start = start; + this.end = end; +}; + +NodeWithToken.prototype.toString = function() { return this.name; }; + +function parse($TEXT, exigent_mode, embed_tokens) { + + var S = { + input : typeof $TEXT == "string" ? tokenizer($TEXT, true) : $TEXT, + token : null, + prev : null, + peeked : null, + in_function : 0, + in_directives : true, + in_loop : 0, + labels : [] + }; + + S.token = next(); + + function is(type, value) { + return is_token(S.token, type, value); + }; + + function peek() { return S.peeked || (S.peeked = S.input()); }; + + function next() { + S.prev = S.token; + if (S.peeked) { + S.token = S.peeked; + S.peeked = null; + } else { + S.token = S.input(); + } + S.in_directives = S.in_directives && ( + S.token.type == "string" || is("punc", ";") + ); + return S.token; + }; + + function prev() { + return S.prev; + }; + + function croak(msg, line, col, pos) { + var ctx = S.input.context(); + js_error(msg, + line != null ? line : ctx.tokline, + col != null ? col : ctx.tokcol, + pos != null ? pos : ctx.tokpos); + }; + + function token_error(token, msg) { + croak(msg, token.line, token.col); + }; + + function unexpected(token) { + if (token == null) + token = S.token; + token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); + }; + + function expect_token(type, val) { + if (is(type, val)) { + return next(); + } + token_error(S.token, "Unexpected token " + S.token.type + ", expected " + type); + }; + + function expect(punc) { return expect_token("punc", punc); }; + + function can_insert_semicolon() { + return !exigent_mode && ( + S.token.nlb || is("eof") || is("punc", "}") + ); + }; + + function semicolon() { + if (is("punc", ";")) next(); + else if (!can_insert_semicolon()) unexpected(); + }; + + function as() { + return slice(arguments); + }; + + function parenthesised() { + expect("("); + var ex = expression(); + expect(")"); + return ex; + }; + + function add_tokens(str, start, end) { + return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end); + }; + + function maybe_embed_tokens(parser) { + if (embed_tokens) return function() { + var start = S.token; + var ast = parser.apply(this, arguments); + ast[0] = add_tokens(ast[0], start, prev()); + return ast; + }; + else return parser; + }; + + var statement = maybe_embed_tokens(function() { + if (is("operator", "/") || is("operator", "/=")) { + S.peeked = null; + S.token = S.input(S.token.value.substr(1)); // force regexp + } + switch (S.token.type) { + case "string": + var dir = S.in_directives, stat = simple_statement(); + if (dir && stat[1][0] == "string" && !is("punc", ",")) + return as("directive", stat[1][1]); + return stat; + case "num": + case "regexp": + case "operator": + case "atom": + return simple_statement(); + + case "name": + return is_token(peek(), "punc", ":") + ? labeled_statement(prog1(S.token.value, next, next)) + : simple_statement(); + + case "punc": + switch (S.token.value) { + case "{": + return as("block", block_()); + case "[": + case "(": + return simple_statement(); + case ";": + next(); + return as("block"); + default: + unexpected(); + } + + case "keyword": + switch (prog1(S.token.value, next)) { + case "break": + return break_cont("break"); + + case "continue": + return break_cont("continue"); + + case "debugger": + semicolon(); + return as("debugger"); + + case "do": + return (function(body){ + expect_token("keyword", "while"); + return as("do", prog1(parenthesised, semicolon), body); + })(in_loop(statement)); + + case "for": + return for_(); + + case "function": + return function_(true); + + case "if": + return if_(); + + case "return": + if (S.in_function == 0) + croak("'return' outside of function"); + return as("return", + is("punc", ";") + ? (next(), null) + : can_insert_semicolon() + ? null + : prog1(expression, semicolon)); + + case "switch": + return as("switch", parenthesised(), switch_block_()); + + case "throw": + if (S.token.nlb) + croak("Illegal newline after 'throw'"); + return as("throw", prog1(expression, semicolon)); + + case "try": + return try_(); + + case "var": + return prog1(var_, semicolon); + + case "const": + return prog1(const_, semicolon); + + case "while": + return as("while", parenthesised(), in_loop(statement)); + + case "with": + return as("with", parenthesised(), statement()); + + default: + unexpected(); + } + } + }); + + function labeled_statement(label) { + S.labels.push(label); + var start = S.token, stat = statement(); + if (exigent_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0])) + unexpected(start); + S.labels.pop(); + return as("label", label, stat); + }; + + function simple_statement() { + return as("stat", prog1(expression, semicolon)); + }; + + function break_cont(type) { + var name; + if (!can_insert_semicolon()) { + name = is("name") ? S.token.value : null; + } + if (name != null) { + next(); + if (!member(name, S.labels)) + croak("Label " + name + " without matching loop or statement"); + } + else if (S.in_loop == 0) + croak(type + " not inside a loop or switch"); + semicolon(); + return as(type, name); + }; + + function for_() { + expect("("); + var init = null; + if (!is("punc", ";")) { + init = is("keyword", "var") + ? (next(), var_(true)) + : expression(true, true); + if (is("operator", "in")) { + if (init[0] == "var" && init[1].length > 1) + croak("Only one variable declaration allowed in for..in loop"); + return for_in(init); + } + } + return regular_for(init); + }; + + function regular_for(init) { + expect(";"); + var test = is("punc", ";") ? null : expression(); + expect(";"); + var step = is("punc", ")") ? null : expression(); + expect(")"); + return as("for", init, test, step, in_loop(statement)); + }; + + function for_in(init) { + var lhs = init[0] == "var" ? as("name", init[1][0]) : init; + next(); + var obj = expression(); + expect(")"); + return as("for-in", init, lhs, obj, in_loop(statement)); + }; + + var function_ = function(in_statement) { + var name = is("name") ? prog1(S.token.value, next) : null; + if (in_statement && !name) + unexpected(); + expect("("); + return as(in_statement ? "defun" : "function", + name, + // arguments + (function(first, a){ + while (!is("punc", ")")) { + if (first) first = false; else expect(","); + if (!is("name")) unexpected(); + a.push(S.token.value); + next(); + } + next(); + return a; + })(true, []), + // body + (function(){ + ++S.in_function; + var loop = S.in_loop; + S.in_directives = true; + S.in_loop = 0; + var a = block_(); + --S.in_function; + S.in_loop = loop; + return a; + })()); + }; + + function if_() { + var cond = parenthesised(), body = statement(), belse; + if (is("keyword", "else")) { + next(); + belse = statement(); + } + return as("if", cond, body, belse); + }; + + function block_() { + expect("{"); + var a = []; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + a.push(statement()); + } + next(); + return a; + }; + + var switch_block_ = curry(in_loop, function(){ + expect("{"); + var a = [], cur = null; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + if (is("keyword", "case")) { + next(); + cur = []; + a.push([ expression(), cur ]); + expect(":"); + } + else if (is("keyword", "default")) { + next(); + expect(":"); + cur = []; + a.push([ null, cur ]); + } + else { + if (!cur) unexpected(); + cur.push(statement()); + } + } + next(); + return a; + }); + + function try_() { + var body = block_(), bcatch, bfinally; + if (is("keyword", "catch")) { + next(); + expect("("); + if (!is("name")) + croak("Name expected"); + var name = S.token.value; + next(); + expect(")"); + bcatch = [ name, block_() ]; + } + if (is("keyword", "finally")) { + next(); + bfinally = block_(); + } + if (!bcatch && !bfinally) + croak("Missing catch/finally blocks"); + return as("try", body, bcatch, bfinally); + }; + + function vardefs(no_in) { + var a = []; + for (;;) { + if (!is("name")) + unexpected(); + var name = S.token.value; + next(); + if (is("operator", "=")) { + next(); + a.push([ name, expression(false, no_in) ]); + } else { + a.push([ name ]); + } + if (!is("punc", ",")) + break; + next(); + } + return a; + }; + + function var_(no_in) { + return as("var", vardefs(no_in)); + }; + + function const_() { + return as("const", vardefs()); + }; + + function new_() { + var newexp = expr_atom(false), args; + if (is("punc", "(")) { + next(); + args = expr_list(")"); + } else { + args = []; + } + return subscripts(as("new", newexp, args), true); + }; + + var expr_atom = maybe_embed_tokens(function(allow_calls) { + if (is("operator", "new")) { + next(); + return new_(); + } + if (is("punc")) { + switch (S.token.value) { + case "(": + next(); + return subscripts(prog1(expression, curry(expect, ")")), allow_calls); + case "[": + next(); + return subscripts(array_(), allow_calls); + case "{": + next(); + return subscripts(object_(), allow_calls); + } + unexpected(); + } + if (is("keyword", "function")) { + next(); + return subscripts(function_(false), allow_calls); + } + if (HOP(ATOMIC_START_TOKEN, S.token.type)) { + var atom = S.token.type == "regexp" + ? as("regexp", S.token.value[0], S.token.value[1]) + : as(S.token.type, S.token.value); + return subscripts(prog1(atom, next), allow_calls); + } + unexpected(); + }); + + function expr_list(closing, allow_trailing_comma, allow_empty) { + var first = true, a = []; + while (!is("punc", closing)) { + if (first) first = false; else expect(","); + if (allow_trailing_comma && is("punc", closing)) break; + if (is("punc", ",") && allow_empty) { + a.push([ "atom", "undefined" ]); + } else { + a.push(expression(false)); + } + } + next(); + return a; + }; + + function array_() { + return as("array", expr_list("]", !exigent_mode, true)); + }; + + function object_() { + var first = true, a = []; + while (!is("punc", "}")) { + if (first) first = false; else expect(","); + if (!exigent_mode && is("punc", "}")) + // allow trailing comma + break; + var type = S.token.type; + var name = as_property_name(); + if (type == "name" && (name == "get" || name == "set") && !is("punc", ":")) { + a.push([ as_name(), function_(false), name ]); + } else { + expect(":"); + a.push([ name, expression(false) ]); + } + // FIXME [!!] Line not in original parse-js, + // added to be able to warn about unquoted + // keyword properties + a[a.length - 1].type = type; + } + next(); + return as("object", a); + }; + + function as_property_name() { + switch (S.token.type) { + case "num": + case "string": + return prog1(S.token.value, next); + } + return as_name(); + }; + + function as_name() { + switch (S.token.type) { + case "name": + case "operator": + case "keyword": + case "atom": + return prog1(S.token.value, next); + default: + unexpected(); + } + }; + + function subscripts(expr, allow_calls) { + if (is("punc", ".")) { + next(); + return subscripts(as("dot", expr, as_name()), allow_calls); + } + if (is("punc", "[")) { + next(); + return subscripts(as("sub", expr, prog1(expression, curry(expect, "]"))), allow_calls); + } + if (allow_calls && is("punc", "(")) { + next(); + return subscripts(as("call", expr, expr_list(")")), true); + } + return expr; + }; + + function maybe_unary(allow_calls) { + if (is("operator") && HOP(UNARY_PREFIX, S.token.value)) { + return make_unary("unary-prefix", + prog1(S.token.value, next), + maybe_unary(allow_calls)); + } + var val = expr_atom(allow_calls); + while (is("operator") && HOP(UNARY_POSTFIX, S.token.value) && !S.token.nlb) { + val = make_unary("unary-postfix", S.token.value, val); + next(); + } + return val; + }; + + function make_unary(tag, op, expr) { + if ((op == "++" || op == "--") && !is_assignable(expr)) + croak("Invalid use of " + op + " operator"); + return as(tag, op, expr); + }; + + function expr_op(left, min_prec, no_in) { + var op = is("operator") ? S.token.value : null; + if (op && op == "in" && no_in) op = null; + var prec = op != null ? PRECEDENCE[op] : null; + if (prec != null && prec > min_prec) { + next(); + var right = expr_op(maybe_unary(true), prec, no_in); + return expr_op(as("binary", op, left, right), min_prec, no_in); + } + return left; + }; + + function expr_ops(no_in) { + return expr_op(maybe_unary(true), 0, no_in); + }; + + function maybe_conditional(no_in) { + var expr = expr_ops(no_in); + if (is("operator", "?")) { + next(); + var yes = expression(false); + expect(":"); + return as("conditional", expr, yes, expression(false, no_in)); + } + return expr; + }; + + function is_assignable(expr) { + if (!exigent_mode) return true; + switch (expr[0]+"") { + case "dot": + case "sub": + case "new": + case "call": + return true; + case "name": + return expr[1] != "this"; + } + }; + + function maybe_assign(no_in) { + var left = maybe_conditional(no_in), val = S.token.value; + if (is("operator") && HOP(ASSIGNMENT, val)) { + if (is_assignable(left)) { + next(); + return as("assign", ASSIGNMENT[val], left, maybe_assign(no_in)); + } + croak("Invalid assignment"); + } + return left; + }; + + var expression = maybe_embed_tokens(function(commas, no_in) { + if (arguments.length == 0) + commas = true; + var expr = maybe_assign(no_in); + if (commas && is("punc", ",")) { + next(); + return as("seq", expr, expression(true, no_in)); + } + return expr; + }); + + function in_loop(cont) { + try { + ++S.in_loop; + return cont(); + } finally { + --S.in_loop; + } + }; + + return as("toplevel", (function(a){ + while (!is("eof")) + a.push(statement()); + return a; + })([])); + +}; + +/* -----[ Utilities ]----- */ + +function curry(f) { + var args = slice(arguments, 1); + return function() { return f.apply(this, args.concat(slice(arguments))); }; +}; + +function prog1(ret) { + if (ret instanceof Function) + ret = ret(); + for (var i = 1, n = arguments.length; --n > 0; ++i) + arguments[i](); + return ret; +}; + +function array_to_hash(a) { + var ret = {}; + for (var i = 0; i < a.length; ++i) + ret[a[i]] = true; + return ret; +}; + +function slice(a, start) { + return Array.prototype.slice.call(a, start || 0); +}; + +function characters(str) { + return str.split(""); +}; + +function member(name, array) { + for (var i = array.length; --i >= 0;) + if (array[i] == name) + return true; + return false; +}; + +function HOP(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +}; + +var warn = function() {}; + +/* -----[ Exports ]----- */ + +exports.tokenizer = tokenizer; +exports.parse = parse; +exports.slice = slice; +exports.curry = curry; +exports.member = member; +exports.array_to_hash = array_to_hash; +exports.PRECEDENCE = PRECEDENCE; +exports.KEYWORDS_ATOM = KEYWORDS_ATOM; +exports.RESERVED_WORDS = RESERVED_WORDS; +exports.KEYWORDS = KEYWORDS; +exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN; +exports.OPERATORS = OPERATORS; +exports.is_alphanumeric_char = is_alphanumeric_char; +exports.is_identifier_start = is_identifier_start; +exports.is_identifier_char = is_identifier_char; +exports.set_logger = function(logger) { + warn = logger; +}; + +// Local variables: +// js-indent-level: 8 +// End: diff --git a/codemirror/test/lint/walk.js b/codemirror/test/lint/walk.js new file mode 100644 index 0000000..97321ac --- /dev/null +++ b/codemirror/test/lint/walk.js @@ -0,0 +1,216 @@ +// AST walker module for Mozilla Parser API compatible trees + +(function(exports) { + "use strict"; + + // A simple walk is one where you simply specify callbacks to be + // called on specific nodes. The last two arguments are optional. A + // simple use would be + // + // walk.simple(myTree, { + // Expression: function(node) { ... } + // }); + // + // to do something with all expressions. All Parser API node types + // can be used to identify node types, as well as Expression, + // Statement, and ScopeBody, which denote categories of nodes. + // + // The base argument can be used to pass a custom (recursive) + // walker, and state can be used to give this walked an initial + // state. + exports.simple = function(node, visitors, base, state) { + if (!base) base = exports; + function c(node, st, override) { + var type = override || node.type, found = visitors[type]; + if (found) found(node, st); + base[type](node, st, c); + } + c(node, state); + }; + + // A recursive walk is one where your functions override the default + // walkers. They can modify and replace the state parameter that's + // threaded through the walk, and can opt how and whether to walk + // their child nodes (by calling their third argument on these + // nodes). + exports.recursive = function(node, state, funcs, base) { + var visitor = exports.make(funcs, base); + function c(node, st, override) { + visitor[override || node.type](node, st, c); + } + c(node, state); + }; + + // Used to create a custom walker. Will fill in all missing node + // type properties with the defaults. + exports.make = function(funcs, base) { + if (!base) base = exports; + var visitor = {}; + for (var type in base) + visitor[type] = funcs.hasOwnProperty(type) ? funcs[type] : base[type]; + return visitor; + }; + + function skipThrough(node, st, c) { c(node, st); } + function ignore(node, st, c) {} + + // Node walkers. + + exports.Program = exports.BlockStatement = function(node, st, c) { + for (var i = 0; i < node.body.length; ++i) + c(node.body[i], st, "Statement"); + }; + exports.Statement = skipThrough; + exports.EmptyStatement = ignore; + exports.ExpressionStatement = function(node, st, c) { + c(node.expression, st, "Expression"); + }; + exports.IfStatement = function(node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Statement"); + if (node.alternate) c(node.alternate, st, "Statement"); + }; + exports.LabeledStatement = function(node, st, c) { + c(node.body, st, "Statement"); + }; + exports.BreakStatement = exports.ContinueStatement = ignore; + exports.WithStatement = function(node, st, c) { + c(node.object, st, "Expression"); + c(node.body, st, "Statement"); + }; + exports.SwitchStatement = function(node, st, c) { + c(node.discriminant, st, "Expression"); + for (var i = 0; i < node.cases.length; ++i) { + var cs = node.cases[i]; + if (cs.test) c(cs.test, st, "Expression"); + for (var j = 0; j < cs.consequent.length; ++j) + c(cs.consequent[j], st, "Statement"); + } + }; + exports.ReturnStatement = function(node, st, c) { + if (node.argument) c(node.argument, st, "Expression"); + }; + exports.ThrowStatement = function(node, st, c) { + c(node.argument, st, "Expression"); + }; + exports.TryStatement = function(node, st, c) { + c(node.block, st, "Statement"); + for (var i = 0; i < node.handlers.length; ++i) + c(node.handlers[i].body, st, "ScopeBody"); + if (node.finalizer) c(node.finalizer, st, "Statement"); + }; + exports.WhileStatement = function(node, st, c) { + c(node.test, st, "Expression"); + c(node.body, st, "Statement"); + }; + exports.DoWhileStatement = exports.WhileStatement; + exports.ForStatement = function(node, st, c) { + if (node.init) c(node.init, st, "ForInit"); + if (node.test) c(node.test, st, "Expression"); + if (node.update) c(node.update, st, "Expression"); + c(node.body, st, "Statement"); + }; + exports.ForInStatement = function(node, st, c) { + c(node.left, st, "ForInit"); + c(node.right, st, "Expression"); + c(node.body, st, "Statement"); + }; + exports.ForInit = function(node, st, c) { + if (node.type == "VariableDeclaration") c(node, st); + else c(node, st, "Expression"); + }; + exports.DebuggerStatement = ignore; + + exports.FunctionDeclaration = function(node, st, c) { + c(node, st, "Function"); + }; + exports.VariableDeclaration = function(node, st, c) { + for (var i = 0; i < node.declarations.length; ++i) { + var decl = node.declarations[i]; + if (decl.init) c(decl.init, st, "Expression"); + } + }; + + exports.Function = function(node, st, c) { + c(node.body, st, "ScopeBody"); + }; + exports.ScopeBody = function(node, st, c) { + c(node, st, "Statement"); + }; + + exports.Expression = skipThrough; + exports.ThisExpression = ignore; + exports.ArrayExpression = function(node, st, c) { + for (var i = 0; i < node.elements.length; ++i) { + var elt = node.elements[i]; + if (elt) c(elt, st, "Expression"); + } + }; + exports.ObjectExpression = function(node, st, c) { + for (var i = 0; i < node.properties.length; ++i) + c(node.properties[i].value, st, "Expression"); + }; + exports.FunctionExpression = exports.FunctionDeclaration; + exports.SequenceExpression = function(node, st, c) { + for (var i = 0; i < node.expressions.length; ++i) + c(node.expressions[i], st, "Expression"); + }; + exports.UnaryExpression = exports.UpdateExpression = function(node, st, c) { + c(node.argument, st, "Expression"); + }; + exports.BinaryExpression = exports.AssignmentExpression = exports.LogicalExpression = function(node, st, c) { + c(node.left, st, "Expression"); + c(node.right, st, "Expression"); + }; + exports.ConditionalExpression = function(node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Expression"); + c(node.alternate, st, "Expression"); + }; + exports.NewExpression = exports.CallExpression = function(node, st, c) { + c(node.callee, st, "Expression"); + if (node.arguments) for (var i = 0; i < node.arguments.length; ++i) + c(node.arguments[i], st, "Expression"); + }; + exports.MemberExpression = function(node, st, c) { + c(node.object, st, "Expression"); + if (node.computed) c(node.property, st, "Expression"); + }; + exports.Identifier = exports.Literal = ignore; + + // A custom walker that keeps track of the scope chain and the + // variables defined in it. + function makeScope(prev) { + return {vars: Object.create(null), prev: prev}; + } + exports.scopeVisitor = exports.make({ + Function: function(node, scope, c) { + var inner = makeScope(scope); + for (var i = 0; i < node.params.length; ++i) + inner.vars[node.params[i].name] = {type: "argument", node: node.params[i]}; + if (node.id) { + var decl = node.type == "FunctionDeclaration"; + (decl ? scope : inner).vars[node.id.name] = + {type: decl ? "function" : "function name", node: node.id}; + } + c(node.body, inner, "ScopeBody"); + }, + TryStatement: function(node, scope, c) { + c(node.block, scope, "Statement"); + for (var i = 0; i < node.handlers.length; ++i) { + var handler = node.handlers[i], inner = makeScope(scope); + inner.vars[handler.param.name] = {type: "catch clause", node: handler.param}; + c(handler.body, inner, "ScopeBody"); + } + if (node.finalizer) c(node.finalizer, scope, "Statement"); + }, + VariableDeclaration: function(node, scope, c) { + for (var i = 0; i < node.declarations.length; ++i) { + var decl = node.declarations[i]; + scope.vars[decl.id.name] = {type: "var", node: decl.id}; + if (decl.init) c(decl.init, scope, "Expression"); + } + } + }); + +})(typeof exports == "undefined" ? acorn.walk = {} : exports); diff --git a/codemirror/test/mode_test.css b/codemirror/test/mode_test.css new file mode 100644 index 0000000..1ac6673 --- /dev/null +++ b/codemirror/test/mode_test.css @@ -0,0 +1,10 @@ +.mt-output .mt-token { + border: 1px solid #ddd; + white-space: pre; + font-family: "Consolas", monospace; + text-align: center; +} + +.mt-output .mt-style { + font-size: x-small; +} diff --git a/codemirror/test/mode_test.js b/codemirror/test/mode_test.js new file mode 100644 index 0000000..f2459b4 --- /dev/null +++ b/codemirror/test/mode_test.js @@ -0,0 +1,192 @@ +/** + * Helper to test CodeMirror highlighting modes. It pretty prints output of the + * highlighter and can check against expected styles. + * + * See test.html in the stex mode for examples. + */ +ModeTest = {}; + +ModeTest.modeOptions = {}; +ModeTest.modeName = CodeMirror.defaults.mode; + +/* keep track of results for printSummary */ +ModeTest.testCount = 0; +ModeTest.passes = 0; + +/** + * Run a test; prettyprints the results using document.write(). + * + * @param name Name of test + * @param text String to highlight. + * @param expected Expected styles and tokens: Array(style, token, [style, token,...]) + * @param modeName + * @param modeOptions + * @param expectedFail + */ +ModeTest.testMode = function(name, text, expected, modeName, modeOptions, expectedFail) { + ModeTest.testCount += 1; + + if (!modeName) modeName = ModeTest.modeName; + + if (!modeOptions) modeOptions = ModeTest.modeOptions; + + var mode = CodeMirror.getMode(modeOptions, modeName); + + if (expected.length < 0) { + throw "must have text for test (" + name + ")"; + } + if (expected.length % 2 != 0) { + throw "must have text for test (" + name + ") plus expected (style, token) pairs"; + } + return test( + modeName + "_" + name, + function(){ + return ModeTest.compare(text, expected, mode); + }, + expectedFail + ); + +} + +ModeTest.compare = function (text, expected, mode) { + + var expectedOutput = []; + for (var i = 0; i < expected.length; i += 2) { + var sty = expected[i]; + if (sty && sty.indexOf(" ")) sty = sty.split(' ').sort().join(' '); + expectedOutput.push(sty, expected[i + 1]); + } + + var observedOutput = ModeTest.highlight(text, mode); + + var pass, passStyle = ""; + pass = ModeTest.highlightOutputsEqual(expectedOutput, observedOutput); + passStyle = pass ? 'mt-pass' : 'mt-fail'; + ModeTest.passes += pass ? 1 : 0; + + var s = ''; + if (pass) { + s += '
    '; + s += '
    ' + ModeTest.htmlEscape(text) + '
    '; + s += '
    '; + s += ModeTest.prettyPrintOutputTable(observedOutput); + s += '
    '; + s += '
    '; + return s; + } else { + s += '
    '; + s += '
    ' + ModeTest.htmlEscape(text) + '
    '; + s += '
    '; + s += 'expected:'; + s += ModeTest.prettyPrintOutputTable(expectedOutput); + s += 'observed:'; + s += ModeTest.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 + */ +ModeTest.highlight = function(string, mode) { + var state = mode.startState() + + var lines = string.replace(/\r\n/g,'\n').split('\n'); + var st = [], pos = 0; + for (var i = 0; i < lines.length; ++i) { + var line = lines[i], newLine = true; + var stream = new CodeMirror.StringStream(line); + if (line == "" && mode.blankLine) mode.blankLine(state); + /* Start copied code from CodeMirror.highlight */ + while (!stream.eol()) { + var style = mode.token(stream, state), substr = stream.current(); + if (style && style.indexOf(" ") > -1) style = style.split(' ').sort().join(' '); + + stream.start = stream.pos; + if (pos && st[pos-2] == style && !newLine) { + st[pos-1] += substr; + } else if (substr) { + st[pos++] = style; st[pos++] = substr; + } + // Give up when line is ridiculously long + if (stream.pos > 5000) { + st[pos++] = null; st[pos++] = this.text.slice(stream.pos); + break; + } + newLine = false; + } + } + + return st; +} + +/** + * Compare two arrays of output from ModeTest.highlight. + * + * @param o1 array of [style, token] pairs + * + * @param o2 array of [style, token] pairs + * + * @return boolean; true iff outputs equal + */ +ModeTest.highlightOutputsEqual = function(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 + */ +ModeTest.prettyPrintOutputTable = function(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 += '
    ' + + '' + + ModeTest.htmlEscape(val).replace(/ /g,'·') + + '' + + '
    ' + output[i] + '
    '; + return s; +} + +/** + * Print how many tests have run so far and how many of those passed. + */ +ModeTest.printSummary = function() { + ModeTest.runTests(ModeTest.displayTest); + document.write(ModeTest.passes + ' passes for ' + ModeTest.testCount + ' tests'); +} + +/** + * Basic HTML escaping. + */ +ModeTest.htmlEscape = function(str) { + str = str.toString(); + return str.replace(/[<&]/g, + function(str) {return str == "&" ? "&" : "<";}); +} + diff --git a/codemirror/test/phantom_driver.js b/codemirror/test/phantom_driver.js new file mode 100644 index 0000000..dbad08d --- /dev/null +++ b/codemirror/test/phantom_driver.js @@ -0,0 +1,31 @@ +var page = require('webpage').create(); + +page.open("http://localhost:3000/test/index.html", function (status) { + if (status != "success") { + console.log("page couldn't be loaded successfully"); + phantom.exit(1); + } + waitFor(function () { + return page.evaluate(function () { + var output = document.getElementById('status'); + if (!output) { return false; } + return (/^(\d+ failures?|all passed)/i).test(output.innerText); + }); + }, function () { + var failed = page.evaluate(function () { return window.failed; }); + var output = page.evaluate(function () { + return document.getElementById('output').innerText + "\n" + + document.getElementById('status').innerText; + }); + console.log(output); + phantom.exit(failed > 0 ? 1 : 0); + }); +}); + +function waitFor (test, cb) { + if (test()) { + cb(); + } else { + setTimeout(function () { waitFor(test, cb); }, 250); + } +} diff --git a/codemirror/test/run.js b/codemirror/test/run.js new file mode 100644 index 0000000..8c7649a --- /dev/null +++ b/codemirror/test/run.js @@ -0,0 +1,32 @@ +#!/usr/bin/env node + +var lint = require("./lint/lint"); + +lint.checkDir("mode"); +lint.checkDir("lib"); + +var ok = lint.success(); + +var files = new (require('node-static').Server)('.'); + +var server = require('http').createServer(function (req, res) { + req.addListener('end', function () { + files.serve(req, res); + }); +}).addListener('error', function (err) { + throw err; +}).listen(3000, function () { + var child_process = require('child_process'); + child_process.exec("which phantomjs", function (err) { + if (err) { + console.error("PhantomJS is not installed. Download from http://phantomjs.org"); + process.exit(1); + } + var cmd = 'phantomjs test/phantom_driver.js'; + child_process.exec(cmd, function (err, stdout) { + server.close(); + console.log(stdout); + process.exit(err || !ok ? 1 : 0); + }); + }); +}); diff --git a/codemirror/test/test.js b/codemirror/test/test.js new file mode 100644 index 0000000..841a984 --- /dev/null +++ b/codemirror/test/test.js @@ -0,0 +1,1188 @@ +function forEach(arr, f) { + for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); +} + +function addDoc(cm, width, height) { + var content = [], line = ""; + for (var i = 0; i < width; ++i) line += "x"; + for (var i = 0; i < height; ++i) content.push(line); + cm.setValue(content.join("\n")); +} + +function byClassName(elt, cls) { + if (elt.getElementsByClassName) return elt.getElementsByClassName(cls); + var found = [], re = new RegExp("\\b" + cls + "\\b"); + function search(elt) { + if (elt.nodeType == 3) return; + if (re.test(elt.className)) found.push(elt); + for (var i = 0, e = elt.childNodes.length; i < e; ++i) + search(elt.childNodes[i]); + } + search(elt); + return found; +} + +var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent); +var mac = /Mac/.test(navigator.platform); +var phantom = /PhantomJS/.test(navigator.userAgent); +var opera = /Opera\/\./.test(navigator.userAgent); +var opera_version = opera && navigator.userAgent.match(/Version\/(\d+\.\d+)/); +if (opera_version) opera_version = Number(opera_version); +var opera_lt10 = opera && (!opera_version || opera_version < 10); + +test("core_fromTextArea", function() { + var te = document.getElementById("code"); + te.value = "CONTENT"; + var cm = CodeMirror.fromTextArea(te); + is(!te.offsetHeight); + eq(cm.getValue(), "CONTENT"); + cm.setValue("foo\nbar"); + eq(cm.getValue(), "foo\nbar"); + cm.save(); + is(/^foo\r?\nbar$/.test(te.value)); + cm.setValue("xxx"); + cm.toTextArea(); + is(te.offsetHeight); + eq(te.value, "xxx"); +}); + +testCM("getRange", function(cm) { + eq(cm.getLine(0), "1234"); + eq(cm.getLine(1), "5678"); + eq(cm.getLine(2), null); + eq(cm.getLine(-1), null); + eq(cm.getRange({line: 0, ch: 0}, {line: 0, ch: 3}), "123"); + eq(cm.getRange({line: 0, ch: -1}, {line: 0, ch: 200}), "1234"); + eq(cm.getRange({line: 0, ch: 2}, {line: 1, ch: 2}), "34\n56"); + eq(cm.getRange({line: 1, ch: 2}, {line: 100, ch: 0}), "78"); +}, {value: "1234\n5678"}); + +testCM("replaceRange", function(cm) { + eq(cm.getValue(), ""); + cm.replaceRange("foo\n", {line: 0, ch: 0}); + eq(cm.getValue(), "foo\n"); + cm.replaceRange("a\nb", {line: 0, ch: 1}); + eq(cm.getValue(), "fa\nboo\n"); + eq(cm.lineCount(), 3); + cm.replaceRange("xyzzy", {line: 0, ch: 0}, {line: 1, ch: 1}); + eq(cm.getValue(), "xyzzyoo\n"); + cm.replaceRange("abc", {line: 0, ch: 0}, {line: 10, ch: 0}); + eq(cm.getValue(), "abc"); + eq(cm.lineCount(), 1); +}); + +testCM("selection", function(cm) { + cm.setSelection({line: 0, ch: 4}, {line: 2, ch: 2}); + is(cm.somethingSelected()); + eq(cm.getSelection(), "11\n222222\n33"); + eqPos(cm.getCursor(false), {line: 2, ch: 2}); + eqPos(cm.getCursor(true), {line: 0, ch: 4}); + cm.setSelection({line: 1, ch: 0}); + is(!cm.somethingSelected()); + eq(cm.getSelection(), ""); + eqPos(cm.getCursor(true), {line: 1, ch: 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), {line: 1, ch: 3}); + cm.setCursor({line: 2, ch: 1}); + eqPos(cm.getCursor(true), {line: 2, ch: 1}); + cm.setCursor(1, 2); + eqPos(cm.getCursor(true), {line: 1, ch: 2}); +}, {value: "111111\n222222\n333333"}); + +testCM("extendSelection", function(cm) { + cm.setExtending(true); + addDoc(cm, 10, 10); + cm.setSelection({line: 3, ch: 5}); + eqPos(cm.getCursor("head"), {line: 3, ch: 5}); + eqPos(cm.getCursor("anchor"), {line: 3, ch: 5}); + cm.setSelection({line: 2, ch: 5}, {line: 5, ch: 5}); + eqPos(cm.getCursor("head"), {line: 5, ch: 5}); + eqPos(cm.getCursor("anchor"), {line: 2, ch: 5}); + eqPos(cm.getCursor("start"), {line: 2, ch: 5}); + eqPos(cm.getCursor("end"), {line: 5, ch: 5}); + cm.setSelection({line: 5, ch: 5}, {line: 2, ch: 5}); + eqPos(cm.getCursor("head"), {line: 2, ch: 5}); + eqPos(cm.getCursor("anchor"), {line: 5, ch: 5}); + eqPos(cm.getCursor("start"), {line: 2, ch: 5}); + eqPos(cm.getCursor("end"), {line: 5, ch: 5}); + cm.extendSelection({line: 3, ch: 2}); + eqPos(cm.getCursor("head"), {line: 3, ch: 2}); + eqPos(cm.getCursor("anchor"), {line: 5, ch: 5}); + cm.extendSelection({line: 6, ch: 2}); + eqPos(cm.getCursor("head"), {line: 6, ch: 2}); + eqPos(cm.getCursor("anchor"), {line: 5, ch: 5}); + cm.extendSelection({line: 6, ch: 3}, {line: 6, ch: 4}); + eqPos(cm.getCursor("head"), {line: 6, ch: 4}); + eqPos(cm.getCursor("anchor"), {line: 5, ch: 5}); + cm.extendSelection({line: 0, ch: 3}, {line: 0, ch: 4}); + eqPos(cm.getCursor("head"), {line: 0, ch: 3}); + eqPos(cm.getCursor("anchor"), {line: 5, ch: 5}); + cm.extendSelection({line: 4, ch: 5}, {line: 6, ch: 5}); + eqPos(cm.getCursor("head"), {line: 6, ch: 5}); + eqPos(cm.getCursor("anchor"), {line: 4, ch: 5}); + cm.setExtending(false); + cm.extendSelection({line: 0, ch: 3}, {line: 0, ch: 4}); + eqPos(cm.getCursor("head"), {line: 0, ch: 4}); + eqPos(cm.getCursor("anchor"), {line: 0, ch: 3}); +}); + +testCM("lines", function(cm) { + eq(cm.getLine(0), "111111"); + eq(cm.getLine(1), "222222"); + eq(cm.getLine(-1), null); + cm.removeLine(1); + cm.setLine(1, "abc"); + eq(cm.getValue(), "111111\nabc"); +}, {value: "111111\n222222\n333333"}); + +testCM("indent", function(cm) { + cm.indentLine(1); + eq(cm.getLine(1), " blah();"); + cm.setOption("indentUnit", 8); + cm.indentLine(1); + eq(cm.getLine(1), "\tblah();"); + cm.setOption("indentUnit", 10); + cm.setOption("tabSize", 4); + cm.indentLine(1); + eq(cm.getLine(1), "\t\t blah();"); +}, {value: "if (x) {\nblah();\n}", indentUnit: 3, indentWithTabs: true, tabSize: 8}); + +test("core_defaults", function() { + var defsCopy = {}, defs = CodeMirror.defaults; + for (var opt in defs) defsCopy[opt] = defs[opt]; + defs.indentUnit = 5; + defs.value = "uu"; + defs.enterMode = "keep"; + defs.tabindex = 55; + var place = document.getElementById("testground"), cm = CodeMirror(place); + try { + eq(cm.getOption("indentUnit"), 5); + cm.setOption("indentUnit", 10); + eq(defs.indentUnit, 5); + eq(cm.getValue(), "uu"); + eq(cm.getOption("enterMode"), "keep"); + eq(cm.getInputField().tabIndex, 55); + } + finally { + for (var opt in defsCopy) defs[opt] = defsCopy[opt]; + place.removeChild(cm.getWrapperElement()); + } +}); + +testCM("lineInfo", function(cm) { + eq(cm.lineInfo(-1), null); + var mark = document.createElement("span"); + var lh = cm.setGutterMarker(1, "FOO", mark); + var info = cm.lineInfo(1); + eq(info.text, "222222"); + eq(info.gutterMarkers.FOO, mark); + eq(info.line, 1); + eq(cm.lineInfo(2).gutterMarkers, null); + cm.setGutterMarker(lh, "FOO", null); + eq(cm.lineInfo(1).gutterMarkers, null); + cm.setGutterMarker(1, "FOO", mark); + cm.setGutterMarker(0, "FOO", mark); + cm.clearGutter("FOO"); + eq(cm.lineInfo(0).gutterMarkers, null); + eq(cm.lineInfo(1).gutterMarkers, null); +}, {value: "111111\n222222\n333333"}); + +testCM("coords", function(cm) { + cm.setSize(null, 100); + addDoc(cm, 32, 200); + var top = cm.charCoords({line: 0, ch: 0}); + var bot = cm.charCoords({line: 200, ch: 30}); + is(top.left < bot.left); + is(top.top < bot.top); + is(top.top < top.bottom); + cm.scrollTo(null, 100); + var top2 = cm.charCoords({line: 0, ch: 0}); + is(top.top > top2.top); + eq(top.left, top2.left); +}); + +testCM("coordsChar", function(cm) { + addDoc(cm, 35, 70); + for (var ch = 0; ch <= 35; ch += 5) { + for (var line = 0; line < 70; line += 5) { + cm.setCursor(line, ch); + var coords = cm.charCoords({line: line, ch: ch}); + var pos = cm.coordsChar({left: coords.left, top: coords.top + 5}); + eqPos(pos, {line: line, ch: ch}); + } + } +}); + +testCM("posFromIndex", function(cm) { + cm.setValue( + "This function should\n" + + "convert a zero based index\n" + + "to line and ch." + ); + + var examples = [ + { index: -1, line: 0, ch: 0 }, // <- Tests clipping + { index: 0, line: 0, ch: 0 }, + { index: 10, line: 0, ch: 10 }, + { index: 39, line: 1, ch: 18 }, + { index: 55, line: 2, ch: 7 }, + { index: 63, line: 2, ch: 15 }, + { index: 64, line: 2, ch: 15 } // <- Tests clipping + ]; + + for (var i = 0; i < examples.length; i++) { + var example = examples[i]; + var pos = cm.posFromIndex(example.index); + eq(pos.line, example.line); + eq(pos.ch, example.ch); + if (example.index >= 0 && example.index < 64) + eq(cm.indexFromPos(pos), example.index); + } +}); + +testCM("undo", function(cm) { + cm.setLine(0, "def"); + eq(cm.historySize().undo, 1); + cm.undo(); + eq(cm.getValue(), "abc"); + eq(cm.historySize().undo, 0); + eq(cm.historySize().redo, 1); + cm.redo(); + eq(cm.getValue(), "def"); + eq(cm.historySize().undo, 1); + eq(cm.historySize().redo, 0); + cm.setValue("1\n\n\n2"); + cm.clearHistory(); + eq(cm.historySize().undo, 0); + for (var i = 0; i < 20; ++i) { + cm.replaceRange("a", {line: 0, ch: 0}); + cm.replaceRange("b", {line: 3, ch: 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("undoMultiLine", function(cm) { + cm.operation(function() { + cm.replaceRange("x", {line:0, ch: 0}); + cm.replaceRange("y", {line:1, ch: 0}); + }); + cm.undo(); + eq(cm.getValue(), "abc\ndef\nghi"); + cm.operation(function() { + cm.replaceRange("y", {line:1, ch: 0}); + cm.replaceRange("x", {line:0, ch: 0}); + }); + cm.undo(); + eq(cm.getValue(), "abc\ndef\nghi"); + cm.operation(function() { + cm.replaceRange("y", {line:2, ch: 0}); + cm.replaceRange("x", {line:1, ch: 0}); + cm.replaceRange("z", {line:2, ch: 0}); + }); + cm.undo(); + eq(cm.getValue(), "abc\ndef\nghi", 3); +}, {value: "abc\ndef\nghi"}); + +testCM("undoSelection", function(cm) { + cm.setSelection({line: 0, ch: 2}, {line: 0, ch: 4}); + cm.replaceSelection(""); + cm.setCursor({line: 1, ch: 0}); + cm.undo(); + eqPos(cm.getCursor(true), {line: 0, ch: 2}); + eqPos(cm.getCursor(false), {line: 0, ch: 4}); + cm.setCursor({line: 1, ch: 0}); + cm.redo(); + eqPos(cm.getCursor(true), {line: 0, ch: 2}); + eqPos(cm.getCursor(false), {line: 0, ch: 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({line: 0, ch: 3}, {line: 0, ch: 6}, {className: "foo"}); + cm.replaceRange(test.c, {line: 0, ch: test.a}, {line: 0, ch: 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 && {line: v[0], ch: 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({line: 0, ch: 5}, {line: 2, ch: 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({line: 0, ch: 1}, {line: 0, ch: 3}, + {className: "CodeMirror-matchingbracket"}); + marker2 = cm.markText({line: 0, ch: 0}, {line: 2, ch: 1}, + {className: "CodeMirror-matchingbracket"}); + bookmark = cm.setBookmark({line: 1, ch: 5}); + cm.operation(function(){ + cm.replaceRange("foo", {line: 0, ch: 2}); + cm.replaceRange("bar\baz\bug\n", {line: 2, ch: 0}, {line: 3, ch: 0}); + }); + cm.setValue(""); + eq(marker1.find(), null); eq(marker2.find(), null); eq(bookmark.find(), null); + cm.undo(); + eqPos(bookmark.find(), {line: 1, ch: 5}); + cm.undo(); + var m1Pos = marker1.find(), m2Pos = marker2.find(); + eqPos(m1Pos.from, {line: 0, ch: 1}); eqPos(m1Pos.to, {line: 0, ch: 3}); + eqPos(m2Pos.from, {line: 0, ch: 0}); eqPos(m2Pos.to, {line: 2, ch: 1}); + eqPos(bookmark.find(), {line: 1, ch: 5}); +}, {value: "1234\n56789\n00\n"}); + +testCM("markTextStayGone", function(cm) { + var m1 = cm.markText({line: 0, ch: 0}, {line: 0, ch: 1}); + cm.replaceRange("hi", {line: 0, ch: 2}); + m1.clear(); + cm.undo(); + eq(m1.find(), null); +}, {value: "hello"}); + +testCM("markClearBetween", function(cm) { + cm.setValue("aaa\nbbb\nccc\nddd\n"); + cm.markText({line: 0, ch: 0}, {line: 2}); + cm.replaceRange("aaa\nbbb\nccc", {line: 0, ch: 0}, {line: 2}); + eq(cm.findMarksAt({line: 1, ch: 1}).length, 0); +}); + +testCM("bookmark", function(cm) { + function p(v) { return v && {line: v[0], ch: 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) || {line: 1, ch: 5}); + cm.replaceRange(test.c, p(test.a), p(test.b)); + eqPos(b.find(), p(test.d)); + }); +}); + +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({line: 100, ch: 180}); + var info = cm.getScrollInfo(); + is(info.left > 0 && info.top > 0); + cm.setCursor({line: 0, ch: 0}); + info = cm.getScrollInfo(); + is(info.left == 0 && info.top == 0, "scrolled clean to top"); + cm.setCursor({line: 100, ch: 180}); + cm.setCursor({line: 199, ch: 0}); + info = cm.getScrollInfo(); + is(info.left == 0 && info.top + 2 > info.height - cm.getScrollerElement().clientHeight, "scrolled clean to bottom"); +}); + +testCM("selectionPos", function(cm) { + cm.setSize(100, 100); + addDoc(cm, 200, 100); + cm.setSelection({line: 1, ch: 100}, {line: 98, ch: 100}); + var lineWidth = cm.charCoords({line: 0, ch: 200}, "local").left; + var lineHeight = (cm.charCoords({line: 99}).top - cm.charCoords({line: 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); + 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({line: start, ch: 0}, {line: 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({line: 3, ch: 0}); + CodeMirror.commands.goLineDown(cm); + eqPos(cm.getCursor(), {line: 5, ch: 0}); + cm.setLine(3, "abcdefg"); + cm.setCursor({line: 3, ch: 6}); + CodeMirror.commands.goLineDown(cm); + eqPos(cm.getCursor(), {line: 5, ch: 4}); + cm.setLine(3, "ab"); + cm.setCursor({line: 3, ch: 2}); + CodeMirror.commands.goLineDown(cm); + eqPos(cm.getCursor(), {line: 5, ch: 2}); + range.clear(); range.clear(); + eq(cleared, 1); +}); + +testCM("hiddenLinesAutoUnfold", function(cm) { + var range = foldLines(cm, 1, 3, true), cleared = 0; + CodeMirror.on(range, "clear", function() {cleared++;}); + cm.setCursor({line: 3, ch: 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(), {line: 3, ch: 0}); + cm.setCursor({line: 0, ch: 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), {line: 10, ch: 0}); + eqPos(cm.getCursor(false), {line: 10, ch: 4}); +}); + + +testCM("everythingFolded", function(cm) { + addDoc(cm, 2, 2); + function enterPress() { + cm.triggerOnKeyDown({type: "keydown", keyCode: 13, preventDefault: function(){}, stopPropagation: function(){}}); + } + var fold = foldLines(cm, 0, 2); + enterPress(); + eq(cm.getValue(), "xx\nxx"); + fold.clear(); + fold = foldLines(cm, 0, 2, true); + eq(fold.find(), null); + enterPress(); + eq(cm.getValue(), "\nxx\nxx"); +}); + +testCM("structuredFold", function(cm) { + addDoc(cm, 4, 8); + var range = cm.markText({line: 1, ch: 2}, {line: 6, ch: 2}, { + replacedWith: document.createTextNode("Q") + }); + cm.setCursor(0, 3); + CodeMirror.commands.goLineDown(cm); + eqPos(cm.getCursor(), {line: 6, ch: 2}); + CodeMirror.commands.goCharLeft(cm); + eqPos(cm.getCursor(), {line: 1, ch: 2}); + CodeMirror.commands.delCharAfter(cm); + eq(cm.getValue(), "xxxx\nxxxx\nxxxx"); + addDoc(cm, 4, 8); + range = cm.markText({line: 1, ch: 2}, {line: 6, ch: 2}, { + replacedWith: document.createTextNode("x"), + clearOnEnter: true + }); + var cleared = 0; + CodeMirror.on(range, "clear", function(){++cleared;}); + cm.setCursor(0, 3); + CodeMirror.commands.goLineDown(cm); + eqPos(cm.getCursor(), {line: 6, ch: 2}); + CodeMirror.commands.goCharLeft(cm); + eqPos(cm.getCursor(), {line: 6, ch: 1}); + eq(cleared, 1); + range.clear(); + eq(cleared, 1); + range = cm.markText({line: 1, ch: 2}, {line: 6, ch: 2}, { + replacedWith: document.createTextNode("Q"), + clearOnEnter: true + }); + range.clear(); + cm.setCursor(1, 2); + CodeMirror.commands.goCharRight(cm); + eqPos(cm.getCursor(), {line: 1, ch: 3}); +}, null); + +testCM("nestedFold", function(cm) { + addDoc(cm, 10, 3); + function fold(ll, cl, lr, cr) { + return cm.markText({line: ll, ch: cl}, {line: lr, ch: 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(), {line: 2, ch: 3}); + inner0.clear(); + CodeMirror.commands.goCharLeft(cm); + eqPos(cm.getCursor(), {line: 0, ch: 1}); + outer.clear(); + CodeMirror.commands.goCharRight(cm); + eqPos(cm.getCursor(), {line: 0, ch: 2}); + CodeMirror.commands.goCharRight(cm); + eqPos(cm.getCursor(), {line: 1, ch: 8}); + inner2.clear(); + CodeMirror.commands.goCharLeft(cm); + eqPos(cm.getCursor(), {line: 1, ch: 7}); + cm.setCursor(0, 5); + CodeMirror.commands.goCharRight(cm); + eqPos(cm.getCursor(), {line: 0, ch: 6}); + CodeMirror.commands.goCharRight(cm); + eqPos(cm.getCursor(), {line: 1, ch: 3}); +}); + +testCM("badNestedFold", function(cm) { + addDoc(cm, 4, 4); + cm.markText({line: 0, ch: 2}, {line: 3, ch: 2}, {collapsed: true}); + var caught; + try {cm.markText({line: 0, ch: 1}, {line: 0, ch: 3}, {collapsed: true});} + catch(e) {caught = e;} + is(caught instanceof Error, "no error"); + is(/overlap/i.test(caught.message), "wrong error"); +}); + +testCM("inlineWidget", function(cm) { + var w = cm.setBookmark({line: 0, ch: 2}, document.createTextNode("uu")); + cm.setCursor(0, 2); + CodeMirror.commands.goLineDown(cm); + eqPos(cm.getCursor(), {line: 1, ch: 4}); + cm.setCursor(0, 2); + cm.replaceSelection("hi"); + eqPos(w.find(), {line: 0, ch: 2}); + cm.setCursor(0, 1); + cm.replaceSelection("ay"); + eqPos(w.find(), {line: 0, ch: 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({line: 0, ch: 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({line: 0, ch: 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", {line: 2, ch: 0}); + forEach([{line: 0, ch: doc.length}, {line: 0, ch: doc.length - 1}, + {line: 0, ch: 0}, {line: 1, ch: doc.length}, {line: 1, ch: 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({line: 0, ch: 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({line: 0, ch: 18}, "local"); + is(endPos.top > lh * .8, "not at top"); + is(endPos.left > w - 20, "not at right"); + endPos = cm.charCoords({line: 0, ch: 18}); + eqPos(cm.coordsChar({left: endPos.left, top: endPos.top + 5}), {line: 0, ch: 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({line: 0, ch: 26}, "div").right * 2.8;; w += 5) { + cm.setSize(w); + if (lines.offsetHeight <= 3.5 * h0) break; + } + cm.setCursor({line: 0, ch: val.length - 1}); + cm.moveV(-1, "line"); + eqPos(cm.getCursor(), {line: 0, ch: 26}); +}, {lineWrapping: true}, ie_lt8 || opera_lt10); + +testCM("clickTab", function(cm) { + var p0 = cm.charCoords({line: 0, ch: 0}); + eqPos(cm.coordsChar({left: p0.left + 5, top: p0.top + 5}), {line: 0, ch: 0}); + eqPos(cm.coordsChar({left: p0.right - 5, top: p0.top + 5}), {line: 0, ch: 1}); +}, {value: "\t\n\n", lineWrapping: true, tabSize: 8}); + +testCM("verticalScroll", function(cm) { + cm.setSize(100, 200); + cm.setValue("foo\nbar\nbaz\n"); + var sc = cm.getScrollerElement(), baseWidth = sc.scrollWidth; + cm.setLine(0, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah"); + is(sc.scrollWidth > baseWidth, "scrollbar present"); + cm.setLine(0, "foo"); + eq(sc.scrollWidth, baseWidth, "scrollbar gone"); + cm.setLine(0, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah"); + cm.setLine(1, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbh"); + is(sc.scrollWidth > baseWidth, "present again"); + var curWidth = sc.scrollWidth; + cm.setLine(0, "foo"); + is(sc.scrollWidth < curWidth, "scrollbar smaller"); + is(sc.scrollWidth > baseWidth, "but still present"); +}); + +testCM("extraKeys", function(cm) { + var outcome; + function fakeKey(expected, code, props) { + if (typeof code == "string") code = code.charCodeAt(0); + var e = {type: "keydown", keyCode: code, preventDefault: function(){}, stopPropagation: function(){}}; + if (props) for (var n in props) e[n] = props[n]; + outcome = null; + cm.triggerOnKeyDown(e); + eq(outcome, expected); + } + CodeMirror.commands.testCommand = function() {outcome = "tc";}; + CodeMirror.commands.goTestCommand = function() {outcome = "gtc";}; + cm.setOption("extraKeys", {"Shift-X": function() {outcome = "sx";}, + "X": function() {outcome = "x";}, + "Ctrl-Alt-U": function() {outcome = "cau";}, + "End": "testCommand", + "Home": "goTestCommand", + "Tab": false}); + fakeKey(null, "U"); + fakeKey("cau", "U", {ctrlKey: true, altKey: true}); + fakeKey(null, "U", {shiftKey: true, ctrlKey: true, altKey: true}); + fakeKey("x", "X"); + fakeKey("sx", "X", {shiftKey: true}); + fakeKey("tc", 35); + fakeKey(null, 35, {shiftKey: true}); + fakeKey("gtc", 36); + fakeKey("gtc", 36, {shiftKey: true}); + fakeKey(null, 9); +}, null, window.opera && mac); + +testCM("wordMovementCommands", function(cm) { + cm.execCommand("goWordLeft"); + eqPos(cm.getCursor(), {line: 0, ch: 0}); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqPos(cm.getCursor(), {line: 0, ch: 7}); + cm.execCommand("goWordLeft"); + eqPos(cm.getCursor(), {line: 0, ch: 5}); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqPos(cm.getCursor(), {line: 0, ch: 12}); + cm.execCommand("goWordLeft"); + eqPos(cm.getCursor(), {line: 0, ch: 9}); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqPos(cm.getCursor(), {line: 1, ch: 1}); + cm.execCommand("goWordRight"); + eqPos(cm.getCursor(), {line: 1, ch: 9}); + cm.execCommand("goWordRight"); + eqPos(cm.getCursor(), {line: 1, ch: 13}); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqPos(cm.getCursor(), {line: 2, ch: 0}); +}, {value: "this is (the) firstline.\na foo12\u00e9\u00f8\u00d7bar\n"}); + +testCM("charMovementCommands", function(cm) { + cm.execCommand("goCharLeft"); cm.execCommand("goColumnLeft"); + eqPos(cm.getCursor(), {line: 0, ch: 0}); + cm.execCommand("goCharRight"); cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), {line: 0, ch: 2}); + cm.setCursor({line: 1, ch: 0}); + cm.execCommand("goColumnLeft"); + eqPos(cm.getCursor(), {line: 1, ch: 0}); + cm.execCommand("goCharLeft"); + eqPos(cm.getCursor(), {line: 0, ch: 5}); + cm.execCommand("goColumnRight"); + eqPos(cm.getCursor(), {line: 0, ch: 5}); + cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), {line: 1, ch: 0}); + cm.execCommand("goLineEnd"); + eqPos(cm.getCursor(), {line: 1, ch: 5}); + cm.execCommand("goLineStartSmart"); + eqPos(cm.getCursor(), {line: 1, ch: 1}); + cm.execCommand("goLineStartSmart"); + eqPos(cm.getCursor(), {line: 1, ch: 0}); + cm.setCursor({line: 2, ch: 0}); + cm.execCommand("goCharRight"); cm.execCommand("goColumnRight"); + eqPos(cm.getCursor(), {line: 2, ch: 0}); +}, {value: "line1\n ine2\n"}); + +testCM("verticalMovementCommands", function(cm) { + cm.execCommand("goLineUp"); + eqPos(cm.getCursor(), {line: 0, ch: 0}); + cm.execCommand("goLineDown"); + if (!phantom) // This fails in PhantomJS, though not in a real Webkit + eqPos(cm.getCursor(), {line: 1, ch: 0}); + cm.setCursor({line: 1, ch: 12}); + cm.execCommand("goLineDown"); + eqPos(cm.getCursor(), {line: 2, ch: 5}); + cm.execCommand("goLineDown"); + eqPos(cm.getCursor(), {line: 3, ch: 0}); + cm.execCommand("goLineUp"); + eqPos(cm.getCursor(), {line: 2, ch: 5}); + cm.execCommand("goLineUp"); + eqPos(cm.getCursor(), {line: 1, ch: 12}); + cm.execCommand("goPageDown"); + eqPos(cm.getCursor(), {line: 5, ch: 0}); + cm.execCommand("goPageDown"); cm.execCommand("goLineDown"); + eqPos(cm.getCursor(), {line: 5, ch: 0}); + cm.execCommand("goPageUp"); + eqPos(cm.getCursor(), {line: 0, ch: 0}); +}, {value: "line1\nlong long line2\nline3\n\nline5\n"}); + +testCM("verticalMovementCommandsWrapping", function(cm) { + cm.setSize(120); + cm.setCursor({line: 0, ch: 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ج", "خمرحبها مها!"], 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({line: 0, ch: 2}); + cm.replaceSelection("خحج", "start"); + cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), {line: 0, ch: 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(), {line: 0, ch: 0}); + cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), {line: 1, ch: 0}); + cm.execCommand("goCharRight"); + cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), {line: 1, ch: 3}); + cm.execCommand("goCharRight"); + cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), {line: 1, ch: 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", {line: 0, ch: 1}); + cm.replaceRange("xy", {line: 1, ch: 1}, {line: 2}); + cm.replaceRange("foo\nbar", {line: 0, ch: 1}); + cm.replaceRange("", {line: 0, ch: 0}, {line: cm.lineCount()}); + eq(log.length, want.length, "same length"); + for (var i = 0; i < log.length; ++i) + eq(log[i], want[i]); +}); + +testCM("scrollEntirelyToRight", function(cm) { + addDoc(cm, 500, 2); + cm.setCursor({line: 0, ch: 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({line: 2, ch: 0}); + var node = document.createElement("div"); + node.innerHTML = "hi"; + var widget = cm.addLineWidget(1, node); + is(last.top < cm.charCoords({line: 2, ch: 0}).top, "took up space"); + cm.setCursor({line: 1, ch: 1}); + cm.execCommand("goLineDown"); + eqPos(cm.getCursor(), {line: 2, ch: 1}); + cm.execCommand("goLineUp"); + eqPos(cm.getCursor(), {line: 1, ch: 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", {line: 1, ch: 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", {line: 0, ch: 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({line: 0, ch: 1}); + cm.execCommand("goLineDown"); + eqPos(cm.getCursor(), {line: 1, ch: 1}); + cm.execCommand("goLineDown"); + eqPos(cm.getCursor(), {line: 2, ch: 1}); + cm.execCommand("goLineDown"); + eq(cm.getCursor().line, 2); + is(cm.getCursor().ch > 1); + cm.execCommand("goLineUp"); + eqPos(cm.getCursor(), {line: 2, ch: 1}); + cm.execCommand("goLineUp"); + eqPos(cm.getCursor(), {line: 1, ch: 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({line: 0, ch: 2}); + cm.execCommand("goLineDown"); + eqPos(cm.getCursor(), {line: 1, ch: 2}); + cm.execCommand("goLineUp"); + eqPos(cm.getCursor(), {line: 0, ch: 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"); + eq(byClassName(cm.getWrapperElement(), "foo").length, 2); + eq(byClassName(cm.getWrapperElement(), "bar").length, 1); + eq(byClassName(cm.getWrapperElement(), "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({line: ll, ch: cl}, {line: lr, ch: cr}, + {atomic: true, inclusiveLeft: li, inclusiveRight: ri}); + } + var m = atom(0, 1, 0, 5); + cm.setCursor({line: 0, ch: 1}); + cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), {line: 0, ch: 5}); + cm.execCommand("goCharLeft"); + eqPos(cm.getCursor(), {line: 0, ch: 1}); + m.clear(); + m = atom(0, 0, 0, 5, true); + eqPos(cm.getCursor(), {line: 0, ch: 5}, "pushed out"); + cm.execCommand("goCharLeft"); + eqPos(cm.getCursor(), {line: 0, ch: 5}); + m.clear(); + m = atom(8, 4, 9, 10, false, true); + cm.setCursor({line: 9, ch: 8}); + eqPos(cm.getCursor(), {line: 8, ch: 4}, "set"); + cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), {line: 8, ch: 4}, "char right"); + cm.execCommand("goLineDown"); + eqPos(cm.getCursor(), {line: 8, ch: 4}, "line down"); + cm.execCommand("goCharLeft"); + eqPos(cm.getCursor(), {line: 8, ch: 3}); + m.clear(); + m = atom(1, 1, 3, 8); + cm.setCursor({line: 2, ch: 0}); + eqPos(cm.getCursor(), {line: 3, ch: 8}); + cm.execCommand("goCharLeft"); + eqPos(cm.getCursor(), {line: 1, ch: 1}); + cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), {line: 3, ch: 8}); + cm.execCommand("goLineUp"); + eqPos(cm.getCursor(), {line: 1, ch: 1}); + cm.execCommand("goLineDown"); + eqPos(cm.getCursor(), {line: 3, ch: 8}); + cm.execCommand("delCharBefore"); + eq(cm.getValue().length, 80, "del chunk"); + m = atom(3, 0, 5, 5); + cm.setCursor({line: 3, ch: 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({line: ll, ch: cl}, {line: lr, ch: cr}, + {readOnly: true, atomic: at}); + } + var m = mark(0, 1, 0, 4); + cm.setCursor({line: 0, ch: 2}); + cm.replaceSelection("hi", "end"); + eqPos(cm.getCursor(), {line: 0, ch: 2}); + eq(cm.getLine(0), "abcde"); + cm.execCommand("selectAll"); + cm.replaceSelection("oops"); + eq(cm.getValue(), "oopsbcd"); + cm.undo(); + eqPos(m.find().from, {line: 0, ch: 1}); + eqPos(m.find().to, {line: 0, ch: 4}); + m.clear(); + cm.setCursor({line: 0, ch: 2}); + cm.replaceSelection("hi"); + eq(cm.getLine(0), "abhicde"); + eqPos(cm.getCursor(), {line: 0, ch: 4}); + m = mark(0, 2, 2, 2, true); + cm.setSelection({line: 1, ch: 1}, {line: 2, ch: 4}); + cm.replaceSelection("t", "end"); + eqPos(cm.getCursor(), {line: 2, ch: 3}); + eq(cm.getLine(2), "klto"); + cm.execCommand("goCharLeft"); + cm.execCommand("goCharLeft"); + eqPos(cm.getCursor(), {line: 0, ch: 2}); + cm.setSelection({line: 0, ch: 1}, {line: 0, ch: 3}); + cm.replaceSelection("xx"); + eqPos(cm.getCursor(), {line: 0, ch: 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(), {line: 0, ch: 1}); + var test = 0; + var map1 = {Right: function() { ++test; }}, map2 = {Right: function() { test += 10; }} + cm.addKeyMap(map1); + sendKey(39); + eqPos(cm.getCursor(), {line: 0, ch: 1}); + eq(test, 1); + cm.addKeyMap(map2); + sendKey(39); + eq(test, 2); + cm.removeKeyMap(map1); + sendKey(39); + eq(test, 12); + cm.removeKeyMap(map2); + sendKey(39); + eq(test, 12); + eqPos(cm.getCursor(), {line: 0, ch: 2}); + cm.addKeyMap({Right: function() { test = 55; }, name: "mymap"}); + sendKey(39); + eq(test, 55); + cm.removeKeyMap("mymap"); + sendKey(39); + eqPos(cm.getCursor(), {line: 0, ch: 3}); +}, {value: "abc"}); diff --git a/codemirror/test/vim_test.js b/codemirror/test/vim_test.js new file mode 100644 index 0000000..a4531d3 --- /dev/null +++ b/codemirror/test/vim_test.js @@ -0,0 +1,812 @@ +var code = '' + +' wOrd1 (#%\n' + +' word3] \n' + +'aopop pop 0 1 2 3 4\n' + +' (a) [b] {c} \n' + +'int getchar(void) {\n' + +' static char buf[BUFSIZ];\n' + +' static char *bufp = buf;\n' + +' if (n == 0) { /* buffer is empty */\n' + +' n = read(0, buf, sizeof buf);\n' + +' bufp = buf;\n' + +' }\n' + +' return (--n >= 0) ? (unsigned char) *bufp++ : EOF;\n' + +'}\n'; + +var lines = (function() { + lineText = code.split('\n'); + var ret = []; + for (var i = 0; i < lineText.length; i++) { + ret[i] = { + line: i, + length: lineText[i].length, + lineText: lineText[i], + textStart: /^\s*/.exec(lineText[i])[0].length + }; + } + return ret; +})(); +var endOfDocument = makeCursor(lines.length - 1, + lines[lines.length - 1].length); +var wordLine = lines[0]; +var bigWordLine = lines[1]; +var charLine = lines[2]; +var bracesLine = lines[3]; + +var word1 = { + start: { line: wordLine.line, ch: 1 }, + end: { line: wordLine.line, ch: 5 } +}; +var word2 = { + start: { line: wordLine.line, ch: word1.end.ch + 2 }, + end: { line: wordLine.line, ch: word1.end.ch + 4 } +}; +var word3 = { + start: { line: bigWordLine.line, ch: 1 }, + end: { line: bigWordLine.line, ch: 5 } +}; +var bigWord1 = word1; +var bigWord2 = word2; +var bigWord3 = { + start: { line: bigWordLine.line, ch: 1 }, + end: { line: bigWordLine.line, ch: 7 } +}; +var bigWord4 = { + start: { line: bigWordLine.line, ch: bigWord1.end.ch + 3 }, + end: { line: bigWordLine.line, ch: bigWord1.end.ch + 7 } +} +var oChars = [ { line: charLine.line, ch: 1 }, + { line: charLine.line, ch: 3 }, + { line: charLine.line, ch: 7 } ]; +var pChars = [ { line: charLine.line, ch: 2 }, + { line: charLine.line, ch: 4 }, + { line: charLine.line, ch: 6 }, + { line: charLine.line, ch: 8 } ]; +var numChars = [ { line: charLine.line, ch: 10 }, + { line: charLine.line, ch: 12 }, + { line: charLine.line, ch: 14 }, + { line: charLine.line, ch: 16 }, + { line: charLine.line, ch: 18 }]; +var parens1 = { + start: { line: bracesLine.line, ch: 1 }, + end: { line: bracesLine.line, ch: 3 } +}; +var squares1 = { + start: { line: bracesLine.line, ch: 5 }, + end: { line: bracesLine.line, ch: 7 } +}; +var curlys1 = { + start: { line: bracesLine.line, ch: 9 }, + end: { line: bracesLine.line, ch: 11 } +}; + +function copyCursor(cur) { + return { ch: cur.ch, line: cur.line }; +} + +function testVim(name, run, opts, expectedFail) { + var vimOpts = { + lineNumbers: true, + mode: 'text/x-csrc', + keyMap: 'vim', + showCursorWhenSelecting: true, + value: code + }; + for (var prop in opts) { + if (opts.hasOwnProperty(prop)) { + vimOpts[prop] = opts[prop]; + } + } + return test('vim_' + name, function() { + var place = document.getElementById("testground"); + var cm = CodeMirror(place, vimOpts); + CodeMirror.Vim.maybeInitState(cm); + var vim = cm.vimState; + + function doKeysFn(cm) { + return function(args) { + if (args instanceof Array) { + arguments = args; + } + for (var i = 0; i < arguments.length; i++) { + CodeMirror.Vim.handleKey(cm, arguments[i]); + } + } + } + function 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), + assertCursorAt: assertCursorAtFn(cm), + fakeOpenDialog: fakeOpenDialog, + getRegisterController: function() { + return CodeMirror.Vim.getRegisterController(); + } + } + CodeMirror.Vim.clearVimGlobalState_(); + var successful = false; + try { + run(cm, vim, helpers); + successful = true; + } finally { + if ((debug && !successful) || verbose) { + place.style.visibility = "visible"; + } else { + place.removeChild(cm.getWrapperElement()); + } + } + }, expectedFail); +}; + +/** + * @param name Name of the test + * @param keys An array of keys or a string with a single key to simulate. + * @param endPos The expected end position of the cursor. + * @param startPos The position the cursor should start at, defaults to 0, 0. + */ +function testMotion(name, keys, endPos, startPos) { + testVim(name, function(cm, vim, helpers) { + if (!startPos) { + startPos = { line: 0, ch: 0 }; + } + cm.setCursor(startPos); + helpers.doKeys(keys); + helpers.assertCursorAt(endPos); + }); +}; + +function makeCursor(line, ch) { + return { line: line, ch: ch }; +}; + +function offsetCursor(cur, offsetLine, offsetCh) { + return { line: cur.line + offsetLine, ch: cur.ch + offsetCh }; +}; + +// Motion tests +testMotion('|', '|', makeCursor(0, 0), makeCursor(0,4)); +testMotion('|_repeat', ['3', '|'], makeCursor(0, 2), makeCursor(0,4)); +testMotion('h', 'h', makeCursor(0, 0), word1.start); +testMotion('h_repeat', ['3', 'h'], offsetCursor(word1.end, 0, -3), word1.end); +testMotion('l', 'l', makeCursor(0, 1)); +testMotion('l_repeat', ['2', 'l'], makeCursor(0, 2)); +testMotion('j', 'j', offsetCursor(word1.end, 1, 0), word1.end); +testMotion('j_repeat', ['2', 'j'], offsetCursor(word1.end, 2, 0), word1.end); +testMotion('k', 'k', offsetCursor(word3.end, -1, 0), word3.end); +testMotion('k_repeat', ['2', 'k'], makeCursor(0, 4), makeCursor(2, 4)); +testMotion('w', 'w', word1.start); +testMotion('w_repeat', ['2', 'w'], word2.start); +testMotion('w_wrap', ['w'], word3.start, word2.start); +testMotion('w_endOfDocument', 'w', endOfDocument, endOfDocument); +testMotion('W', 'W', bigWord1.start); +testMotion('W_repeat', ['2', 'W'], bigWord3.start, bigWord1.start); +testMotion('e', 'e', word1.end); +testMotion('e_repeat', ['2', 'e'], word2.end); +testMotion('e_wrap', 'e', word3.end, word2.end); +testMotion('e_endOfDocument', 'e', endOfDocument, endOfDocument); +testMotion('b', 'b', word3.start, word3.end); +testMotion('b_repeat', ['2', 'b'], word2.start, word3.end); +testMotion('b_wrap', 'b', word2.start, word3.start); +testMotion('b_startOfDocument', 'b', makeCursor(0, 0), makeCursor(0, 0)); +testMotion('ge', ['g', 'e'], word2.end, word3.end); +testMotion('ge_repeat', ['2', 'g', 'e'], word1.end, word3.start); +testMotion('ge_wrap', ['g', 'e'], word2.end, word3.start); +testMotion('ge_startOfDocument', ['g', 'e'], makeCursor(0, 0), + makeCursor(0, 0)); +testMotion('gg', ['g', 'g'], makeCursor(lines[0].line, lines[0].textStart), + makeCursor(3, 1)); +testMotion('gg_repeat', ['3', 'g', 'g'], + makeCursor(lines[2].line, lines[2].textStart)); +testMotion('G', 'G', + makeCursor(lines[lines.length - 1].line, lines[lines.length - 1].textStart), + makeCursor(3, 1)); +testMotion('G_repeat', ['3', 'G'], makeCursor(lines[2].line, + lines[2].textStart)); +// TODO: Make the test code long enough to test Ctrl-F and Ctrl-B. +testMotion('0', '0', makeCursor(0, 0), makeCursor(0, 8)); +testMotion('^', '^', makeCursor(0, lines[0].textStart), makeCursor(0, 8)); +testMotion('$', '$', makeCursor(0, lines[0].length - 1), makeCursor(0, 1)); +testMotion('$_repeat', ['2', '$'], makeCursor(1, lines[1].length - 1), + makeCursor(0, 3)); +testMotion('f', ['f', 'p'], pChars[0], makeCursor(charLine.line, 0)); +testMotion('f_repeat', ['2', 'f', 'p'], pChars[2], pChars[0]); +testMotion('f_num', ['f', '2'], numChars[2], makeCursor(charLine.line, 0)); +testMotion('t', ['t','p'], offsetCursor(pChars[0], 0, -1), + makeCursor(charLine.line, 0)); +testMotion('t_repeat', ['2', 't', 'p'], offsetCursor(pChars[2], 0, -1), + pChars[0]); +testMotion('F', ['F', 'p'], pChars[0], pChars[1]); +testMotion('F_repeat', ['2', 'F', 'p'], pChars[0], pChars[2]); +testMotion('T', ['T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[1]); +testMotion('T_repeat', ['2', 'T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[2]); +testMotion('%_parens', ['%'], parens1.end, parens1.start); +testMotion('%_squares', ['%'], squares1.end, squares1.start); +testMotion('%_braces', ['%'], curlys1.end, curlys1.start); +// Make sure that moving down after going to the end of a line always leaves you +// at the end of a line, but preserves the offset in other cases +testVim('Changing lines after Eol operation', function(cm, vim, helpers) { + var startPos = { line: 0, ch: 0 }; + cm.setCursor(startPos); + helpers.doKeys(['$']); + helpers.doKeys(['j']); + // After moving to Eol and then down, we should be at Eol of line 2 + helpers.assertCursorAt({ line: 1, ch: lines[1].length - 1 }); + helpers.doKeys(['j']); + // After moving down, we should be at Eol of line 3 + helpers.assertCursorAt({ line: 2, ch: lines[2].length - 1 }); + helpers.doKeys(['h']); + helpers.doKeys(['j']); + // After moving back one space and then down, since line 4 is shorter than line 2, we should + // be at Eol of line 2 - 1 + helpers.assertCursorAt({ line: 3, ch: lines[3].length - 1 }); + helpers.doKeys(['j']); + helpers.doKeys(['j']); + // After moving down again, since line 3 has enough characters, we should be back to the + // same place we were at on line 1 + helpers.assertCursorAt({ line: 5, ch: lines[2].length - 2 }); +}); + +// Operator tests +testVim('dl', function(cm, vim, helpers) { + var curStart = makeCursor(0, 0); + cm.setCursor(curStart); + helpers.doKeys('d', 'l'); + eq('word1 ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(' ', register.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1 ' }); +testVim('dl_eol', function(cm, vim, helpers) { + var curStart = makeCursor(0, 6); + cm.setCursor(curStart); + helpers.doKeys('d', 'l'); + eq(' word1', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(' ', register.text); + is(!register.linewise); + helpers.assertCursorAt(makeCursor(0, 6)); +}, { value: ' word1 ' }); +testVim('dl_repeat', function(cm, vim, helpers) { + var curStart = makeCursor(0, 0); + cm.setCursor(curStart); + helpers.doKeys('2', 'd', 'l'); + eq('ord1 ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(' w', register.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1 ' }); +testVim('dh', function(cm, vim, helpers) { + var curStart = makeCursor(0, 3); + cm.setCursor(curStart); + helpers.doKeys('d', 'h'); + eq(' wrd1 ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('o', register.text); + is(!register.linewise); + eqPos(offsetCursor(curStart, 0 , -1), cm.getCursor()); +}, { value: ' word1 ' }); +testVim('dj', function(cm, vim, helpers) { + var curStart = makeCursor(0, 3); + cm.setCursor(curStart); + helpers.doKeys('d', 'j'); + eq(' word3', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(' word1\nword2\n', register.text); + is(register.linewise); + eqPos(makeCursor(0, 1), cm.getCursor()); +}, { 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); + eqPos(makeCursor(0, 1), cm.getCursor()); +}, { value: ' word1\nword2\n word3' }); +testVim('dk_start_of_document', function(cm, vim, helpers) { + var curStart = makeCursor(0, 3); + cm.setCursor(curStart); + helpers.doKeys('d', 'k'); + eq(' word1 ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('', register.text); + is(!register.linewise); + helpers.assertCursorAt(0, 3); +}, { value: ' word1 ' }); +testVim('dw_space', function(cm, vim, helpers) { + var curStart = makeCursor(0, 0); + cm.setCursor(curStart); + helpers.doKeys('d', 'w'); + eq('word1 ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(' ', register.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1 ' }); +testVim('dw_word', function(cm, vim, helpers) { + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('d', 'w'); + eq(' word2', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1 ', register.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1 word2' }); +testVim('dw_only_word', function(cm, vim, helpers) { + // Test that if there is only 1 word left, dw deletes till the end of the + // line. + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('d', 'w'); + eq(' ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1 ', register.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1 ' }); +testVim('dw_eol', function(cm, vim, helpers) { + // Assert that dw does not delete the newline if last word to delete is at end + // of line. + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('d', 'w'); + eq(' \nword2', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1', register.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1\nword2' }); +testVim('dw_repeat', function(cm, vim, helpers) { + // Assert that dw does delete newline if it should go to the next line, and + // that repeat works properly. + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('d', '2', 'w'); + eq(' ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1\nword2', register.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1\nword2' }); +testVim('d_inclusive', function(cm, vim, helpers) { + // Assert that when inclusive is set, the character the cursor is on gets + // deleted too. + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('d', 'e'); + eq(' ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1', register.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1 ' }); +testVim('d_reverse', function(cm, vim, helpers) { + // Test that deleting in reverse works. + cm.setCursor(1, 0); + helpers.doKeys('d', 'b'); + eq(' word2 ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1\n', register.text); + is(!register.linewise); + eqPos(makeCursor(0, 1), cm.getCursor()); +}, { 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); + eqPos(makeCursor(0, lines[1].textStart), cm.getCursor()); +}); +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); + eqPos(makeCursor(0, lines[2].textStart), cm.getCursor()); +}); +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); + eqPos(makeCursor(0, lines[2].textStart), cm.getCursor()); +}); +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); + eqPos(makeCursor(0, lines[6].textStart), cm.getCursor()); +}); +// Yank commands should behave the exact same as d commands, expect that nothing +// gets deleted. +testVim('yw_repeat', function(cm, vim, helpers) { + // Assert that yw does yank newline if it should go to the next line, and + // that repeat works properly. + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('y', '2', 'w'); + eq(' word1\nword2', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1\nword2', register.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1\nword2' }); +testVim('yy_multiply_repeat', function(cm, vim, helpers) { + var curStart = makeCursor(0, 3); + cm.setCursor(curStart); + var expectedBuffer = cm.getRange({ line: 0, ch: 0 }, + { line: 6, ch: 0 }); + var expectedLineCount = cm.lineCount(); + helpers.doKeys('2', 'y', '3', 'y'); + eq(expectedLineCount, cm.lineCount()); + var register = helpers.getRegisterController().getRegister(); + eq(expectedBuffer, register.text); + is(register.linewise); + eqPos(curStart, cm.getCursor()); +}); +// Change commands behave like d commands except that it also enters insert +// mode. In addition, when the change is linewise, an additional newline is +// inserted so that insert mode starts on that line. +testVim('cw_repeat', function(cm, vim, helpers) { + // Assert that cw does delete newline if it should go to the next line, and + // that repeat works properly. + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('c', '2', 'w'); + eq(' ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1\nword2', register.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); + eq('vim-insert', cm.getOption('keyMap')); +}, { value: ' word1\nword2' }); +testVim('cc_multiply_repeat', function(cm, vim, helpers) { + cm.setCursor(0, 3); + var expectedBuffer = cm.getRange({ line: 0, ch: 0 }, + { line: 6, ch: 0 }); + var expectedLineCount = cm.lineCount() - 5; + helpers.doKeys('2', 'c', '3', 'c'); + eq(expectedLineCount, cm.lineCount()); + var register = helpers.getRegisterController().getRegister(); + eq(expectedBuffer, register.text); + is(register.linewise); + eqPos(makeCursor(0, lines[0].textStart), cm.getCursor()); + eq('vim-insert', cm.getOption('keyMap')); +}); +// Swapcase commands edit in place and do not modify registers. +testVim('g~w_repeat', function(cm, vim, helpers) { + // Assert that dw does delete newline if it should go to the next line, and + // that repeat works properly. + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('g', '~', '2', 'w'); + eq(' WORD1\nWORD2', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('', register.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1\nword2' }); +testVim('g~g~', function(cm, vim, helpers) { + var curStart = makeCursor(0, 3); + cm.setCursor(curStart); + var expectedLineCount = cm.lineCount(); + var expectedValue = cm.getValue().toUpperCase(); + helpers.doKeys('2', 'g', '~', '3', 'g', '~'); + eq(expectedValue, cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('', register.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1\nword2\nword3\nword4\nword5\nword6' }); +testVim('>{motion}', function(cm, vim, helpers) { + cm.setCursor(1, 3); + var expectedLineCount = cm.lineCount(); + var expectedValue = ' word1\n word2\nword3 '; + helpers.doKeys('>', 'k'); + eq(expectedValue, cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('', register.text); + is(!register.linewise); + eqPos(makeCursor(0, 3), cm.getCursor()); +}, { 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); + eqPos(makeCursor(0, 3), cm.getCursor()); +}, { 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); + eqPos(makeCursor(0, 1), cm.getCursor()); +}, { 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); + eqPos(makeCursor(0, 1), cm.getCursor()); +}, { value: ' word1\n word2\nword3 ', indentUnit: 2 }); + +// Operator-motion tests +testVim('D', function(cm, vim, helpers) { + var curStart = makeCursor(0, 3); + cm.setCursor(curStart); + helpers.doKeys('D'); + eq(' wo\nword2\n word3', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('rd1', register.text); + is(!register.linewise); + eqPos(makeCursor(0, 3), cm.getCursor()); +}, { 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(makeCursor(0, 3), 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); + eqPos(makeCursor(0, 3), cm.getCursor()); +}, { value: ' word1\nword2\n word3' }); + +// Action tests +testVim('a', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('a'); + eqPos(makeCursor(0, 2), cm.getCursor()); + 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(makeCursor(0, lines[0].length)); + eq('vim-insert', cm.getOption('keyMap')); +}); +testVim('i', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('i'); + eqPos(makeCursor(0, 1), cm.getCursor()); + eq('vim-insert', cm.getOption('keyMap')); +}); +testVim('A', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('A'); + eqPos(makeCursor(0, lines[0].length), cm.getCursor()); + eq('vim-insert', cm.getOption('keyMap')); +}); +testVim('I', function(cm, vim, helpers) { + cm.setCursor(0, 4); + helpers.doKeys('I'); + eqPos(makeCursor(0, lines[0].textStart), cm.getCursor()); + eq('vim-insert', cm.getOption('keyMap')); +}); +testVim('o', function(cm, vim, helpers) { + cm.setCursor(0, 4); + helpers.doKeys('o'); + eq('word1\n\nword2', cm.getValue()); + eqPos(makeCursor(1, 0), cm.getCursor()); + eq('vim-insert', cm.getOption('keyMap')); +}, { value: 'word1\nword2' }); +testVim('O', function(cm, vim, helpers) { + cm.setCursor(0, 4); + helpers.doKeys('O'); + eq('\nword1\nword2', cm.getValue()); + eqPos(makeCursor(0, 0), cm.getCursor()); + 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()); + eqPos(makeCursor(0, expectedValue.indexOf('word2') - 1), cm.getCursor()); +}, { 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()); + eqPos(makeCursor(0, expectedValue.indexOf('word3') - 1), cm.getCursor()); +}, { 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()); + eqPos(makeCursor(1, 2), cm.getCursor()); +}, { 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()); + eqPos(makeCursor(1, 2), cm.getCursor()); +}, { 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()); + eqPos(makeCursor(0, 1), cm.getCursor()); +}, { 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()); + eqPos(makeCursor(1, 2), cm.getCursor()); +}, { 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()); + eqPos(makeCursor(1, 3), cm.getCursor()); +}, { 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()); + eqPos(makeCursor(0, 2), cm.getCursor()); +}, { value: '___' }); +testVim('r', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('3', 'r', 'u'); + eq('wuuuet', cm.getValue()); + eqPos(makeCursor(0, 3), cm.getCursor()); +}, { value: 'wordet' }); +testVim('/ and n/N', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('match'); + helpers.doKeys('/'); + helpers.assertCursorAt(makeCursor(0, 11)); + helpers.doKeys('n'); + helpers.assertCursorAt(makeCursor(1, 6)); + helpers.doKeys('N'); + helpers.assertCursorAt(makeCursor(0, 11)); + + cm.setCursor(0, 0); + helpers.doKeys('2', '/'); + helpers.assertCursorAt(makeCursor(1, 6)); +}, { value: 'match nope match \n nope Match' }); +testVim('/_case', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('Match'); + helpers.doKeys('/'); + helpers.assertCursorAt(makeCursor(1, 6)); +}, { value: 'match nope match \n nope Match' }); +testVim('? and n/N', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('match'); + helpers.doKeys('?'); + helpers.assertCursorAt(makeCursor(1, 6)); + helpers.doKeys('n'); + helpers.assertCursorAt(makeCursor(0, 11)); + helpers.doKeys('N'); + helpers.assertCursorAt(makeCursor(1, 6)); + + cm.setCursor(0, 0); + helpers.doKeys('2', '?'); + helpers.assertCursorAt(makeCursor(0, 11)); +}, { value: 'match nope match \n nope Match' }); +testVim(',/ clearSearchHighlight', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('match'); + helpers.doKeys('?'); + helpers.doKeys(',', '/', 'n'); + helpers.assertCursorAt(0, 11); +}, { value: 'match nope match \n nope Match' }); +testVim('*', function(cm, vim, helpers) { + cm.setCursor(0, 9); + helpers.doKeys('*'); + helpers.assertCursorAt(makeCursor(0, 22)); + + cm.setCursor(0, 9); + helpers.doKeys('2', '*'); + helpers.assertCursorAt(makeCursor(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(makeCursor(1, 8)); + + cm.setCursor(0, 9); + helpers.doKeys('2', '#'); + helpers.assertCursorAt(makeCursor(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(makeCursor(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(makeCursor(1, 8)); +}, { value: ' := match nomatch match \nnomatch Match' }); diff --git a/codemirror/theme/ambiance-mobile.css b/codemirror/theme/ambiance-mobile.css new file mode 100644 index 0000000..35b3750 --- /dev/null +++ b/codemirror/theme/ambiance-mobile.css @@ -0,0 +1,6 @@ +.cm-s-ambiance.CodeMirror { + -webkit-box-shadow: none; + -moz-box-shadow: none; + -o-box-shadow: none; + box-shadow: none; +} diff --git a/codemirror/theme/ambiance.css b/codemirror/theme/ambiance.css new file mode 100644 index 0000000..beec553 --- /dev/null +++ b/codemirror/theme/ambiance.css @@ -0,0 +1,76 @@ +/* ambiance theme for codemirror */ + +/* Color scheme */ + +.cm-s-ambiance .cm-keyword { color: #cda869; } +.cm-s-ambiance .cm-atom { color: #CF7EA9; } +.cm-s-ambiance .cm-number { color: #78CF8A; } +.cm-s-ambiance .cm-def { color: #aac6e3; } +.cm-s-ambiance .cm-variable { color: #ffb795; } +.cm-s-ambiance .cm-variable-2 { color: #eed1b3; } +.cm-s-ambiance .cm-variable-3 { color: #faded3; } +.cm-s-ambiance .cm-property { color: #eed1b3; } +.cm-s-ambiance .cm-operator {color: #fa8d6a;} +.cm-s-ambiance .cm-comment { color: #555; font-style:italic; } +.cm-s-ambiance .cm-string { color: #8f9d6a; } +.cm-s-ambiance .cm-string-2 { color: #9d937c; } +.cm-s-ambiance .cm-meta { color: #D2A8A1; } +.cm-s-ambiance .cm-error { color: #AF2018; } +.cm-s-ambiance .cm-qualifier { color: yellow; } +.cm-s-ambiance .cm-builtin { color: #9999cc; } +.cm-s-ambiance .cm-bracket { color: #24C2C7; } +.cm-s-ambiance .cm-tag { color: #fee4ff } +.cm-s-ambiance .cm-attribute { color: #9B859D; } +.cm-s-ambiance .cm-header {color: blue;} +.cm-s-ambiance .cm-quote { color: #24C2C7; } +.cm-s-ambiance .cm-hr { color: pink; } +.cm-s-ambiance .cm-link { color: #F4C20B; } +.cm-s-ambiance .cm-special { color: #FF9D00; } + +.cm-s-ambiance .CodeMirror-matchingbracket { color: #0f0; } +.cm-s-ambiance .CodeMirror-nonmatchingbracket { color: #f22; } + +.cm-s-ambiance .CodeMirror-selected { + background: rgba(255, 255, 255, 0.15); +} +.cm-s-ambiance .CodeMirror-focused .CodeMirror-selected { + background: rgba(255, 255, 255, 0.10); +} + +/* Editor styling */ + +.cm-s-ambiance.CodeMirror { + line-height: 1.40em; + font-family: Monaco, Menlo,"Andale Mono","lucida console","Courier New",monospace !important; + color: #E6E1DC; + background-color: #202020; + -webkit-box-shadow: inset 0 0 10px black; + -moz-box-shadow: inset 0 0 10px black; + -o-box-shadow: inset 0 0 10px black; + box-shadow: inset 0 0 10px black; +} + +.cm-s-ambiance .CodeMirror-gutters { + background: #3D3D3D; + border-right: 1px solid #4D4D4D; + box-shadow: 0 10px 20px black; +} + +.cm-s-ambiance .CodeMirror-linenumber { + text-shadow: 0px 1px 1px #4d4d4d; + color: #222; + padding: 0 5px; +} + +.cm-s-ambiance .CodeMirror-lines .CodeMirror-cursor { + border-left: 1px solid #7991E8; +} + +.cm-s-ambiance .activeline { + background: none repeat scroll 0% 0% rgba(255, 255, 255, 0.031); +} + +.cm-s-ambiance.CodeMirror, +.cm-s-ambiance .CodeMirror-gutters { + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAQAAAAHUWYVAABFFUlEQVQYGbzBCeDVU/74/6fj9HIcx/FRHx9JCFmzMyGRURhLZIkUsoeRfUjS2FNDtr6WkMhO9sm+S8maJfu+Jcsg+/o/c+Z4z/t97/vezy3z+z8ekGlnYICG/o7gdk+wmSHZ1z4pJItqapjoKXWahm8NmV6eOTbWUOp6/6a/XIg6GQqmenJ2lDHyvCFZ2cBDbmtHA043VFhHwXxClWmeYAdLhV00Bd85go8VmaFCkbVkzlQENzfBDZ5gtN7HwF0KDrTwJ0dypSOzpaKCMwQHKTIreYIxlmhXTzTWkVm+LTynZhiSBT3RZQ7aGfjGEd3qyXQ1FDymqbKxpspERQN2MiRjNZlFFQXfCNFm9nM1zpAsoYjmtRTc5ajwuaXc5xrWskT97RaKzAGe5ARHhVUsDbjKklziiX5WROcJwSNCNI+9w1Jwv4Zb2r7lCMZ4oq5C0EdTx+2GzNuKpJ+iFf38JEWkHJn9DNF7mmBDITrWEg0VWL3pHU20tSZnuqWu+R3BtYa8XxV1HO7GyD32UkOpL/yDloINFTmvtId+nmAjxRw40VMwVKiwrKLE4bK5UOVntYwhOcSSXKrJHKPJedocpGjVz/ZMIbnYUPB10/eKCrs5apqpgVmWzBYWpmtKHecJPjaUuEgRDDaU0oZghCJ6zNMQ5ZhDYx05r5v2muQdM0EILtXUsaKiQX9WMEUotagQzFbUNN6NUPC2nm5pxEWGCjMc3GdJHjSU2kORLK/JGSrkfGEIjncU/CYUnOipoYemwj8tST9NsJmB7TUVXtbUtXATJVZXBMvYeTXJfobgJUPmGMP/yFaWonaa6BcFO3nqcIqCozSZoZoSr1g4zJOzuyGnxTEX3lUEJ7WcZgme8ddaWvWJo2AJR9DZU3CUIbhCSG6ybSwN6qtJVnCU2svDTP2ZInOw2cBTrqtQahtNZn9NcJ4l2NaSmSkkP1noZWnVwkLmdUPOwLZEwy2Z3S3R+4rIG9hcbpPXHFVWcQdZkn2FOta3cKWQnNRC5g1LsJah4GCzSVsKnCOY5OAFRTBekyyryeyilhFKva75r4Mc0aWanGEaThcy31s439KKxTzJYY5WTHPU1FtIHjQU3Oip4xlNzj/lBw23dYZVliQa7WAXf4shetcQfatI+jWRDBPmyNeW6A1P5kdDgyYJlba0BIM8BZu1JfrFwItyjcAMR3K0BWOIrtMEXyhyrlVEx3ui5dUBjmB/Q3CXW85R4mBD0s7B+4q5tKUjOlb9qqmhi5AZ6GFIC5HXtOobdYGlVdMVbNJ8toNTFcHxnoL+muBagcctjWnbNMuR00uI7nQESwg5q2qqrKWIfrNUmeQocY6HuyxJV02wj36w00yhpmUFenv4p6fUkZYqLyuinx2RGOjhCXYyJF84oiU00YMOOhhquNdfbOB7gU88pY4xJO8LVdp6/q2voeB4R04vIdhSE40xZObx1HGGJ/ja0LBthFInKaLPPFzuCaYaoj8JjPME8yoyxo6zlBqkiUZYgq00OYMswbWO5NGmq+xhipxHLRW29ARjNKXO0wRnear8XSg4XFPLKEPUS1GqvyLwiuBUoa7zpZ0l5xxFwWmWZC1H5h5FwU8eQ7K+g8UcVY6TMQreVQT/8uQ8Z+ALIXnSEa2pYZQneE9RZbSBNYXfWYJzW/h/4j4Dp1tYVcFIC5019Vyi4ThPqSFCzjGWaHQTBU8q6vrVwgxP9Lkm840imWKpcLCjYTtrKuwvsKSnrvHCXGkSMk9p6lhckfRpIeis+N2PiszT+mFLspyGleUhDwcLrZqmyeylxwjBcKHEapqkmyangyLZRVOijwOtCY5SsG5zL0OwlCJ4y5KznF3EUNDDrinwiyLZRzOXtlBbK5ITHFGLp8Q0R6ab6mS7enI2cFrxOyHvOCFaT1HThS1krjCwqWeurCkk+willhCC+RSZnRXBiZaC5RXRIZYKp2lyfrHwiKPKR0JDzrdU2EFgpidawlFDR6FgXUMNa+g1FY3bUQh2cLCwosRdnuQTS/S+JVrGLeWIvtQUvONJxlqSQYYKpwoN2kaocLjdVsis4Mk80ESF2YpSkzwldjHkjFCUutI/r+EHDU8oCs6yzL3PhWiEooZdFMkymlas4AcI3KmoMMNSQ3tHzjGWCrcJJdYyZC7QFGwjRL9p+MrRkAGWzIaWCn9W0F3TsK01c2ZvQw0byvxuQU0r1lM0qJO7wW0kRIMdDTtXEdzi4VIh+EoIHm0mWtAtpCixlabgn83fKTI7anJe9ST7WIK1DMGpQmYeA58ImV6ezOGOzK2Kgq01pd60cKWiUi9Lievb/0vIDPHQ05Kzt4ddPckQBQtoaurjyHnek/nKzpQLrVgKPjIkh2v4uyezpv+Xoo7fPFXaGFp1vaLKxQ4uUpQQS5VuQs7BCq4xRJv7fwpVvvFEB3j+620haOuocqMhWd6TTPAEx+mdFNGHdranFe95WrWmIvlY4F1Dle2ECgc6cto7SryuqGGGha0tFQ5V53migUKmg6XKAo4qS3mik+0OZpAhOLeZKicacgaYcyx5hypYQE02ZA4xi/pNhOQxR4klNKyqacj+mpxnLTnnGSo85++3ZCZq6lrZkXlGEX3o+C9FieccJbZWVFjC0Yo1FZnJhoYMFoI1hEZ9r6hwg75HwzBNhbZCdJEfJwTPGzJvaKImw1yYX1HDAmpXR+ZJQ/SmgqMNVQb5vgamGwLtt7VwvP7Qk1xpiM5x5Cyv93E06MZmgs0Nya2azIKOYKCGBQQW97RmhKNKF02JZqHEJ4o58qp7X5EcZmc56trXEqzjCBZ1MFGR87Ql2tSTs6CGxS05PTzRQorkbw7aKoKXFDXsYW42VJih/q+FP2BdTzDTwVqOYB13liM50vG7wy28qagyuIXMeQI/Oqq8bcn5wJI50xH00CRntyfpL1T4hydYpoXgNiFzoIUTDZnLNRzh4TBHwbYGDvZkxmlyJloyr6tRihpeUG94GnKtIznREF0tzJG/OOr73JBcrSh1k6WuTprgLU+mnSGnv6Zge0NNz+kTDdH8nuAuTdJDCNb21LCiIuqlYbqGzT3RAoZofQfjFazkqeNWdYaGvYTM001EW2oKPvVk1ldUGSgUtHFwjKM1h9jnFcmy5lChoLNaQMGGDsYbKixlaMBmmsx1QjCfflwTfO/gckW0ruZ3jugKR3R5W9hGUWqCgxuFgsuaCHorotGKzGaeZB9DMsaTnKCpMtwTvOzhYk0rdrArKCqcaWmVk1+F372ur1YkKxgatI8Qfe1gIX9wE9FgS8ESmuABIXnRUbCapcKe+nO7slClSZFzpV/LkLncEb1qiO42fS3R855Su2mCLh62t1SYZZYVmKwIHjREF2uihTzB20JOkz7dkxzYQnK0UOU494wh+VWRc6Un2kpTaVgLDFEkJ/uhzRcI0YKGgpGWOlocBU/a4fKoJ/pEaNV6jip3+Es9VXY078rGnmAdf7t9ylPXS34RBSuYPs1UecZTU78WanhBCHpZ5sAoTz0LGZKjPf9TRypqWEiTvOFglL1fCEY3wY/++rbk7C8bWebA6p6om6PgOL2kp44TFJlVNBXae2rqqdZztOJpT87GQsE9jqCPIe9VReZuQ/CIgacsyZdCpIScSYqcZk8r+nsyCzhyfhOqHGOIvrLknC8wTpFcaYiGC/RU1NRbUeUpocQOnkRpGOrIOcNRx+1uA0UrzhSSt+VyS3SJpnFWkzNDqOFGIWcfR86DnmARTQ1HKIL33ExPiemeOhYSSjzlSUZZuE4TveoJLnBUOFof6KiysCbnAEcZgcUNTDOwkqWu3RWtmGpZwlHhJENdZ3miGz0lJlsKnjbwqSHQjpxnFDlTLLwqJPMZMjd7KrzkSG7VsxXBZE+F8YZkb01Oe00yyRK9psh5SYh29ySPKBo2ylNht7ZkZnsKenjKNJu9PNEyZpaCHv4Kt6RQsLvAVp7M9kIimmCUwGeWqLMmGuIotYMmWNpSahkhZw9FqZsVnKJhsjAHvtHMsTM9fCI06Dx/u3vfUXCqfsKRc4oFY2jMsoo/7DJDwZ1CsIKnJu+J9ldkpmiCxQx1rWjI+T9FwcWWzOuaYH0Hj7klNRVWEQpmaqosakiGNTFHdjS/qnUdmf0NJW5xsL0HhimCCZZSRzmSPTXJQ4aaztAwtZnoabebJ+htCaZ7Cm535ByoqXKbX1WRc4Eh2MkRXWzImVc96Cj4VdOKVxR84VdQsIUM8Psoou2byVHyZFuq7O8otbSQ2UAoeEWTudATLGSpZzVLlXVkPU2Jc+27lsw2jmg5T5VhbeE3BT083K9WsTTkFU/Osi0rC5lRlpwRHUiesNS0sOvmqGML1aRbPAxTJD9ZKtxuob+hhl8cwYGWpJ8nub7t5p6coYbMovZ1BTdaKn1jYD6h4GFDNFyT/Kqe1XCXphXHOKLZmuRSRdBPEfVUXQzJm5YGPGGJdvAEr7hHNdGZnuBvrpciGmopOLf5N0uVMy0FfYToJk90uUCbJupaVpO53UJXR2bVpoU00V2KOo4zMFrBd0Jtz2pa0clT5Q5L8IpQ177mWQejPMEJhuQjS10ref6HHjdEhy1P1EYR7GtO0uSsKJQYLiTnG1rVScj5lyazpqWGl5uBbRWl7m6ixGOOnEsMJR7z8J0n6KMnCdxhiNYQCoZ6CmYLnO8omC3MkW3bktlPmEt/VQQHejL3+dOE5FlPdK/Mq8hZxxJtLyRrepLThYKbLZxkSb5W52vYxNOaOxUF0yxMUPwBTYqCzy01XayYK0sJyWBLqX0MwU5CzoymRzV0EjjeUeLgDpTo6ij42ZAzvD01dHUUTPLU96MdLbBME8nFBn7zJCMtJcZokn8YoqU0FS5WFKyniHobguMcmW8N0XkWZjkyN3hqOMtS08r+/xTBwpZSZ3qiVRX8SzMHHjfUNFjgHEPmY9PL3ykEzxkSre/1ZD6z/NuznuB0RcE1TWTm9zRgfUWVJiG6yrzgmWPXC8EAR4Wxhlad0ZbgQyEz3pG5RVEwwDJH2mgKpjcTiCOzn1lfUWANFbZ2BA8balnEweJC9J0iuaeZoI+ippFCztEKVvckR2iice1JvhVytrQwUAZpgsubCPaU7xUe9vWnaOpaSBEspalykhC9bUlOMpT42ZHca6hyrqKmw/wMR8H5ZmdFoBVJb03O4UL0tSNnvIeRmkrLWqrs78gcrEn2tpcboh0UPOW3UUR9PMk4T4nnNKWmCjlrefhCwxRNztfmIQVdDElvS4m1/WuOujoZCs5XVOjtKPGokJzsYCtFYoWonSPT21DheU/wWhM19FcElwqNGOsp9Q8N/cwXaiND1MmeL1Q5XROtYYgGeFq1aTMsoMmcrKjQrOFQTQ1fmBYhmW6o8Jkjc7iDJRTBIo5kgJD5yMEYA3srCg7VFKwiVJkmRCc5ohGOKhsYMn/XBLdo5taZjlb9YAlGWRimqbCsoY7HFAXLa5I1HPRxMMsQDHFkWtRNniqT9UEeNjcE7RUlrCJ4R2CSJuqlKHWvJXjAUNcITYkenuBRB84TbeepcqTj3zZyFJzgYQdHnqfgI0ddUwS6GqWpsKWhjq9cV0vBAEMN2znq+EBfIWT+pClYw5xsTlJU6GeIBsjGmmANTzJZiIYpgrM0Oa8ZMjd7NP87jxhqGOhJlnQtjuQpB+8aEE00wZFznSJPyHxgH3HkPOsJFvYk8zqCHzTs1BYOa4J3PFU+UVRZxlHDM4YavlNUuMoRveiZA2d7grMNc2g+RbSCEKzmgYsUmWmazFJyoiOZ4KnyhKOGRzWJa0+moyV4TVHDzn51Awtqaphfk/lRQ08FX1iiqxTB/kLwd0VynKfEvI6cd4XMV5bMhZ7gZUWVzYQ6Nm2BYzxJbw3bGthEUUMfgbGeorae6DxHtJoZ6alhZ0+ytiVoK1R4z5PTrOECT/SugseEOlb1MMNR4VRNcJy+V1Hg9ONClSZFZjdHlc6W6FBLdJja2MC5hhpu0DBYEY1TFGwiFAxRRCsYkiM9JRb0JNMVkW6CZYT/2EiTGWmo8k+h4FhDNE7BvppoTSFnmCV5xZKzvcCdDo7VVPnIU+I+Rc68juApC90MwcFCsJ5hDqxgScYKreruyQwTqrzoqDCmhWi4IbhB0Yrt3RGa6GfDv52rKXWhh28dyZaWUvcZeMTBaZoSGyiCtRU5J8iviioHaErs7Jkj61syVzTTgOcUOQ8buFBTYWdL5g3T4qlpe0+wvD63heAXRfCCIed9RbCsp2CiI7raUOYOTU13N8PNHvpaGvayo4a3LLT1lDrVEPT2zLUlheB1R+ZTRfKWJ+dcocLJfi11vyJ51lLqJ0WD7tRwryezjiV5W28uJO9qykzX8JDe2lHl/9oyBwa2UMfOngpXCixvKdXTk3wrsKmiVYdZIqsoWEERjbcUNDuiaQomGoIbFdEHmsyWnuR+IeriKDVLnlawlyNHKwKlSU631PKep8J4Q+ayjkSLKYLhalNHlYvttb6fHm0p6OApsZ4l2VfdqZkjuysy6ysKLlckf1KUutCTs39bmCgEyyoasIWlVaMF7mgmWtBT8Kol5xpH9IGllo8cJdopcvZ2sImlDmMIbtDk3KIpeNiS08lQw11NFPTwVFlPP6pJ2gvRfI7gQUfmNAtf6Gs0wQxDsKGlVBdF8rCa3jzdwMaGHOsItrZk7hAyOzpK9VS06j5F49b0VNGOOfKs3lDToMsMBe9ZWtHFEgxTJLs7qrygKZjUnmCYoeAqeU6jqWuLJup4WghOdvCYJnrSkSzoyRkm5M2StQwVltPkfCAk58tET/CSg+8MUecmotMEnhBKfWBIZsg2ihruMJQaoIm+tkTLKEqspMh00w95gvFCQRtDwTT1gVDDSEVdlwqZfxoQRbK0g+tbiBZxzKlpnpypejdDwTaeOvorMk/IJE10h9CqRe28hhLbe0pMsdSwv4ZbhKivo2BjDWfL8UKJgeavwlwb5KlwhyE4u4XkGE2ytZCznKLCDZZq42VzT8HLCrpruFbIfOIINmh/qCdZ1ZBc65kLHR1Bkyf5zn6pN3SvGKIlFNGplhrO9QSXanLOMQTLCa0YJCRrCZm/CZmrLTm7WzCK4GJDiWUdFeYx1LCFg3NMd0XmCuF3Y5rITLDUsYS9zoHVzwnJoYpSTQoObyEzr4cFBNqYTopoaU/wkyLZ2lPhX/5Y95ulxGTV7KjhWrOZgl8MyUUafjYraNjNU1N3IWcjT5WzWqjwtoarHSUObGYO3GCJZpsBlnJGPd6ZYLyl1GdCA2625IwwJDP8GUKymbzuyPlZlvTUsaUh5zFDhRWFzPKKZLAlWdcQbObgF9tOqOsmB1dqcqYJmWstFbZRRI9poolmqiLnU0POvxScpah2iSL5UJNzgScY5+AuIbpO0YD3NCW+dLMszFSdFCWGqG6eVq2uYVNDdICGD6W7EPRWZEY5gpsE9rUkS3mijzzJnm6UpUFXG1hCUeVoS5WfNcFpblELL2qqrCvMvRfd45oalvKU2tiQ6ePJOVMRXase9iTtLJztPxJKLWpo2CRDcJwn2sWSLKIO1WQWNTCvpVUvOZhgSC40JD0dOctaSqzkCRbXsKlb11Oip6PCJ0IwSJM31j3akRxlP7Rwn6aGaUL0qiLnJkvB3xWZ2+Q1TfCwpQH3G0o92UzmX4o/oJNQMMSQc547wVHhdk+VCw01DFYEnTxzZKAm74QmeNNR1w6WzEhNK15VJzuCdxQ53dRUDws5KvwgBMOEgpcVNe0hZI6RXT1Jd0cyj5nsaEAHgVmGaJIlWdsc5Ui2ElrRR6jrRAttNMEAIWrTDFubkZaok7/AkzfIwfuWVq0jHzuCK4QabtLUMVPB3kJ0oyHTSVFlqMALilJf2Rf8k5aaHtMfayocLBS8L89oKoxpJvnAkDPa0qp5DAUTHKWmCcnthlou8iCKaFFLHWcINd1nyIwXqrSxMNmSs6KmoL2QrKuWtlQ5V0120xQ5vRyZS1rgFkWwhiOwiuQbR0OOVhQM9iS3tiXp4RawRPMp5tDletOOBL95MpM01dZTBM9pkn5qF010rIeHFcFZhmSGpYpTsI6nwhqe5C9ynhlpp5ophuRb6WcJFldkVnVEwwxVfrVkvnWUuNLCg5bgboFHPDlDPDmnK7hUrWiIbjadDclujlZcaokOFup4Ri1kacV6jmrrK1hN9bGwpKEBQ4Q6DvIUXOmo6U5LqQM6EPyiKNjVkPnJkDPNEaxhiFay5ExW1NXVUGqcpYYdPcGiCq7z/TSlbhL4pplWXKd7NZO5QQFrefhRQW/NHOsqcIglc4UhWklR8K0QzbAw08CBDnpbgqXdeD/QUsM4RZXDFBW6WJKe/mFPdH0LtBgiq57wFLzlyQzz82qYx5D5WJP5yVJDW01BfyHnS6HKO/reZqId1WGa4Hkh2kWodJ8i6KoIPlAj2hPt76CzXsVR6koPRzWTfKqIentatYpQw2me4AA3y1Kind3SwoOKZDcFXTwl9tWU6mfgRk9d71sKtlNwrjnYw5tC5n5LdKiGry3JKNlHEd3oaMCFHrazBPMp/uNJ+V7IudcSbeOIdjUEdwl0VHCOZo5t6YluEuaC9mQeMgSfOyKnYGFHcIeQ84yQWbuJYJpZw5CzglDH7gKnWqqM9ZTaXcN0TeYhR84eQtJT76JJ1lREe7WnnvsMmRc9FQ7SBBM9mV3lCUdmHk/S2RAMt0QjFNFqQpWjDPQ01DXWUdDBkXziKPjGEP3VP+zIWU2t7im41FOloyWzn/L6dkUy3VLDaZ6appgDLHPjJEsyvJngWEPUyVBiAaHCTEXwrLvSEbV1e1gKJniicWorC1MUrVjB3uDhJE/wgSOzk1DXpk0k73qCM8xw2UvD5kJmDUfOomqMpWCkJRlvKXGmoeBm18USjVIk04SClxTB6YrgLAPLWYK9HLUt5cmc0vYES8GnTeRc6skZbQkWdxRsIcyBRzx1DbTk9FbU0caTPOgJHhJKnOGIVhQqvKmo0llRw9sabrZkDtdg3PqaKi9oatjY8B+G371paMg6+mZFNNtQ04mWBq3rYLOmtWWQp8KJnpy9DdFensyjdqZ+yY40VJlH8wcdLzC8PZnvHMFUTZUrDTkLyQaGus5X5LzpYAf3i+e/ZlhqGqWhh6Ou6xTR9Z6oi5AZZtp7Mj2EEm8oSpxiYZCHU/1fbGdNNNRRoZMhmilEb2gqHOEJDtXkHK/JnG6IrvbPCwV3NhONVdS1thBMs1T4QOBcTWa2IzhMk2nW5Kyn9tXUtpv9RsG2msxk+ZsQzRQacJncpgke0+T8y5Fzj8BiGo7XlJjaTIlpQs7KFjpqGnKuoyEPeIKnFMkZHvopgh81ySxNFWvJWcKRs70j2FOT012IllEEO1n4pD1513Yg2ssQPOThOkvyrqHUdEXOSEsihmBbTbKX1kLBPWqWkLOqJbjB3GBIZmoa8qWl4CG/iZ7oiA72ZL7TJNeZUY7kFQftDcHHluBzRbCegzMtrRjVQpX2lgoPKKLJAkcbMl01XK2p7yhL8pCBbQ3BN2avJgKvttcrWDK3CiUOVxQ8ZP+pqXKyIxnmBymCg5vJjNfkPK4+c8cIfK8ocVt7kmfd/I5SR1hKvCzUtb+lhgc00ZaO6CyhIQP1Uv4yIZjload72PXX0OIJvnFU+0Zf6MhsJwTfW0r0UwQfW4LNLZl5HK261JCZ4qnBaAreVAS3WrjV0LBnNDUNNDToCEeFfwgcb4gOEqLRhirWkexrCEYKVV711DLYEE1XBEsp5tpTGjorkomKYF9FDXv7fR3BGwbettSxnyL53MBPjsxDZjMh+VUW9NRxq1DhVk+FSxQcaGjV9Pawv6eGByw5qzoy7xk4RsOShqjJwWKe/1pEEfzkobeD/dQJmpqedcyBTy2sr4nGNRH0c0SPWTLrqAc0OQcb/gemKgqucQT7ySWKCn2EUotoCvpZct7RO2sy/QW0IWcXd7pQRQyZVwT2USRO87uhjioTLKV2brpMUcMQRbKH/N2T+UlTpaMls6cmc6CCNy3JdYYSUzzJQ4oSD3oKLncULOiJvjBEC2oqnCJkJluCYy2ZQ5so9YYlZ1VLlQU1mXEW1jZERwj/MUSRc24TdexlqLKfQBtDTScJUV8FszXBEY5ktpD5Ur9hYB4Nb1iikw3JoYpkKX+RodRKFt53MMuRnKSpY31PwYaGaILh3wxJGz9TkTPEETxoCWZrgvOlmyMzxFEwVJE5xZKzvyJ4WxEc16Gd4Xe3Weq4XH2jKRikqOkGQ87hQnC7wBmGYLAnesX3M+S87eFATauuN+Qcrh7xIxXJbUIdMw3JGE3ylCWzrieaqCn4zhGM19TQ3z1oH1AX+pWEqIc7wNGAkULBo/ZxRaV9NNyh4Br3rCHZzbzmSfawBL0dNRwpW1kK9mxPXR9povcdrGSZK9c2k0xwFGzjuniCtRSZCZ6ccZ7gaktmgAOtKbG/JnOkJrjcQTdFMsxRQ2cLY3WTIrlCw1eWKn8R6pvt4GFDso3QoL4a3nLk3G6JrtME3dSenpx7PNFTmga0EaJTLQ061sEeQoWXhSo9LTXsaSjoJQRXeZLtDclbCrYzfzHHeaKjHCVOUkQHO3JeEepr56mhiyaYYKjjNU+Fed1wS5VlhWSqI/hYUdDOkaxiKehoyOnrCV5yBHtbWFqTHCCwtpDcYolesVR5yUzTZBb3RNMd0d6WP+SvhuBmRcGxnuQzT95IC285cr41cLGQ6aJJhmi4TMGempxeimBRQw1tFKV+8jd6KuzoSTqqDxzRtpZkurvKEHxlqXKRIjjfUNNXQsNOsRScoWFLT+YeRZVD3GRN0MdQcKqQjHDMrdGGVu3iYJpQx3WGUvfbmxwFfR20WBq0oYY7LMFhhgYtr8jpaEnaOzjawWWaTP8mMr0t/EPDPoqcnxTBI5o58L7uoWnMrpoqPwgVrlAUWE+V+TQl9rawoyP6QGAlQw2TPRX+YSkxyBC8Z6jhHkXBgQL7WII3DVFnRfCrBfxewv9D6xsyjys4VkhWb9pUU627JllV0YDNHMku/ldNMMXDEo4aFnAkk4U6frNEU4XgZUPmEKHUl44KrzmYamjAbh0JFvGnaTLPu1s9jPCwjFpYiN7z1DTOk/nc07CfDFzmCf7i+bfNHXhDtLeBXzTBT5rkMvWOIxpl4EMh2LGJBu2syDnAEx2naEhHDWMMzPZEhygyS1mS5RTJr5ZkoKbEUoYqr2kqdDUE8ztK7OaIntJkFrIECwv8LJTaVx5XJE86go8dFeZ3FN3rjabCAYpoYEeC9zzJVULBbmZhDyd7ko09ydpNZ3nm2Kee4FPPXHnYEF1nqOFEC08LUVcDvYXkJHW8gTaKCk9YGOeIJhqiE4ToPEepdp7IWFjdwnWaufGMwJJCMtUTTBBK9BGCOy2tGGrJTHIwyEOzp6aPzNMOtlZkDvcEWpP5SVNhfkvDxhmSazTJXYrM9U1E0xwFVwqZQwzJxw6+kGGGUj2FglGGmnb1/G51udRSMNlTw6GGnCcUwVcOpmsqTHa06o72sw1RL02p9z0VbnMLOaIX3QKaYKSCFQzBKEUNHTSc48k53RH9wxGMtpQa5KjjW0W0n6XCCCG4yxNNdhQ4R4l1Ff+2sSd6UFHiIEOyqqFgT01mEUMD+joy75jPhOA+oVVLm309FR4yVOlp4RhLiScNmSmaYF5Pw0STrOIoWMSR2UkRXOMp+M4SHW8o8Zoi6OZgjKOaFar8zZDzkWzvKOjkKBjmCXby8JahhjXULY4KlzgKLvAwxVGhvyd4zxB1d9T0piazmKLCVZY5sKiD0y2ZSYrkUEPUbIk+dlQ4SJHTR50k1DPaUWIdTZW9NJwnJMOECgd7ou/MnppMJ02O1VT4Wsh85MnZzcFTngpXGKo84qmwgKbCL/orR/SzJ2crA+t6Mp94KvxJUeIbT3CQu1uIdlQEOzlKfS3UMcrTiFmOuroocrZrT2AcmamOKg8YomeEKm/rlT2sociMaybaUlFhuqHCM2qIJ+rg4EcDFymiDSxzaHdPcpE62pD5kyM5SBMoA1PaUtfIthS85ig1VPiPPYXgYEMNk4Qq7TXBgo7oT57gPUdwgCHzhIVFPFU6OYJzHAX9m5oNrVjeE61miDrqQ4VSa1oiURTsKHC0IfjNwU2WzK6eqK8jWln4g15TVBnqmDteCJ501PGAocJhhqjZdtBEB6lnhLreFJKxmlKbeGrqLiSThVIbCdGzloasa6lpMQXHCME2boLpJgT7yWaemu6wBONbqGNVRS0PKIL7LckbjmQtR7K8I5qtqel+T/ChJTNIKLjdUMNIRyvOEko9YYl2cwQveBikCNawJKcLBbc7+JM92mysNvd/Fqp8a0k6CNEe7cnZrxlW0wQXaXjaktnRwNOGZKYiONwS7a1JVheq3WgJHlQUGKHKmp4KAxXR/ULURcNgoa4zhKSLpZR3kxRRb0NmD0OFn+UCS7CzI1nbP6+o4x47QZE5xRCt3ZagnYcvmpYQktXdk5YKXTzBC57kKEe0VVuiSYqapssMS3C9p2CKkHOg8B8Pa8p5atrIw3qezIWanMGa5HRDNF6RM9wcacl0N+Q8Z8hsIkSnaIIdHRUOEebAPy1zbCkhM062FCJtif7PU+UtoVXzWKqM1PxXO8cfdruhFQ/a6x3JKYagvVDhQEtNiyiiSQ7OsuRsZUku0CRNDs4Sog6KKjsZgk2bYJqijgsEenoKeniinRXBn/U3lgpPdyDZynQx8IiioMnCep5Ky8mjGs6Wty0l1hUQTcNWswS3WRp2kCNZwJG8omG8JphPUaFbC8lEfabwP7VtM9yoaNCAjpR41VNhrD9LkbN722v0CoZMByFzhaW+MyzRYEWFDQwN2M4/JiT76PuljT3VU/A36eaIThb+R9oZGOAJ9tewkgGvqOMNRWYjT/Cwu99Q8LqDE4TgbLWxJ1jaDDAERsFOFrobgjUsBScaguXU8kKm2RL19tRypSHnHNlHiIZqgufs4opgQdVdwxBNNFBR6kVFqb8ogimOzB6a6HTzrlDHEpYaxjiiA4TMQobkDg2vejjfwJGWmnbVFAw3H3hq2NyQfG7hz4aC+w3BbwbesG0swYayvpAs6++Ri1Vfzx93mFChvyN5xVHTS+0p9aqCAxyZ6ZacZyw5+7uuQkFPR9DDk9NOiE7X1PCYJVjVUqq7JlrHwWALF5nfHNGjApdpqgzx5OwilDhCiDYTgnc9waGW4BdLNNUQvOtpzDOWHDH8D7TR/A/85KljEQu3NREc4Pl/6B1Hhc8Umb5CsKMmGC9EPcxoT2amwHNCmeOEnOPbklnMkbOgIvO5UMOpQrS9UGVdt6iH/fURjhI/WOpaW9OKLYRod6HCUEdOX000wpDZQ6hwg6LgZfOqo1RfT/CrJzjekXOGhpc1VW71ZLbXyyp+93ILbC1kPtIEYx0FIx1VDrLoVzXRKRYWk809yYlC9ImcrinxtabKnzRJk3lAU1OLEN1j2zrYzr2myHRXJFf4h4QKT1qSTzTB5+ZNTzTRkAxX8FcLV2uS8eoQQ2aAkFzvCM72sJIcJET3WPjRk5wi32uSS9rfZajpWEvj9hW42F4o5NytSXYy8IKHay10VYdrcl4SkqscrXpMwyGOgtkajheSxdQqmpxP1L3t4R5PqasFnrQEjytq6qgp9Y09Qx9o4S1FzhUCn1kyHSzBWLemoSGvOqLNhZyBjmCaAUYpMgt4Ck7wBBMMwWKWgjsUwTaGVsxWC1mYoKiyqqeGKYqonSIRQ3KIkHO0pmAxTdBHkbOvfllfr+AA+7gnc50huVKYK393FOyg7rbPO/izI7hE4CnHHHnJ0ogNPRUGeUpsrZZTBJcrovUcJe51BPsr6GkJdhCCsZ6aTtMEb2pqWkqeVtDXE/QVggsU/Nl86d9RMF3DxvZTA58agu810RWawCiSzzXBeU3MMW9oyJUedvNEvQyNu1f10BSMddR1vaLCYpYa/mGocLSiYDcLbQz8aMn5iyF4xBNMs1P0QEOV7o5gaWGuzSeLue4tt3ro7y4Tgm4G/mopdZgl6q0o6KzJWE3mMksNr3r+a6CbT8g5wZNzT9O7fi/zpaOmnz3BRoqos+tv9zMbdpxsqDBOEewtJLt7cg5wtKKbvldpSzRRCD43VFheCI7yZLppggMVBS/KMAdHODJvOwq2NQSbKKKPLdFWQs7Fqo+mpl01JXYRgq8dnGLhTiFzqmWsUMdpllZdbKlyvSdYxhI9YghOtxR8LgSLWHK62mGGVoxzBE8LNWzqH9CUesQzFy5RQzTc56mhi6fgXEWwpKfE5Z7M05ZgZUPmo6auiv8YKzDYwWBLMErIbKHJvOwIrvEdhOBcQ9JdU1NHQ7CXn2XIDFBKU2WAgcX9UAUzDXWd5alwuyJ41Z9rjKLCL4aCp4WarhPm2rH+SaHUYE001JDZ2ZAzXPjdMpZWvC9wmqIB2lLhQ01D5jO06hghWMndbM7yRJMsoCj1vYbnFQVrW9jak3OlEJ3s/96+p33dEPRV5GxiqaGjIthUU6FFEZyqCa5qJrpBdzSw95IUnOPIrCUUjRZQFrbw5PR0R1qiYx3cb6nrWUMrBmmiBQxVHtTew5ICP/ip6g4hed/Akob/32wvBHsIOX83cI8hGeNeNPCIkPmXe8fPKx84OMSRM1MTdXSwjCZ4S30jVGhvqTRak/OVhgGazHuOCud5onEO1lJr6ecVyaOK6H7zqlBlIaHE0oroCgfvGJIdPcmfLNGLjpz7hZwZQpUbFME0A1cIJa7VNORkgfsMBatbKgwwJM9bSvQXeNOvbIjelg6WWvo5kvbKaJJNHexkKNHL9xRyFlH8Ti2riB5wVPhUk7nGkJnoCe428LR/wRGdYIlmWebCyxou1rCk4g/ShugBDX0V0ZQWkh0dOVsagkM0yV6OoLd5ye+pRlsCr0n+KiQrGuq5yJDzrTAXHtLUMduTDBVKrSm3eHL+6ijxhFDX9Z5gVU/wliHYTMiMFpKLNMEywu80wd3meoFmt6VbRMPenhrOc6DVe4pgXU8DnnHakLOIIrlF4FZPIw6R+zxBP0dyq6OOZ4Q5sLKCcz084ok+VsMMyQhNZmmBgX5xIXOEJTmi7VsGTvMTNdHHhpzdbE8Du2oKxgvBqQKdDDnTFOylCFaxR1syz2iqrOI/FEpNc3C6f11/7+ASS6l2inq2ciTrCCzgyemrCL5SVPjQkdPZUmGy2c9Sw9FtR1sS30RmsKPCS4rkIC/2U0MduwucYolGaPjKEyhzmiPYXagyWbYz8LWBDdzRimAXzxx4z8K9hpzlhLq+NiQ97HuKorMUfK/OVvC2JfiHUPCQI/q7J2gjK+tTDNxkCc4TMssqCs4TGtLVwQihyoAWgj9bosU80XGW6Ac9TJGziaUh5+hnFcHOnlaM1iRn29NaqGENTTTSUHCH2tWTeV0osUhH6psuVLjRUmGWhm6OZEshGeNowABHcJ2Bpy2ZszRcKkRXd2QuKVEeXnbfaEq825FguqfgfE2whlChSRMdron+LATTPQ2Z369t4B9C5gs/ylzv+CMmepIDPclFQl13W0rspPd1JOcbghGOEutqCv5qacURQl3dDKyvyJlqKXGPgcM9FfawJAMVmdcspcYKOZc4GjDYkFlK05olNMHyHn4zFNykyOxt99RkHlfwmiHo60l2EKI+mhreEKp080Tbug08BVPcgoqC5zWt+NLDTZ7oNSF51N1qie7Va3uCCwyZbkINf/NED6jzOsBdZjFN8oqG3wxVunqCSYYKf3EdhJyf9YWGf7tRU2oH3VHgPr1fe5J9hOgHd7xQ0y7qBwXr23aGErP0cm64JVjZwsOGqL+mhNgZmhJLW2oY4UhedsyBgzrCKrq7BmcpNVhR6jBPq64Vgi+kn6XE68pp8J5/+0wRHGOpsKenQn9DZntPzjRLZpDAdD2fnSgkG9tmIXnUwQ6WVighs7Yi2MxQ0N3CqYaCXkJ0oyOztMDJjmSSpcpvlrk0RMMOjmArQ04PRV1DO1FwhCVaUVPpKUM03JK5SxPsIWRu8/CGHi8UHChiqGFDTbSRJWeYUDDcH6vJWUxR4k1FXbMUwV6e4AJFXS8oMqsZKqzvYQ9DDQdZckY4aGsIhtlubbd2r3j4QBMoTamdPZk7O/Bf62lacZwneNjQoGcdVU7zJOd7ghsUHOkosagic6cnWc8+4gg285R6zZP5s1/LUbCKIznTwK36PkdwlOrl4U1LwfdCCa+IrvFkmgw1PCAUXKWo0sURXWcI2muKJlgyFzhynCY4RBOsqCjoI1R5zREco0n2Vt09BQtYSizgKNHfUmUrQ5UOCh51BFcLmY7umhYqXKQomOop8bUnWNNQcIiBcYaC6xzMNOS8JQQfeqKBmmglB+97ok/lfk3ygaHSyZaCRTzRxQo6GzLfa2jWBPepw+UmT7SQEJyiyRkhBLMVOfcoMjcK0eZChfUNzFAUzCsEN5vP/X1uP/n/aoMX+K+nw/Hjr/9xOo7j7Pju61tLcgvJpTWXNbfN5jLpi6VfCOviTktKlFusQixdEKWmEBUKNaIpjZRSSOXSgzaaKLdabrm1/9nZ+/f+vd/vz/v9+Xy+zZ7PRorYoZqyLrCwQdEAixxVOEXNNnjX2nUSRlkqGmWowk8lxR50JPy9Bo6qJXaXwNvREBvnThPEPrewryLhcAnj5WE15Fqi8W7R1sAuEu86S4ENikItFN4xkv9Af4nXSnUVcLiA9xzesFpivRRVeFKtsMRaKBhuSbjOELnAUtlSQUpXgdfB4Z1oSbnFEetbQ0IrAe+Y+pqnDcEJFj6S8LDZzZHwY4e3XONNlARraomNEt2bkvGsosA3ioyHm+6jCMbI59wqt4eeara28IzEmyPgoRaUOEDhTVdEJhmCoTWfC0p8aNkCp0oYqih2iqGi4yXeMkOsn4LdLLnmKfh/YogjNsPebeFGR4m9BJHLzB61XQ3BtpISfS2FugsK9FAtLWX1dCRcrCnUp44CNzuCowUZmxSRgYaE6Za0W2u/E7CVXCiI/UOR8aAm1+OSyE3mOUcwyc1zBBeoX1kiKy0Zfxck1Gsyulti11i83QTBF5Kg3pDQThFMVHiPSlK+0cSedng/VaS8bOZbtsBcTcZAR8JP5KeqQ1OYKAi20njdNNRpgnsU//K+JnaXJaGTomr7aYIphoRn9aeShJWKEq9LcozSF7QleEfDI5LYm5bgVkFkRwVDBCVu0DDIkGupo8TZBq+/pMQURYErJQmPKGKjNDkWOLx7Jd5QizdUweIaKrlP7SwJDhZvONjLkOsBBX9UpGxnydhXkfBLQ8IxgojQbLFnJf81JytSljclYYyEFyx0kVBvKWOFJmONpshGAcsduQY5giVNCV51eOdJYo/pLhbvM0uDHSevNKRcrKZIqnCtJeEsO95RoqcgGK4ocZcho1tTYtcZvH41pNQ7vA0WrhIfOSraIIntIAi+NXWCErdbkvrWwjRLrt0NKUdL6KSOscTOdMSOUtBHwL6OLA0vNSdynaWQEnCpIvKaIrJJEbvHkmuNhn6OjM8VkSGSqn1uYJCGHnq9I3aLhNME3t6GjIkO7xrNFumpyTNX/NrwX7CrIRiqqWijI9JO4d1iieykyfiposQIQ8YjjsjlBh6oHWbwRjgYJQn2NgSnNycmJAk3NiXhx44Sxykihxm8ybUwT1OVKySc7vi3OXVkdBJ4AyXBeksDXG0IhgtYY0lY5ahCD0ehborIk5aUWRJviMA7Xt5kyRjonrXENkm8yYqgs8VzgrJmClK20uMM3jRJ0FiQICQF9hdETlLQWRIb5ki6WDfWRPobvO6a4GP5mcOrNzDFELtTkONLh9dXE8xypEg7z8A9jkhrQ6Fhjlg/QVktJXxt4WXzT/03Q8IaQWSqIuEvloQ2mqC9Jfi7wRul4RX3pSPlzpoVlmCtI2jvKHCFhjcM3sN6lqF6HxnKelLjXWbwrpR4xzuCrTUZx2qq9oAh8p6ixCUGr78g8oyjRAtB5CZFwi80VerVpI0h+IeBxa6Zg6kWvpDHaioYYuEsRbDC3eOmC2JvGYLeioxGknL2UATNJN6hmtj1DlpLvDVmocYbrGCVJKOrg4X6DgddLA203BKMFngdJJFtFd7vJLm6KEpc5yjQrkk7M80SGe34X24nSex1Ra5Omgb71JKyg8SrU3i/kARKwWpH0kOGhKkObyfd0ZGjvyXlAkVZ4xRbYJ2irFMkFY1SwyWxr2oo4zlNiV+7zmaweFpT4kR3kaDAFW6xpSqzJay05FtYR4HmZhc9UxKbbfF2V8RG1MBmSaE+kmC6JnaRXK9gsiXhJHl/U0qM0WTcbyhwkYIvFGwjSbjfwhiJt8ZSQU+Bd5+marPMOkVkD0muxYLIfEuhh60x/J92itguihJSEMySVPQnTewnEm+620rTQEMsOfo4/kP/0ARvWjitlpSX7GxBgcMEsd3EEeYWvdytd+Saawi6aCIj1CkGb6Aj9rwhx16Cf3vAwFy5pyLhVonXzy51FDpdEblbkdJbUcEPDEFzQ8qNmhzzLTmmKWKbFCXeEuRabp6rxbvAtLF442QjQ+wEA9eL1xSR7Q0JXzlSHjJ4exq89yR0laScJ/FW6z4a73pFMEfDiRZvuvijIt86RaSFOl01riV2mD1UEvxGk/Geg5aWwGki1zgKPG9J2U8PEg8qYvMsZeytiTRXBMslCU8JSlxi8EabjwUldlDNLfzTUmCgxWsjqWCOHavYAqsknKFIO0yQ61VL5AVFxk6WhEaCAkdJgt9aSkzXlKNX2jEa79waYuc7gq0N3GDJGCBhoiTXUEPsdknCUE1CK0fwsiaylSF2uiDyO4XX3pFhNd7R4itFGc0k/ElBZwWvq+GC6szVeEoS/MZ+qylwpKNKv9Z469UOjqCjwlusicyTxG6VpNxcQ8IncoR4RhLbR+NdpGGmJWOcIzJGUuKPGpQg8rrG21dOMqQssJQ4RxH5jaUqnZuQ0F4Q+cjxLwPtpZbIAk3QTJHQWBE5S1BokoVtDd6lhqr9UpHSUxMcIYl9pojsb8h4SBOsMQcqvOWC2E8EVehqiJ1hrrAEbQxeK0NGZ0Gkq+guSRgniM23bIHVkqwx4hiHd7smaOyglyIyQuM978j4VS08J/A2G1KeMBRo4fBaSNhKUEZfQewVQ/C1I+MgfbEleEzCUw7mKXI0M3hd1EESVji8x5uQ41nxs1q4RMJCCXs7Iq9acpxn22oSDnQ/sJTxsCbHIYZiLyhY05TY0ZLIOQrGaSJDDN4t8pVaIrsqqFdEegtizc1iTew5Q4ayBDMUsQMkXocaYkc0hZua412siZ1rSXlR460zRJ5SlHGe5j801RLMlJTxtaOM3Q1pvxJ45zUlWFD7rsAbpfEm1JHxG0eh8w2R7QQVzBUw28FhFp5QZzq8t2rx2joqulYTWSuJdTYfWwqMFMcovFmSyJPNyLhE4E10pHzYjOC3huArRa571ZsGajQpQx38SBP5pyZB6lMU3khDnp0MBV51BE9o2E+TY5Ml2E8S7C0o6w1xvCZjf0HkVEHCzFoyNmqC+9wdcqN+Tp7jSDheE9ws8Y5V0NJCn2bk2tqSY4okdrEhx1iDN8cSudwepWmAGXKcJXK65H9to8jYQRH7SBF01ESUJdd0TayVInaWhLkOjlXE5irKGOnI6GSWGCJa482zBI9rCr0jyTVcEuzriC1vcr6mwFGSiqy5zMwxBH/TJHwjSPhL8+01kaaSUuMFKTcLEvaUePcrSmwn8DZrgikWb7CGPxkSjhQwrRk57tctmxLsb9sZvL9LSlyuSLlWkqOjwduo8b6Uv1DkmudIeFF2dHCgxVtk8dpIvHpBxhEOdhKk7OLIUSdJ+cSRY57B+0DgGUUlNfpthTfGkauzxrvTsUUaCVhlKeteTXCoJDCa2NOKhOmC4G1H8JBd4OBZReSRGkqcb/CO1PyLJTLB4j1q8JYaIutEjSLX8YKM+a6phdMsdLFUoV5RTm9JSkuDN8WcIon0NZMNZWh1q8C7SJEwV5HxrmnnTrf3KoJBlmCYI2ilSLlfEvlE4011NNgjgthzEua0oKK7JLE7HZHlEl60BLMVFewg4EWNt0ThrVNEVkkiTwpKXSWJzdRENgvKGq4IhjsiezgSFtsfCUq8qki5S1LRQeYQQ4nemmCkImWMw3tFUoUBZk4NOeZYEp4XRKTGa6wJjrWNHBVJR4m3FCnbuD6aak2WsMTh3SZImGCIPKNgsDpVwnsa70K31lCFJZYcwwSMFcQulGTsZuEaSdBXkPGZhu0FsdUO73RHjq8MPGGIfaGIbVTk6iuI3GFgucHrIQkmWSJdBd7BBu+uOryWAhY7+Lki9rK5wtEQzWwvtbqGhIMFwWRJsElsY4m9IIg9L6lCX0VklaPAYkfkZEGDnOWowlBJjtMUkcGK4Lg6EtoZInMUBVYLgn0UsdmCyCz7gIGHFfk+k1QwTh5We7A9x+IdJ6CvIkEagms0hR50eH9UnTQJ+2oiKyVlLFUE+8gBGu8MQ3CppUHesnjTHN4QB/UGPhCTHLFPHMFrCqa73gqObUJGa03wgbhHkrCfpEpzNLE7JDS25FMKhlhKKWKfCgqstLCPu1zBXy0J2ztwjtixBu8UTRn9LVtkmCN2iyFhtME70JHRQ1KVZXqKI/KNIKYMCYs1GUMEKbM1bKOI9LDXC7zbHS+bt+1MTWS9odA9DtrYtpbImQJ2VHh/lisEwaHqUk1kjKTAKknkBEXkbkdMGwq0dnhzLJF3NJH3JVwrqOB4Sca2hti75nmJN0WzxS6UxDYoEpxpa4htVlRjkYE7DZGzJVU72uC9IyhQL4i8YfGWSYLLNcHXloyz7QhNifmKSE9JgfGmuyLhc403Xm9vqcp6gXe3xuuv8F6VJNxkyTHEkHG2g0aKXL0MsXc1bGfgas2//dCONXiNLCX+5mB7eZIl1kHh7ajwpikyzlUUWOVOsjSQlsS+M0R+pPje/dzBXRZGO0rMtgQrLLG9VSu9n6CMXS3BhwYmSoIBhsjNBmZbgusE9BCPCP5triU4VhNbJfE+swSP27aayE8tuTpYYjtrYjMVGZdp2NpS1s6aBnKSHDsbKuplKbHM4a0wMFd/5/DmGyKrJSUaW4IBrqUhx0vyfzTBBLPIUcnZdrAkNsKR0sWRspumSns6Ch0v/qqIbBYUWKvPU/CFoyrDJGwSNFhbA/MlzKqjrO80hRbpKx0Jewsi/STftwGSlKc1JZyAzx05dhLEdnfQvhZOqiHWWEAHC7+30FuRcZUgaO5gpaIK+xsiHRUsqaPElTV40xQZQ107Q9BZE1nryDVGU9ZSQ47bmhBpLcYpUt7S+xuK/FiT8qKjwXYw5ypS2iuCv7q1gtgjhuBuB8LCFY5cUuCNtsQOFcT+4Ih9JX+k8Ea6v0iCIRZOtCT0Et00JW5UeC85Cg0ScK0k411HcG1zKtre3SeITBRk7WfwDhEvaYLTHP9le0m8By0JDwn4TlLW/aJOvGHxdjYUes+ScZigCkYQdNdEOhkiezgShqkx8ueKjI8lDfK2oNiOFvrZH1hS+tk7NV7nOmLHicGWEgubkXKdwdtZknCLJXaCpkrjZBtLZFsDP9CdxWsSr05Sxl6CMmoFbCOgryX40uDtamB7SVmXW4Ihlgpmq+00tBKUUa83WbjLUNkzDmY7cow1JDygyPGlhgGKYKz4vcV7QBNbJIgM11TUqZaMdwTeSguH6rOaw1JRKzaaGyxVm2EJ/uCIrVWUcZUkcp2grMsEjK+DMwS59jQk3Kd6SEq1d0S6uVmO4Bc1lDXTUcHjluCXEq+1OlBDj1pi9zgiXxnKuE0SqTXwhqbETW6RggMEnGl/q49UT2iCzgJvRwVXS2K/d6+ZkyUl7jawSVLit46EwxVljDZwoSQ20sDBihztHfk2yA8NVZghiXwrYHQdfKAOtzsayjhY9bY0yE2CWEeJ9xfzO423xhL5syS2TFJofO2pboHob0nY4GiAgRrvGQEDa/FWSsoaaYl0syRsEt3kWoH3B01shCXhTUWe9w3Bt44SC9QCh3eShQctwbaK2ApLroGCMlZrYqvlY3qYhM0aXpFkPOuoqJ3Dm6fxXrGwVF9gCWZagjPqznfkuMKQ8DPTQRO8ZqG1hPGKEm9IgpGW4DZDgTNriTxvFiq+Lz+0cKfp4wj6OCK9JSnzNSn9LFU7UhKZZMnYwcJ8s8yRsECScK4j5UOB95HFO0CzhY4xJxuCix0lDlEUeMdS6EZBkTsUkZ4K74dugyTXS7aNgL8aqjDfkCE0ZbwkCXpaWCKhl8P7VD5jxykivSyxyZrYERbe168LYu9ZYh86IkscgVLE7tWPKmJv11CgoyJltMEbrohtVAQfO4ImltiHEroYEs7RxAarVpY8AwXMcMReFOTYWe5iiLRQxJ5Q8DtJ8LQhWOhIeFESPGsILhbNDRljNbHzNRlTFbk2S3L0NOS6V1KFJYKUbSTcIIhM0wQ/s2TM0SRMNcQmSap3jCH4yhJZKSkwyRHpYYgsFeQ4U7xoCB7VVOExhXepo9ABBsYbvGWKXPME3lyH95YioZ0gssQRWWbI+FaSMkXijZXwgiTlYdPdkNLaETxlyDVIwqeaEus0aTcYcg0RVOkpR3CSJqIddK+90JCxzsDVloyrFd5ZAr4TBKfaWa6boEA7C7s6EpYaeFPjveooY72mjIccLHJ9HUwVlDhKkmutJDJBwnp1rvulJZggKDRfbXAkvC/4l3ozQOG9a8lxjx0i7nV4jSXc7vhe3OwIxjgSHjdEhhsif9YkPGlus3iLFDnWOFhtCZbJg0UbQcIaR67JjthoCyMEZRwhiXWyxO5QxI6w5NhT4U1WsJvDO60J34fW9hwzwlKij6ZAW9ne4L0s8C6XeBMEkd/LQy1VucBRot6QMlbivaBhoBgjqGiCJNhsqVp/S2SsG6DIONCR0dXhvWbJ+MRRZJkkuEjgDXJjFQW6SSL7GXK8Z2CZg7cVsbWGoKmEpzQ5elpiy8Ryg7dMkLLUEauzeO86CuwlSOlgYLojZWeJ9xM3S1PWfEfKl5ISLQ0MEKR8YOB2QfCxJBjrKPCN4f9MkaSsqoVXJBmP7EpFZ9UQfOoOFwSzBN4MQ8LsGrymlipcJQhmy0GaQjPqCHaXRwuCZwRbqK2Fg9wlClZqYicrIgMdZfxTQ0c7TBIbrChxmuzoKG8XRaSrIhhiyNFJkrC7oIAWMEOQa5aBekPCRknCo4IKPrYkvCDI8aYmY7WFtprgekcJZ3oLIqssCSMtFbQTJKwXYy3BY5oCh2iKPCpJOE+zRdpYgi6O2KmOAgvVCYaU4ySRek1sgyFhJ403QFHiVEmJHwtybO1gs8Hr5+BETQX3War0qZngYGgtVZtoqd6vFSk/UwdZElYqyjrF4HXUeFspIi9IGKf4j92pKGAdCYMVsbcV3kRF0N+R8LUd5PCsIGWoxDtBkCI0nKofdJQxT+LtZflvuc8Q3CjwWkq8KwUpHzkK/NmSsclCL0nseQdj5FRH5CNHSgtLiW80Of5HU9Hhlsga9bnBq3fEVltKfO5IaSTmGjjc4J0otcP7QsJUSQM8pEj5/wCuUuC2DWz8AAAAAElFTkSuQmCC"); +} diff --git a/codemirror/theme/blackboard.css b/codemirror/theme/blackboard.css new file mode 100644 index 0000000..f2bde69 --- /dev/null +++ b/codemirror/theme/blackboard.css @@ -0,0 +1,25 @@ +/* Port of TextMate's Blackboard theme */ + +.cm-s-blackboard.CodeMirror { background: #0C1021; color: #F8F8F8; } +.cm-s-blackboard .CodeMirror-selected { background: #253B76 !important; } +.cm-s-blackboard .CodeMirror-gutters { background: #0C1021; border-right: 0; } +.cm-s-blackboard .CodeMirror-linenumber { color: #888; } +.cm-s-blackboard .CodeMirror-cursor { border-left: 1px solid #A7A7A7 !important; } + +.cm-s-blackboard .cm-keyword { color: #FBDE2D; } +.cm-s-blackboard .cm-atom { color: #D8FA3C; } +.cm-s-blackboard .cm-number { color: #D8FA3C; } +.cm-s-blackboard .cm-def { color: #8DA6CE; } +.cm-s-blackboard .cm-variable { color: #FF6400; } +.cm-s-blackboard .cm-operator { color: #FBDE2D;} +.cm-s-blackboard .cm-comment { color: #AEAEAE; } +.cm-s-blackboard .cm-string { color: #61CE3C; } +.cm-s-blackboard .cm-string-2 { color: #61CE3C; } +.cm-s-blackboard .cm-meta { color: #D8FA3C; } +.cm-s-blackboard .cm-error { background: #9D1E15; color: #F8F8F8; } +.cm-s-blackboard .cm-builtin { color: #8DA6CE; } +.cm-s-blackboard .cm-tag { color: #8DA6CE; } +.cm-s-blackboard .cm-attribute { color: #8DA6CE; } +.cm-s-blackboard .cm-header { color: #FF6400; } +.cm-s-blackboard .cm-hr { color: #AEAEAE; } +.cm-s-blackboard .cm-link { color: #8DA6CE; } diff --git a/codemirror/theme/cobalt.css b/codemirror/theme/cobalt.css new file mode 100644 index 0000000..6095799 --- /dev/null +++ b/codemirror/theme/cobalt.css @@ -0,0 +1,18 @@ +.cm-s-cobalt.CodeMirror { background: #002240; color: white; } +.cm-s-cobalt div.CodeMirror-selected { background: #b36539 !important; } +.cm-s-cobalt .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; } +.cm-s-cobalt .CodeMirror-linenumber { color: #d0d0d0; } +.cm-s-cobalt .CodeMirror-cursor { border-left: 1px solid white !important; } + +.cm-s-cobalt span.cm-comment { color: #08f; } +.cm-s-cobalt span.cm-atom { color: #845dc4; } +.cm-s-cobalt span.cm-number, .cm-s-cobalt span.cm-attribute { color: #ff80e1; } +.cm-s-cobalt span.cm-keyword { color: #ffee80; } +.cm-s-cobalt span.cm-string { color: #3ad900; } +.cm-s-cobalt span.cm-meta { color: #ff9d00; } +.cm-s-cobalt span.cm-variable-2, .cm-s-cobalt span.cm-tag { color: #9effff; } +.cm-s-cobalt span.cm-variable-3, .cm-s-cobalt span.cm-def { color: white; } +.cm-s-cobalt span.cm-error { color: #9d1e15; } +.cm-s-cobalt span.cm-bracket { color: #d8d8d8; } +.cm-s-cobalt span.cm-builtin, .cm-s-cobalt span.cm-special { color: #ff9e59; } +.cm-s-cobalt span.cm-link { color: #845dc4; } diff --git a/codemirror/theme/eclipse.css b/codemirror/theme/eclipse.css new file mode 100644 index 0000000..47d66a0 --- /dev/null +++ b/codemirror/theme/eclipse.css @@ -0,0 +1,25 @@ +.cm-s-eclipse span.cm-meta {color: #FF1717;} +.cm-s-eclipse span.cm-keyword { line-height: 1em; font-weight: bold; color: #7F0055; } +.cm-s-eclipse span.cm-atom {color: #219;} +.cm-s-eclipse span.cm-number {color: #164;} +.cm-s-eclipse span.cm-def {color: #00f;} +.cm-s-eclipse span.cm-variable {color: black;} +.cm-s-eclipse span.cm-variable-2 {color: #0000C0;} +.cm-s-eclipse span.cm-variable-3 {color: #0000C0;} +.cm-s-eclipse span.cm-property {color: black;} +.cm-s-eclipse span.cm-operator {color: black;} +.cm-s-eclipse span.cm-comment {color: #3F7F5F;} +.cm-s-eclipse span.cm-string {color: #2A00FF;} +.cm-s-eclipse span.cm-string-2 {color: #f50;} +.cm-s-eclipse span.cm-error {color: #f00;} +.cm-s-eclipse span.cm-qualifier {color: #555;} +.cm-s-eclipse span.cm-builtin {color: #30a;} +.cm-s-eclipse span.cm-bracket {color: #cc7;} +.cm-s-eclipse span.cm-tag {color: #170;} +.cm-s-eclipse span.cm-attribute {color: #00c;} +.cm-s-eclipse span.cm-link {color: #219;} + +.cm-s-eclipse .CodeMirror-matchingbracket { + border:1px solid grey; + color:black !important;; +} diff --git a/codemirror/theme/elegant.css b/codemirror/theme/elegant.css new file mode 100644 index 0000000..d0ce0cb --- /dev/null +++ b/codemirror/theme/elegant.css @@ -0,0 +1,10 @@ +.cm-s-elegant span.cm-number, .cm-s-elegant span.cm-string, .cm-s-elegant span.cm-atom {color: #762;} +.cm-s-elegant span.cm-comment {color: #262; font-style: italic; line-height: 1em;} +.cm-s-elegant span.cm-meta {color: #555; font-style: italic; line-height: 1em;} +.cm-s-elegant span.cm-variable {color: black;} +.cm-s-elegant span.cm-variable-2 {color: #b11;} +.cm-s-elegant span.cm-qualifier {color: #555;} +.cm-s-elegant span.cm-keyword {color: #730;} +.cm-s-elegant span.cm-builtin {color: #30a;} +.cm-s-elegant span.cm-error {background-color: #fdd;} +.cm-s-elegant span.cm-link {color: #762;} diff --git a/codemirror/theme/erlang-dark.css b/codemirror/theme/erlang-dark.css new file mode 100644 index 0000000..ea9c26c --- /dev/null +++ b/codemirror/theme/erlang-dark.css @@ -0,0 +1,21 @@ +.cm-s-erlang-dark.CodeMirror { background: #002240; color: white; } +.cm-s-erlang-dark div.CodeMirror-selected { background: #b36539 !important; } +.cm-s-erlang-dark .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; } +.cm-s-erlang-dark .CodeMirror-linenumber { color: #d0d0d0; } +.cm-s-erlang-dark .CodeMirror-cursor { border-left: 1px solid white !important; } + +.cm-s-erlang-dark span.cm-atom { color: #845dc4; } +.cm-s-erlang-dark span.cm-attribute { color: #ff80e1; } +.cm-s-erlang-dark span.cm-bracket { color: #ff9d00; } +.cm-s-erlang-dark span.cm-builtin { color: #eeaaaa; } +.cm-s-erlang-dark span.cm-comment { color: #7777ff; } +.cm-s-erlang-dark span.cm-def { color: #ee77aa; } +.cm-s-erlang-dark span.cm-error { color: #9d1e15; } +.cm-s-erlang-dark span.cm-keyword { color: #ffee80; } +.cm-s-erlang-dark span.cm-meta { color: #50fefe; } +.cm-s-erlang-dark span.cm-number { color: #ffd0d0; } +.cm-s-erlang-dark span.cm-operator { color: #dd1111; } +.cm-s-erlang-dark span.cm-string { color: #3ad900; } +.cm-s-erlang-dark span.cm-tag { color: #9effff; } +.cm-s-erlang-dark span.cm-variable { color: #50fe50; } +.cm-s-erlang-dark span.cm-variable-2 { color: #ee00ee; } diff --git a/codemirror/theme/lesser-dark.css b/codemirror/theme/lesser-dark.css new file mode 100644 index 0000000..67f71ad --- /dev/null +++ b/codemirror/theme/lesser-dark.css @@ -0,0 +1,44 @@ +/* +http://lesscss.org/ dark theme +Ported to CodeMirror by Peter Kroon +*/ +.cm-s-lesser-dark { + line-height: 1.3em; +} +.cm-s-lesser-dark { + font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', 'Monaco', Courier, monospace !important; +} + +.cm-s-lesser-dark.CodeMirror { background: #262626; color: #EBEFE7; text-shadow: 0 -1px 1px #262626; } +.cm-s-lesser-dark div.CodeMirror-selected {background: #45443B !important;} /* 33322B*/ +.cm-s-lesser-dark .CodeMirror-cursor { border-left: 1px solid white !important; } +.cm-s-lesser-dark pre { padding: 0 8px; }/*editable code holder*/ + +div.CodeMirror span.CodeMirror-matchingbracket { color: #7EFC7E; }/*65FC65*/ + +.cm-s-lesser-dark .CodeMirror-gutters { background: #262626; border-right:1px solid #aaa; } +.cm-s-lesser-dark .CodeMirror-linenumber { color: #777; } + +.cm-s-lesser-dark span.cm-keyword { color: #599eff; } +.cm-s-lesser-dark span.cm-atom { color: #C2B470; } +.cm-s-lesser-dark span.cm-number { color: #B35E4D; } +.cm-s-lesser-dark span.cm-def {color: white;} +.cm-s-lesser-dark span.cm-variable { color:#D9BF8C; } +.cm-s-lesser-dark span.cm-variable-2 { color: #669199; } +.cm-s-lesser-dark span.cm-variable-3 { color: white; } +.cm-s-lesser-dark span.cm-property {color: #92A75C;} +.cm-s-lesser-dark span.cm-operator {color: #92A75C;} +.cm-s-lesser-dark span.cm-comment { color: #666; } +.cm-s-lesser-dark span.cm-string { color: #BCD279; } +.cm-s-lesser-dark span.cm-string-2 {color: #f50;} +.cm-s-lesser-dark span.cm-meta { color: #738C73; } +.cm-s-lesser-dark span.cm-error { color: #9d1e15; } +.cm-s-lesser-dark span.cm-qualifier {color: #555;} +.cm-s-lesser-dark span.cm-builtin { color: #ff9e59; } +.cm-s-lesser-dark span.cm-bracket { color: #EBEFE7; } +.cm-s-lesser-dark span.cm-tag { color: #669199; } +.cm-s-lesser-dark span.cm-attribute {color: #00c;} +.cm-s-lesser-dark span.cm-header {color: #a0a;} +.cm-s-lesser-dark span.cm-quote {color: #090;} +.cm-s-lesser-dark span.cm-hr {color: #999;} +.cm-s-lesser-dark span.cm-link {color: #00c;} diff --git a/codemirror/theme/monokai.css b/codemirror/theme/monokai.css new file mode 100644 index 0000000..a0b3c7c --- /dev/null +++ b/codemirror/theme/monokai.css @@ -0,0 +1,28 @@ +/* Based on Sublime Text's Monokai theme */ + +.cm-s-monokai.CodeMirror {background: #272822; color: #f8f8f2;} +.cm-s-monokai div.CodeMirror-selected {background: #49483E !important;} +.cm-s-monokai .CodeMirror-gutters {background: #272822; border-right: 0px;} +.cm-s-monokai .CodeMirror-linenumber {color: #d0d0d0;} +.cm-s-monokai .CodeMirror-cursor {border-left: 1px solid #f8f8f0 !important;} + +.cm-s-monokai span.cm-comment {color: #75715e;} +.cm-s-monokai span.cm-atom {color: #ae81ff;} +.cm-s-monokai span.cm-number {color: #ae81ff;} + +.cm-s-monokai span.cm-property, .cm-s-monokai span.cm-attribute {color: #a6e22e;} +.cm-s-monokai span.cm-keyword {color: #f92672;} +.cm-s-monokai span.cm-string {color: #e6db74;} + +.cm-s-monokai span.cm-variable {color: #a6e22e;} +.cm-s-monokai span.cm-variable-2 {color: #9effff;} +.cm-s-monokai span.cm-def {color: #fd971f;} +.cm-s-monokai span.cm-error {background: #f92672; color: #f8f8f0;} +.cm-s-monokai span.cm-bracket {color: #f8f8f2;} +.cm-s-monokai span.cm-tag {color: #f92672;} +.cm-s-monokai span.cm-link {color: #ae81ff;} + +.cm-s-monokai .CodeMirror-matchingbracket { + text-decoration: underline; + color: white !important; +} diff --git a/codemirror/theme/neat.css b/codemirror/theme/neat.css new file mode 100644 index 0000000..8a307f8 --- /dev/null +++ b/codemirror/theme/neat.css @@ -0,0 +1,9 @@ +.cm-s-neat span.cm-comment { color: #a86; } +.cm-s-neat span.cm-keyword { line-height: 1em; font-weight: bold; color: blue; } +.cm-s-neat span.cm-string { color: #a22; } +.cm-s-neat span.cm-builtin { line-height: 1em; font-weight: bold; color: #077; } +.cm-s-neat span.cm-special { line-height: 1em; font-weight: bold; color: #0aa; } +.cm-s-neat span.cm-variable { color: black; } +.cm-s-neat span.cm-number, .cm-s-neat span.cm-atom { color: #3a3; } +.cm-s-neat span.cm-meta {color: #555;} +.cm-s-neat span.cm-link { color: #3a3; } diff --git a/codemirror/theme/night.css b/codemirror/theme/night.css new file mode 100644 index 0000000..8804a39 --- /dev/null +++ b/codemirror/theme/night.css @@ -0,0 +1,21 @@ +/* Loosely based on the Midnight Textmate theme */ + +.cm-s-night.CodeMirror { background: #0a001f; color: #f8f8f8; } +.cm-s-night div.CodeMirror-selected { background: #447 !important; } +.cm-s-night .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; } +.cm-s-night .CodeMirror-linenumber { color: #f8f8f8; } +.cm-s-night .CodeMirror-cursor { border-left: 1px solid white !important; } + +.cm-s-night span.cm-comment { color: #6900a1; } +.cm-s-night span.cm-atom { color: #845dc4; } +.cm-s-night span.cm-number, .cm-s-night span.cm-attribute { color: #ffd500; } +.cm-s-night span.cm-keyword { color: #599eff; } +.cm-s-night span.cm-string { color: #37f14a; } +.cm-s-night span.cm-meta { color: #7678e2; } +.cm-s-night span.cm-variable-2, .cm-s-night span.cm-tag { color: #99b2ff; } +.cm-s-night span.cm-variable-3, .cm-s-night span.cm-def { color: white; } +.cm-s-night span.cm-error { color: #9d1e15; } +.cm-s-night span.cm-bracket { color: #8da6ce; } +.cm-s-night span.cm-comment { color: #6900a1; } +.cm-s-night span.cm-builtin, .cm-s-night span.cm-special { color: #ff9e59; } +.cm-s-night span.cm-link { color: #845dc4; } diff --git a/codemirror/theme/rubyblue.css b/codemirror/theme/rubyblue.css new file mode 100644 index 0000000..8817de0 --- /dev/null +++ b/codemirror/theme/rubyblue.css @@ -0,0 +1,21 @@ +.cm-s-rubyblue { font:13px/1.4em Trebuchet, Verdana, sans-serif; } /* - customized editor font - */ + +.cm-s-rubyblue.CodeMirror { background: #112435; color: white; } +.cm-s-rubyblue div.CodeMirror-selected { background: #38566F !important; } +.cm-s-rubyblue .CodeMirror-gutters { background: #1F4661; border-right: 7px solid #3E7087; } +.cm-s-rubyblue .CodeMirror-linenumber { color: white; } +.cm-s-rubyblue .CodeMirror-cursor { border-left: 1px solid white !important; } + +.cm-s-rubyblue span.cm-comment { color: #999; font-style:italic; line-height: 1em; } +.cm-s-rubyblue span.cm-atom { color: #F4C20B; } +.cm-s-rubyblue span.cm-number, .cm-s-rubyblue span.cm-attribute { color: #82C6E0; } +.cm-s-rubyblue span.cm-keyword { color: #F0F; } +.cm-s-rubyblue span.cm-string { color: #F08047; } +.cm-s-rubyblue span.cm-meta { color: #F0F; } +.cm-s-rubyblue span.cm-variable-2, .cm-s-rubyblue span.cm-tag { color: #7BD827; } +.cm-s-rubyblue span.cm-variable-3, .cm-s-rubyblue span.cm-def { color: white; } +.cm-s-rubyblue span.cm-error { color: #AF2018; } +.cm-s-rubyblue span.cm-bracket { color: #F0F; } +.cm-s-rubyblue span.cm-link { color: #F4C20B; } +.cm-s-rubyblue span.CodeMirror-matchingbracket { color:#F0F !important; } +.cm-s-rubyblue span.cm-builtin, .cm-s-rubyblue span.cm-special { color: #FF9D00; } diff --git a/codemirror/theme/solarized.css b/codemirror/theme/solarized.css new file mode 100644 index 0000000..06a6c7f --- /dev/null +++ b/codemirror/theme/solarized.css @@ -0,0 +1,207 @@ +/* +Solarized theme for code-mirror +http://ethanschoonover.com/solarized +*/ + +/* +Solarized color pallet +http://ethanschoonover.com/solarized/img/solarized-palette.png +*/ + +.solarized.base03 { color: #002b36; } +.solarized.base02 { color: #073642; } +.solarized.base01 { color: #586e75; } +.solarized.base00 { color: #657b83; } +.solarized.base0 { color: #839496; } +.solarized.base1 { color: #93a1a1; } +.solarized.base2 { color: #eee8d5; } +.solarized.base3 { color: #fdf6e3; } +.solarized.solar-yellow { color: #b58900; } +.solarized.solar-orange { color: #cb4b16; } +.solarized.solar-red { color: #dc322f; } +.solarized.solar-magenta { color: #d33682; } +.solarized.solar-violet { color: #6c71c4; } +.solarized.solar-blue { color: #268bd2; } +.solarized.solar-cyan { color: #2aa198; } +.solarized.solar-green { color: #859900; } + +/* Color scheme for code-mirror */ + +.cm-s-solarized { + line-height: 1.45em; + font-family: Menlo,Monaco,"Andale Mono","lucida console","Courier New",monospace !important; + color-profile: sRGB; + rendering-intent: auto; +} +.cm-s-solarized.cm-s-dark { + color: #839496; + background-color: #002b36; + text-shadow: #002b36 0 1px; +} +.cm-s-solarized.cm-s-light { + background-color: #fdf6e3; + color: #657b83; + text-shadow: #eee8d5 0 1px; +} + +.cm-s-solarized .CodeMirror-widget { + text-shadow: none; +} + + +.cm-s-solarized .cm-keyword { color: #cb4b16 } +.cm-s-solarized .cm-atom { color: #d33682; } +.cm-s-solarized .cm-number { color: #d33682; } +.cm-s-solarized .cm-def { color: #2aa198; } + +.cm-s-solarized .cm-variable { color: #268bd2; } +.cm-s-solarized .cm-variable-2 { color: #b58900; } +.cm-s-solarized .cm-variable-3 { color: #6c71c4; } + +.cm-s-solarized .cm-property { color: #2aa198; } +.cm-s-solarized .cm-operator {color: #6c71c4;} + +.cm-s-solarized .cm-comment { color: #586e75; font-style:italic; } + +.cm-s-solarized .cm-string { color: #859900; } +.cm-s-solarized .cm-string-2 { color: #b58900; } + +.cm-s-solarized .cm-meta { color: #859900; } +.cm-s-solarized .cm-error, +.cm-s-solarized .cm-invalidchar { + color: #586e75; + border-bottom: 1px dotted #dc322f; +} +.cm-s-solarized .cm-qualifier { color: #b58900; } +.cm-s-solarized .cm-builtin { color: #d33682; } +.cm-s-solarized .cm-bracket { color: #cb4b16; } +.cm-s-solarized .CodeMirror-matchingbracket { color: #859900; } +.cm-s-solarized .CodeMirror-nonmatchingbracket { color: #dc322f; } +.cm-s-solarized .cm-tag { color: #93a1a1 } +.cm-s-solarized .cm-attribute { color: #2aa198; } +.cm-s-solarized .cm-header { color: #586e75; } +.cm-s-solarized .cm-quote { color: #93a1a1; } +.cm-s-solarized .cm-hr { + color: transparent; + border-top: 1px solid #586e75; + display: block; +} +.cm-s-solarized .cm-link { color: #93a1a1; cursor: pointer; } +.cm-s-solarized .cm-special { color: #6c71c4; } +.cm-s-solarized .cm-em { + color: #999; + text-decoration: underline; + text-decoration-style: dotted; +} +.cm-s-solarized .cm-strong { color: #eee; } +.cm-s-solarized .cm-tab:before { + content: "➤"; /*visualize tab character*/ + color: #586e75; +} + +.cm-s-solarized.cm-s-dark .CodeMirror-focused .CodeMirror-selected { + background: #386774; + color: inherit; +} + +.cm-s-solarized.cm-s-dark ::selection { + background: #386774; + color: inherit; +} + +.cm-s-solarized.cm-s-dark .CodeMirror-selected { + background: #586e75; +} + +.cm-s-solarized.cm-s-light .CodeMirror-focused .CodeMirror-selected { + background: #eee8d5; + color: inherit; +} + +.cm-s-solarized.cm-s-light ::selection { + background: #eee8d5; + color: inherit; +} + +.cm-s-solarized.cm-s-light .CodeMirror-selected { + background: #93a1a1; +} + + + +/* Editor styling */ + + + +/* Little shadow on the view-port of the buffer view */ +.cm-s-solarized.CodeMirror { + -moz-box-shadow: inset 7px 0 12px -6px #000; + -webkit-box-shadow: inset 7px 0 12px -6px #000; + box-shadow: inset 7px 0 12px -6px #000; +} + +/* Gutter border and some shadow from it */ +.cm-s-solarized .CodeMirror-gutters { + padding: 0 15px 0 10px; + box-shadow: 0 10px 20px black; + border-right: 1px solid; +} + +/* Gutter colors and line number styling based of color scheme (dark / light) */ + +/* Dark */ +.cm-s-solarized.cm-s-dark .CodeMirror-gutters { + background-color: #073642; + border-color: #00232c; +} + +.cm-s-solarized.cm-s-dark .CodeMirror-linenumber { + text-shadow: #021014 0 -1px; +} + +/* Light */ +.cm-s-solarized.cm-s-light .CodeMirror-gutters { + background-color: #eee8d5; + border-color: #eee8d5; +} + +/* Common */ +.cm-s-solarized .CodeMirror-linenumber { + color: #586e75; +} + +.cm-s-solarized .CodeMirror-gutter .CodeMirror-gutter-text { + color: #586e75; +} + +.cm-s-solarized .CodeMirror-lines { + padding-left: 5px; +} + +.cm-s-solarized .CodeMirror-lines .CodeMirror-cursor { + border-left: 1px solid #819090; +} + +/* +Active line. Negative margin compensates left padding of the text in the +view-port +*/ +.cm-s-solarized .activeline { + margin-left: -20px; +} + +.cm-s-solarized.cm-s-dark .activeline { + background: rgba(255, 255, 255, 0.05); + +} +.cm-s-solarized.cm-s-light .activeline { + background: rgba(0, 0, 0, 0.05); +} + +/* +View-port and gutter both get little noise background to give it a real feel. +*/ +.cm-s-solarized.CodeMirror, +.cm-s-solarized .CodeMirror-gutters { + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAQAAAAHUWYVAABFFUlEQVQYGbzBCeDVU/74/6fj9HIcx/FRHx9JCFmzMyGRURhLZIkUsoeRfUjS2FNDtr6WkMhO9sm+S8maJfu+Jcsg+/o/c+Z4z/t97/vezy3z+z8ekGlnYICG/o7gdk+wmSHZ1z4pJItqapjoKXWahm8NmV6eOTbWUOp6/6a/XIg6GQqmenJ2lDHyvCFZ2cBDbmtHA043VFhHwXxClWmeYAdLhV00Bd85go8VmaFCkbVkzlQENzfBDZ5gtN7HwF0KDrTwJ0dypSOzpaKCMwQHKTIreYIxlmhXTzTWkVm+LTynZhiSBT3RZQ7aGfjGEd3qyXQ1FDymqbKxpspERQN2MiRjNZlFFQXfCNFm9nM1zpAsoYjmtRTc5ajwuaXc5xrWskT97RaKzAGe5ARHhVUsDbjKklziiX5WROcJwSNCNI+9w1Jwv4Zb2r7lCMZ4oq5C0EdTx+2GzNuKpJ+iFf38JEWkHJn9DNF7mmBDITrWEg0VWL3pHU20tSZnuqWu+R3BtYa8XxV1HO7GyD32UkOpL/yDloINFTmvtId+nmAjxRw40VMwVKiwrKLE4bK5UOVntYwhOcSSXKrJHKPJedocpGjVz/ZMIbnYUPB10/eKCrs5apqpgVmWzBYWpmtKHecJPjaUuEgRDDaU0oZghCJ6zNMQ5ZhDYx05r5v2muQdM0EILtXUsaKiQX9WMEUotagQzFbUNN6NUPC2nm5pxEWGCjMc3GdJHjSU2kORLK/JGSrkfGEIjncU/CYUnOipoYemwj8tST9NsJmB7TUVXtbUtXATJVZXBMvYeTXJfobgJUPmGMP/yFaWonaa6BcFO3nqcIqCozSZoZoSr1g4zJOzuyGnxTEX3lUEJ7WcZgme8ddaWvWJo2AJR9DZU3CUIbhCSG6ybSwN6qtJVnCU2svDTP2ZInOw2cBTrqtQahtNZn9NcJ4l2NaSmSkkP1noZWnVwkLmdUPOwLZEwy2Z3S3R+4rIG9hcbpPXHFVWcQdZkn2FOta3cKWQnNRC5g1LsJah4GCzSVsKnCOY5OAFRTBekyyryeyilhFKva75r4Mc0aWanGEaThcy31s439KKxTzJYY5WTHPU1FtIHjQU3Oip4xlNzj/lBw23dYZVliQa7WAXf4shetcQfatI+jWRDBPmyNeW6A1P5kdDgyYJlba0BIM8BZu1JfrFwItyjcAMR3K0BWOIrtMEXyhyrlVEx3ui5dUBjmB/Q3CXW85R4mBD0s7B+4q5tKUjOlb9qqmhi5AZ6GFIC5HXtOobdYGlVdMVbNJ8toNTFcHxnoL+muBagcctjWnbNMuR00uI7nQESwg5q2qqrKWIfrNUmeQocY6HuyxJV02wj36w00yhpmUFenv4p6fUkZYqLyuinx2RGOjhCXYyJF84oiU00YMOOhhquNdfbOB7gU88pY4xJO8LVdp6/q2voeB4R04vIdhSE40xZObx1HGGJ/ja0LBthFInKaLPPFzuCaYaoj8JjPME8yoyxo6zlBqkiUZYgq00OYMswbWO5NGmq+xhipxHLRW29ARjNKXO0wRnear8XSg4XFPLKEPUS1GqvyLwiuBUoa7zpZ0l5xxFwWmWZC1H5h5FwU8eQ7K+g8UcVY6TMQreVQT/8uQ8Z+ALIXnSEa2pYZQneE9RZbSBNYXfWYJzW/h/4j4Dp1tYVcFIC5019Vyi4ThPqSFCzjGWaHQTBU8q6vrVwgxP9Lkm840imWKpcLCjYTtrKuwvsKSnrvHCXGkSMk9p6lhckfRpIeis+N2PiszT+mFLspyGleUhDwcLrZqmyeylxwjBcKHEapqkmyangyLZRVOijwOtCY5SsG5zL0OwlCJ4y5KznF3EUNDDrinwiyLZRzOXtlBbK5ITHFGLp8Q0R6ab6mS7enI2cFrxOyHvOCFaT1HThS1krjCwqWeurCkk+willhCC+RSZnRXBiZaC5RXRIZYKp2lyfrHwiKPKR0JDzrdU2EFgpidawlFDR6FgXUMNa+g1FY3bUQh2cLCwosRdnuQTS/S+JVrGLeWIvtQUvONJxlqSQYYKpwoN2kaocLjdVsis4Mk80ESF2YpSkzwldjHkjFCUutI/r+EHDU8oCs6yzL3PhWiEooZdFMkymlas4AcI3KmoMMNSQ3tHzjGWCrcJJdYyZC7QFGwjRL9p+MrRkAGWzIaWCn9W0F3TsK01c2ZvQw0byvxuQU0r1lM0qJO7wW0kRIMdDTtXEdzi4VIh+EoIHm0mWtAtpCixlabgn83fKTI7anJe9ST7WIK1DMGpQmYeA58ImV6ezOGOzK2Kgq01pd60cKWiUi9Lievb/0vIDPHQ05Kzt4ddPckQBQtoaurjyHnek/nKzpQLrVgKPjIkh2v4uyezpv+Xoo7fPFXaGFp1vaLKxQ4uUpQQS5VuQs7BCq4xRJv7fwpVvvFEB3j+620haOuocqMhWd6TTPAEx+mdFNGHdranFe95WrWmIvlY4F1Dle2ECgc6cto7SryuqGGGha0tFQ5V53migUKmg6XKAo4qS3mik+0OZpAhOLeZKicacgaYcyx5hypYQE02ZA4xi/pNhOQxR4klNKyqacj+mpxnLTnnGSo85++3ZCZq6lrZkXlGEX3o+C9FieccJbZWVFjC0Yo1FZnJhoYMFoI1hEZ9r6hwg75HwzBNhbZCdJEfJwTPGzJvaKImw1yYX1HDAmpXR+ZJQ/SmgqMNVQb5vgamGwLtt7VwvP7Qk1xpiM5x5Cyv93E06MZmgs0Nya2azIKOYKCGBQQW97RmhKNKF02JZqHEJ4o58qp7X5EcZmc56trXEqzjCBZ1MFGR87Ql2tSTs6CGxS05PTzRQorkbw7aKoKXFDXsYW42VJih/q+FP2BdTzDTwVqOYB13liM50vG7wy28qagyuIXMeQI/Oqq8bcn5wJI50xH00CRntyfpL1T4hydYpoXgNiFzoIUTDZnLNRzh4TBHwbYGDvZkxmlyJloyr6tRihpeUG94GnKtIznREF0tzJG/OOr73JBcrSh1k6WuTprgLU+mnSGnv6Zge0NNz+kTDdH8nuAuTdJDCNb21LCiIuqlYbqGzT3RAoZofQfjFazkqeNWdYaGvYTM001EW2oKPvVk1ldUGSgUtHFwjKM1h9jnFcmy5lChoLNaQMGGDsYbKixlaMBmmsx1QjCfflwTfO/gckW0ruZ3jugKR3R5W9hGUWqCgxuFgsuaCHorotGKzGaeZB9DMsaTnKCpMtwTvOzhYk0rdrArKCqcaWmVk1+F372ur1YkKxgatI8Qfe1gIX9wE9FgS8ESmuABIXnRUbCapcKe+nO7slClSZFzpV/LkLncEb1qiO42fS3R855Su2mCLh62t1SYZZYVmKwIHjREF2uihTzB20JOkz7dkxzYQnK0UOU494wh+VWRc6Un2kpTaVgLDFEkJ/uhzRcI0YKGgpGWOlocBU/a4fKoJ/pEaNV6jip3+Es9VXY078rGnmAdf7t9ylPXS34RBSuYPs1UecZTU78WanhBCHpZ5sAoTz0LGZKjPf9TRypqWEiTvOFglL1fCEY3wY/++rbk7C8bWebA6p6om6PgOL2kp44TFJlVNBXae2rqqdZztOJpT87GQsE9jqCPIe9VReZuQ/CIgacsyZdCpIScSYqcZk8r+nsyCzhyfhOqHGOIvrLknC8wTpFcaYiGC/RU1NRbUeUpocQOnkRpGOrIOcNRx+1uA0UrzhSSt+VyS3SJpnFWkzNDqOFGIWcfR86DnmARTQ1HKIL33ExPiemeOhYSSjzlSUZZuE4TveoJLnBUOFof6KiysCbnAEcZgcUNTDOwkqWu3RWtmGpZwlHhJENdZ3miGz0lJlsKnjbwqSHQjpxnFDlTLLwqJPMZMjd7KrzkSG7VsxXBZE+F8YZkb01Oe00yyRK9psh5SYh29ySPKBo2ylNht7ZkZnsKenjKNJu9PNEyZpaCHv4Kt6RQsLvAVp7M9kIimmCUwGeWqLMmGuIotYMmWNpSahkhZw9FqZsVnKJhsjAHvtHMsTM9fCI06Dx/u3vfUXCqfsKRc4oFY2jMsoo/7DJDwZ1CsIKnJu+J9ldkpmiCxQx1rWjI+T9FwcWWzOuaYH0Hj7klNRVWEQpmaqosakiGNTFHdjS/qnUdmf0NJW5xsL0HhimCCZZSRzmSPTXJQ4aaztAwtZnoabebJ+htCaZ7Cm535ByoqXKbX1WRc4Eh2MkRXWzImVc96Cj4VdOKVxR84VdQsIUM8Psoou2byVHyZFuq7O8otbSQ2UAoeEWTudATLGSpZzVLlXVkPU2Jc+27lsw2jmg5T5VhbeE3BT083K9WsTTkFU/Osi0rC5lRlpwRHUiesNS0sOvmqGML1aRbPAxTJD9ZKtxuob+hhl8cwYGWpJ8nub7t5p6coYbMovZ1BTdaKn1jYD6h4GFDNFyT/Kqe1XCXphXHOKLZmuRSRdBPEfVUXQzJm5YGPGGJdvAEr7hHNdGZnuBvrpciGmopOLf5N0uVMy0FfYToJk90uUCbJupaVpO53UJXR2bVpoU00V2KOo4zMFrBd0Jtz2pa0clT5Q5L8IpQ177mWQejPMEJhuQjS10ref6HHjdEhy1P1EYR7GtO0uSsKJQYLiTnG1rVScj5lyazpqWGl5uBbRWl7m6ixGOOnEsMJR7z8J0n6KMnCdxhiNYQCoZ6CmYLnO8omC3MkW3bktlPmEt/VQQHejL3+dOE5FlPdK/Mq8hZxxJtLyRrepLThYKbLZxkSb5W52vYxNOaOxUF0yxMUPwBTYqCzy01XayYK0sJyWBLqX0MwU5CzoymRzV0EjjeUeLgDpTo6ij42ZAzvD01dHUUTPLU96MdLbBME8nFBn7zJCMtJcZokn8YoqU0FS5WFKyniHobguMcmW8N0XkWZjkyN3hqOMtS08r+/xTBwpZSZ3qiVRX8SzMHHjfUNFjgHEPmY9PL3ykEzxkSre/1ZD6z/NuznuB0RcE1TWTm9zRgfUWVJiG6yrzgmWPXC8EAR4Wxhlad0ZbgQyEz3pG5RVEwwDJH2mgKpjcTiCOzn1lfUWANFbZ2BA8balnEweJC9J0iuaeZoI+ippFCztEKVvckR2iice1JvhVytrQwUAZpgsubCPaU7xUe9vWnaOpaSBEspalykhC9bUlOMpT42ZHca6hyrqKmw/wMR8H5ZmdFoBVJb03O4UL0tSNnvIeRmkrLWqrs78gcrEn2tpcboh0UPOW3UUR9PMk4T4nnNKWmCjlrefhCwxRNztfmIQVdDElvS4m1/WuOujoZCs5XVOjtKPGokJzsYCtFYoWonSPT21DheU/wWhM19FcElwqNGOsp9Q8N/cwXaiND1MmeL1Q5XROtYYgGeFq1aTMsoMmcrKjQrOFQTQ1fmBYhmW6o8Jkjc7iDJRTBIo5kgJD5yMEYA3srCg7VFKwiVJkmRCc5ohGOKhsYMn/XBLdo5taZjlb9YAlGWRimqbCsoY7HFAXLa5I1HPRxMMsQDHFkWtRNniqT9UEeNjcE7RUlrCJ4R2CSJuqlKHWvJXjAUNcITYkenuBRB84TbeepcqTj3zZyFJzgYQdHnqfgI0ddUwS6GqWpsKWhjq9cV0vBAEMN2znq+EBfIWT+pClYw5xsTlJU6GeIBsjGmmANTzJZiIYpgrM0Oa8ZMjd7NP87jxhqGOhJlnQtjuQpB+8aEE00wZFznSJPyHxgH3HkPOsJFvYk8zqCHzTs1BYOa4J3PFU+UVRZxlHDM4YavlNUuMoRveiZA2d7grMNc2g+RbSCEKzmgYsUmWmazFJyoiOZ4KnyhKOGRzWJa0+moyV4TVHDzn51Awtqaphfk/lRQ08FX1iiqxTB/kLwd0VynKfEvI6cd4XMV5bMhZ7gZUWVzYQ6Nm2BYzxJbw3bGthEUUMfgbGeorae6DxHtJoZ6alhZ0+ytiVoK1R4z5PTrOECT/SugseEOlb1MMNR4VRNcJy+V1Hg9ONClSZFZjdHlc6W6FBLdJja2MC5hhpu0DBYEY1TFGwiFAxRRCsYkiM9JRb0JNMVkW6CZYT/2EiTGWmo8k+h4FhDNE7BvppoTSFnmCV5xZKzvcCdDo7VVPnIU+I+Rc68juApC90MwcFCsJ5hDqxgScYKreruyQwTqrzoqDCmhWi4IbhB0Yrt3RGa6GfDv52rKXWhh28dyZaWUvcZeMTBaZoSGyiCtRU5J8iviioHaErs7Jkj61syVzTTgOcUOQ8buFBTYWdL5g3T4qlpe0+wvD63heAXRfCCIed9RbCsp2CiI7raUOYOTU13N8PNHvpaGvayo4a3LLT1lDrVEPT2zLUlheB1R+ZTRfKWJ+dcocLJfi11vyJ51lLqJ0WD7tRwryezjiV5W28uJO9qykzX8JDe2lHl/9oyBwa2UMfOngpXCixvKdXTk3wrsKmiVYdZIqsoWEERjbcUNDuiaQomGoIbFdEHmsyWnuR+IeriKDVLnlawlyNHKwKlSU631PKep8J4Q+ayjkSLKYLhalNHlYvttb6fHm0p6OApsZ4l2VfdqZkjuysy6ysKLlckf1KUutCTs39bmCgEyyoasIWlVaMF7mgmWtBT8Kol5xpH9IGllo8cJdopcvZ2sImlDmMIbtDk3KIpeNiS08lQw11NFPTwVFlPP6pJ2gvRfI7gQUfmNAtf6Gs0wQxDsKGlVBdF8rCa3jzdwMaGHOsItrZk7hAyOzpK9VS06j5F49b0VNGOOfKs3lDToMsMBe9ZWtHFEgxTJLs7qrygKZjUnmCYoeAqeU6jqWuLJup4WghOdvCYJnrSkSzoyRkm5M2StQwVltPkfCAk58tET/CSg+8MUecmotMEnhBKfWBIZsg2ihruMJQaoIm+tkTLKEqspMh00w95gvFCQRtDwTT1gVDDSEVdlwqZfxoQRbK0g+tbiBZxzKlpnpypejdDwTaeOvorMk/IJE10h9CqRe28hhLbe0pMsdSwv4ZbhKivo2BjDWfL8UKJgeavwlwb5KlwhyE4u4XkGE2ytZCznKLCDZZq42VzT8HLCrpruFbIfOIINmh/qCdZ1ZBc65kLHR1Bkyf5zn6pN3SvGKIlFNGplhrO9QSXanLOMQTLCa0YJCRrCZm/CZmrLTm7WzCK4GJDiWUdFeYx1LCFg3NMd0XmCuF3Y5rITLDUsYS9zoHVzwnJoYpSTQoObyEzr4cFBNqYTopoaU/wkyLZ2lPhX/5Y95ulxGTV7KjhWrOZgl8MyUUafjYraNjNU1N3IWcjT5WzWqjwtoarHSUObGYO3GCJZpsBlnJGPd6ZYLyl1GdCA2625IwwJDP8GUKymbzuyPlZlvTUsaUh5zFDhRWFzPKKZLAlWdcQbObgF9tOqOsmB1dqcqYJmWstFbZRRI9poolmqiLnU0POvxScpah2iSL5UJNzgScY5+AuIbpO0YD3NCW+dLMszFSdFCWGqG6eVq2uYVNDdICGD6W7EPRWZEY5gpsE9rUkS3mijzzJnm6UpUFXG1hCUeVoS5WfNcFpblELL2qqrCvMvRfd45oalvKU2tiQ6ePJOVMRXase9iTtLJztPxJKLWpo2CRDcJwn2sWSLKIO1WQWNTCvpVUvOZhgSC40JD0dOctaSqzkCRbXsKlb11Oip6PCJ0IwSJM31j3akRxlP7Rwn6aGaUL0qiLnJkvB3xWZ2+Q1TfCwpQH3G0o92UzmX4o/oJNQMMSQc547wVHhdk+VCw01DFYEnTxzZKAm74QmeNNR1w6WzEhNK15VJzuCdxQ53dRUDws5KvwgBMOEgpcVNe0hZI6RXT1Jd0cyj5nsaEAHgVmGaJIlWdsc5Ui2ElrRR6jrRAttNMEAIWrTDFubkZaok7/AkzfIwfuWVq0jHzuCK4QabtLUMVPB3kJ0oyHTSVFlqMALilJf2Rf8k5aaHtMfayocLBS8L89oKoxpJvnAkDPa0qp5DAUTHKWmCcnthlou8iCKaFFLHWcINd1nyIwXqrSxMNmSs6KmoL2QrKuWtlQ5V0120xQ5vRyZS1rgFkWwhiOwiuQbR0OOVhQM9iS3tiXp4RawRPMp5tDletOOBL95MpM01dZTBM9pkn5qF010rIeHFcFZhmSGpYpTsI6nwhqe5C9ynhlpp5ophuRb6WcJFldkVnVEwwxVfrVkvnWUuNLCg5bgboFHPDlDPDmnK7hUrWiIbjadDclujlZcaokOFup4Ri1kacV6jmrrK1hN9bGwpKEBQ4Q6DvIUXOmo6U5LqQM6EPyiKNjVkPnJkDPNEaxhiFay5ExW1NXVUGqcpYYdPcGiCq7z/TSlbhL4pplWXKd7NZO5QQFrefhRQW/NHOsqcIglc4UhWklR8K0QzbAw08CBDnpbgqXdeD/QUsM4RZXDFBW6WJKe/mFPdH0LtBgiq57wFLzlyQzz82qYx5D5WJP5yVJDW01BfyHnS6HKO/reZqId1WGa4Hkh2kWodJ8i6KoIPlAj2hPt76CzXsVR6koPRzWTfKqIentatYpQw2me4AA3y1Kind3SwoOKZDcFXTwl9tWU6mfgRk9d71sKtlNwrjnYw5tC5n5LdKiGry3JKNlHEd3oaMCFHrazBPMp/uNJ+V7IudcSbeOIdjUEdwl0VHCOZo5t6YluEuaC9mQeMgSfOyKnYGFHcIeQ84yQWbuJYJpZw5CzglDH7gKnWqqM9ZTaXcN0TeYhR84eQtJT76JJ1lREe7WnnvsMmRc9FQ7SBBM9mV3lCUdmHk/S2RAMt0QjFNFqQpWjDPQ01DXWUdDBkXziKPjGEP3VP+zIWU2t7im41FOloyWzn/L6dkUy3VLDaZ6appgDLHPjJEsyvJngWEPUyVBiAaHCTEXwrLvSEbV1e1gKJniicWorC1MUrVjB3uDhJE/wgSOzk1DXpk0k73qCM8xw2UvD5kJmDUfOomqMpWCkJRlvKXGmoeBm18USjVIk04SClxTB6YrgLAPLWYK9HLUt5cmc0vYES8GnTeRc6skZbQkWdxRsIcyBRzx1DbTk9FbU0caTPOgJHhJKnOGIVhQqvKmo0llRw9sabrZkDtdg3PqaKi9oatjY8B+G371paMg6+mZFNNtQ04mWBq3rYLOmtWWQp8KJnpy9DdFensyjdqZ+yY40VJlH8wcdLzC8PZnvHMFUTZUrDTkLyQaGus5X5LzpYAf3i+e/ZlhqGqWhh6Ou6xTR9Z6oi5AZZtp7Mj2EEm8oSpxiYZCHU/1fbGdNNNRRoZMhmilEb2gqHOEJDtXkHK/JnG6IrvbPCwV3NhONVdS1thBMs1T4QOBcTWa2IzhMk2nW5Kyn9tXUtpv9RsG2msxk+ZsQzRQacJncpgke0+T8y5Fzj8BiGo7XlJjaTIlpQs7KFjpqGnKuoyEPeIKnFMkZHvopgh81ySxNFWvJWcKRs70j2FOT012IllEEO1n4pD1513Yg2ssQPOThOkvyrqHUdEXOSEsihmBbTbKX1kLBPWqWkLOqJbjB3GBIZmoa8qWl4CG/iZ7oiA72ZL7TJNeZUY7kFQftDcHHluBzRbCegzMtrRjVQpX2lgoPKKLJAkcbMl01XK2p7yhL8pCBbQ3BN2avJgKvttcrWDK3CiUOVxQ8ZP+pqXKyIxnmBymCg5vJjNfkPK4+c8cIfK8ocVt7kmfd/I5SR1hKvCzUtb+lhgc00ZaO6CyhIQP1Uv4yIZjload72PXX0OIJvnFU+0Zf6MhsJwTfW0r0UwQfW4LNLZl5HK261JCZ4qnBaAreVAS3WrjV0LBnNDUNNDToCEeFfwgcb4gOEqLRhirWkexrCEYKVV711DLYEE1XBEsp5tpTGjorkomKYF9FDXv7fR3BGwbettSxnyL53MBPjsxDZjMh+VUW9NRxq1DhVk+FSxQcaGjV9Pawv6eGByw5qzoy7xk4RsOShqjJwWKe/1pEEfzkobeD/dQJmpqedcyBTy2sr4nGNRH0c0SPWTLrqAc0OQcb/gemKgqucQT7ySWKCn2EUotoCvpZct7RO2sy/QW0IWcXd7pQRQyZVwT2USRO87uhjioTLKV2brpMUcMQRbKH/N2T+UlTpaMls6cmc6CCNy3JdYYSUzzJQ4oSD3oKLncULOiJvjBEC2oqnCJkJluCYy2ZQ5so9YYlZ1VLlQU1mXEW1jZERwj/MUSRc24TdexlqLKfQBtDTScJUV8FszXBEY5ktpD5Ur9hYB4Nb1iikw3JoYpkKX+RodRKFt53MMuRnKSpY31PwYaGaILh3wxJGz9TkTPEETxoCWZrgvOlmyMzxFEwVJE5xZKzvyJ4WxEc16Gd4Xe3Weq4XH2jKRikqOkGQ87hQnC7wBmGYLAnesX3M+S87eFATauuN+Qcrh7xIxXJbUIdMw3JGE3ylCWzrieaqCn4zhGM19TQ3z1oH1AX+pWEqIc7wNGAkULBo/ZxRaV9NNyh4Br3rCHZzbzmSfawBL0dNRwpW1kK9mxPXR9povcdrGSZK9c2k0xwFGzjuniCtRSZCZ6ccZ7gaktmgAOtKbG/JnOkJrjcQTdFMsxRQ2cLY3WTIrlCw1eWKn8R6pvt4GFDso3QoL4a3nLk3G6JrtME3dSenpx7PNFTmga0EaJTLQ061sEeQoWXhSo9LTXsaSjoJQRXeZLtDclbCrYzfzHHeaKjHCVOUkQHO3JeEepr56mhiyaYYKjjNU+Fed1wS5VlhWSqI/hYUdDOkaxiKehoyOnrCV5yBHtbWFqTHCCwtpDcYolesVR5yUzTZBb3RNMd0d6WP+SvhuBmRcGxnuQzT95IC285cr41cLGQ6aJJhmi4TMGempxeimBRQw1tFKV+8jd6KuzoSTqqDxzRtpZkurvKEHxlqXKRIjjfUNNXQsNOsRScoWFLT+YeRZVD3GRN0MdQcKqQjHDMrdGGVu3iYJpQx3WGUvfbmxwFfR20WBq0oYY7LMFhhgYtr8jpaEnaOzjawWWaTP8mMr0t/EPDPoqcnxTBI5o58L7uoWnMrpoqPwgVrlAUWE+V+TQl9rawoyP6QGAlQw2TPRX+YSkxyBC8Z6jhHkXBgQL7WII3DVFnRfCrBfxewv9D6xsyjys4VkhWb9pUU627JllV0YDNHMku/ldNMMXDEo4aFnAkk4U6frNEU4XgZUPmEKHUl44KrzmYamjAbh0JFvGnaTLPu1s9jPCwjFpYiN7z1DTOk/nc07CfDFzmCf7i+bfNHXhDtLeBXzTBT5rkMvWOIxpl4EMh2LGJBu2syDnAEx2naEhHDWMMzPZEhygyS1mS5RTJr5ZkoKbEUoYqr2kqdDUE8ztK7OaIntJkFrIECwv8LJTaVx5XJE86go8dFeZ3FN3rjabCAYpoYEeC9zzJVULBbmZhDyd7ko09ydpNZ3nm2Kee4FPPXHnYEF1nqOFEC08LUVcDvYXkJHW8gTaKCk9YGOeIJhqiE4ToPEepdp7IWFjdwnWaufGMwJJCMtUTTBBK9BGCOy2tGGrJTHIwyEOzp6aPzNMOtlZkDvcEWpP5SVNhfkvDxhmSazTJXYrM9U1E0xwFVwqZQwzJxw6+kGGGUj2FglGGmnb1/G51udRSMNlTw6GGnCcUwVcOpmsqTHa06o72sw1RL02p9z0VbnMLOaIX3QKaYKSCFQzBKEUNHTSc48k53RH9wxGMtpQa5KjjW0W0n6XCCCG4yxNNdhQ4R4l1Ff+2sSd6UFHiIEOyqqFgT01mEUMD+joy75jPhOA+oVVLm309FR4yVOlp4RhLiScNmSmaYF5Pw0STrOIoWMSR2UkRXOMp+M4SHW8o8Zoi6OZgjKOaFar8zZDzkWzvKOjkKBjmCXby8JahhjXULY4KlzgKLvAwxVGhvyd4zxB1d9T0piazmKLCVZY5sKiD0y2ZSYrkUEPUbIk+dlQ4SJHTR50k1DPaUWIdTZW9NJwnJMOECgd7ou/MnppMJ02O1VT4Wsh85MnZzcFTngpXGKo84qmwgKbCL/orR/SzJ2crA+t6Mp94KvxJUeIbT3CQu1uIdlQEOzlKfS3UMcrTiFmOuroocrZrT2AcmamOKg8YomeEKm/rlT2sociMaybaUlFhuqHCM2qIJ+rg4EcDFymiDSxzaHdPcpE62pD5kyM5SBMoA1PaUtfIthS85ig1VPiPPYXgYEMNk4Qq7TXBgo7oT57gPUdwgCHzhIVFPFU6OYJzHAX9m5oNrVjeE61miDrqQ4VSa1oiURTsKHC0IfjNwU2WzK6eqK8jWln4g15TVBnqmDteCJ501PGAocJhhqjZdtBEB6lnhLreFJKxmlKbeGrqLiSThVIbCdGzloasa6lpMQXHCME2boLpJgT7yWaemu6wBONbqGNVRS0PKIL7LckbjmQtR7K8I5qtqel+T/ChJTNIKLjdUMNIRyvOEko9YYl2cwQveBikCNawJKcLBbc7+JM92mysNvd/Fqp8a0k6CNEe7cnZrxlW0wQXaXjaktnRwNOGZKYiONwS7a1JVheq3WgJHlQUGKHKmp4KAxXR/ULURcNgoa4zhKSLpZR3kxRRb0NmD0OFn+UCS7CzI1nbP6+o4x47QZE5xRCt3ZagnYcvmpYQktXdk5YKXTzBC57kKEe0VVuiSYqapssMS3C9p2CKkHOg8B8Pa8p5atrIw3qezIWanMGa5HRDNF6RM9wcacl0N+Q8Z8hsIkSnaIIdHRUOEebAPy1zbCkhM062FCJtif7PU+UtoVXzWKqM1PxXO8cfdruhFQ/a6x3JKYagvVDhQEtNiyiiSQ7OsuRsZUku0CRNDs4Sog6KKjsZgk2bYJqijgsEenoKeniinRXBn/U3lgpPdyDZynQx8IiioMnCep5Ky8mjGs6Wty0l1hUQTcNWswS3WRp2kCNZwJG8omG8JphPUaFbC8lEfabwP7VtM9yoaNCAjpR41VNhrD9LkbN722v0CoZMByFzhaW+MyzRYEWFDQwN2M4/JiT76PuljT3VU/A36eaIThb+R9oZGOAJ9tewkgGvqOMNRWYjT/Cwu99Q8LqDE4TgbLWxJ1jaDDAERsFOFrobgjUsBScaguXU8kKm2RL19tRypSHnHNlHiIZqgufs4opgQdVdwxBNNFBR6kVFqb8ogimOzB6a6HTzrlDHEpYaxjiiA4TMQobkDg2vejjfwJGWmnbVFAw3H3hq2NyQfG7hz4aC+w3BbwbesG0swYayvpAs6++Ri1Vfzx93mFChvyN5xVHTS+0p9aqCAxyZ6ZacZyw5+7uuQkFPR9DDk9NOiE7X1PCYJVjVUqq7JlrHwWALF5nfHNGjApdpqgzx5OwilDhCiDYTgnc9waGW4BdLNNUQvOtpzDOWHDH8D7TR/A/85KljEQu3NREc4Pl/6B1Hhc8Umb5CsKMmGC9EPcxoT2amwHNCmeOEnOPbklnMkbOgIvO5UMOpQrS9UGVdt6iH/fURjhI/WOpaW9OKLYRod6HCUEdOX000wpDZQ6hwg6LgZfOqo1RfT/CrJzjekXOGhpc1VW71ZLbXyyp+93ILbC1kPtIEYx0FIx1VDrLoVzXRKRYWk809yYlC9ImcrinxtabKnzRJk3lAU1OLEN1j2zrYzr2myHRXJFf4h4QKT1qSTzTB5+ZNTzTRkAxX8FcLV2uS8eoQQ2aAkFzvCM72sJIcJET3WPjRk5wi32uSS9rfZajpWEvj9hW42F4o5NytSXYy8IKHay10VYdrcl4SkqscrXpMwyGOgtkajheSxdQqmpxP1L3t4R5PqasFnrQEjytq6qgp9Y09Qx9o4S1FzhUCn1kyHSzBWLemoSGvOqLNhZyBjmCaAUYpMgt4Ck7wBBMMwWKWgjsUwTaGVsxWC1mYoKiyqqeGKYqonSIRQ3KIkHO0pmAxTdBHkbOvfllfr+AA+7gnc50huVKYK393FOyg7rbPO/izI7hE4CnHHHnJ0ogNPRUGeUpsrZZTBJcrovUcJe51BPsr6GkJdhCCsZ6aTtMEb2pqWkqeVtDXE/QVggsU/Nl86d9RMF3DxvZTA58agu810RWawCiSzzXBeU3MMW9oyJUedvNEvQyNu1f10BSMddR1vaLCYpYa/mGocLSiYDcLbQz8aMn5iyF4xBNMs1P0QEOV7o5gaWGuzSeLue4tt3ro7y4Tgm4G/mopdZgl6q0o6KzJWE3mMksNr3r+a6CbT8g5wZNzT9O7fi/zpaOmnz3BRoqos+tv9zMbdpxsqDBOEewtJLt7cg5wtKKbvldpSzRRCD43VFheCI7yZLppggMVBS/KMAdHODJvOwq2NQSbKKKPLdFWQs7Fqo+mpl01JXYRgq8dnGLhTiFzqmWsUMdpllZdbKlyvSdYxhI9YghOtxR8LgSLWHK62mGGVoxzBE8LNWzqH9CUesQzFy5RQzTc56mhi6fgXEWwpKfE5Z7M05ZgZUPmo6auiv8YKzDYwWBLMErIbKHJvOwIrvEdhOBcQ9JdU1NHQ7CXn2XIDFBKU2WAgcX9UAUzDXWd5alwuyJ41Z9rjKLCL4aCp4WarhPm2rH+SaHUYE001JDZ2ZAzXPjdMpZWvC9wmqIB2lLhQ01D5jO06hghWMndbM7yRJMsoCj1vYbnFQVrW9jak3OlEJ3s/96+p33dEPRV5GxiqaGjIthUU6FFEZyqCa5qJrpBdzSw95IUnOPIrCUUjRZQFrbw5PR0R1qiYx3cb6nrWUMrBmmiBQxVHtTew5ICP/ip6g4hed/Akob/32wvBHsIOX83cI8hGeNeNPCIkPmXe8fPKx84OMSRM1MTdXSwjCZ4S30jVGhvqTRak/OVhgGazHuOCud5onEO1lJr6ecVyaOK6H7zqlBlIaHE0oroCgfvGJIdPcmfLNGLjpz7hZwZQpUbFME0A1cIJa7VNORkgfsMBatbKgwwJM9bSvQXeNOvbIjelg6WWvo5kvbKaJJNHexkKNHL9xRyFlH8Ti2riB5wVPhUk7nGkJnoCe428LR/wRGdYIlmWebCyxou1rCk4g/ShugBDX0V0ZQWkh0dOVsagkM0yV6OoLd5ye+pRlsCr0n+KiQrGuq5yJDzrTAXHtLUMduTDBVKrSm3eHL+6ijxhFDX9Z5gVU/wliHYTMiMFpKLNMEywu80wd3meoFmt6VbRMPenhrOc6DVe4pgXU8DnnHakLOIIrlF4FZPIw6R+zxBP0dyq6OOZ4Q5sLKCcz084ok+VsMMyQhNZmmBgX5xIXOEJTmi7VsGTvMTNdHHhpzdbE8Du2oKxgvBqQKdDDnTFOylCFaxR1syz2iqrOI/FEpNc3C6f11/7+ASS6l2inq2ciTrCCzgyemrCL5SVPjQkdPZUmGy2c9Sw9FtR1sS30RmsKPCS4rkIC/2U0MduwucYolGaPjKEyhzmiPYXagyWbYz8LWBDdzRimAXzxx4z8K9hpzlhLq+NiQ97HuKorMUfK/OVvC2JfiHUPCQI/q7J2gjK+tTDNxkCc4TMssqCs4TGtLVwQihyoAWgj9bosU80XGW6Ac9TJGziaUh5+hnFcHOnlaM1iRn29NaqGENTTTSUHCH2tWTeV0osUhH6psuVLjRUmGWhm6OZEshGeNowABHcJ2Bpy2ZszRcKkRXd2QuKVEeXnbfaEq825FguqfgfE2whlChSRMdron+LATTPQ2Z369t4B9C5gs/ylzv+CMmepIDPclFQl13W0rspPd1JOcbghGOEutqCv5qacURQl3dDKyvyJlqKXGPgcM9FfawJAMVmdcspcYKOZc4GjDYkFlK05olNMHyHn4zFNykyOxt99RkHlfwmiHo60l2EKI+mhreEKp080Tbug08BVPcgoqC5zWt+NLDTZ7oNSF51N1qie7Va3uCCwyZbkINf/NED6jzOsBdZjFN8oqG3wxVunqCSYYKf3EdhJyf9YWGf7tRU2oH3VHgPr1fe5J9hOgHd7xQ0y7qBwXr23aGErP0cm64JVjZwsOGqL+mhNgZmhJLW2oY4UhedsyBgzrCKrq7BmcpNVhR6jBPq64Vgi+kn6XE68pp8J5/+0wRHGOpsKenQn9DZntPzjRLZpDAdD2fnSgkG9tmIXnUwQ6WVighs7Yi2MxQ0N3CqYaCXkJ0oyOztMDJjmSSpcpvlrk0RMMOjmArQ04PRV1DO1FwhCVaUVPpKUM03JK5SxPsIWRu8/CGHi8UHChiqGFDTbSRJWeYUDDcH6vJWUxR4k1FXbMUwV6e4AJFXS8oMqsZKqzvYQ9DDQdZckY4aGsIhtlubbd2r3j4QBMoTamdPZk7O/Bf62lacZwneNjQoGcdVU7zJOd7ghsUHOkosagic6cnWc8+4gg285R6zZP5s1/LUbCKIznTwK36PkdwlOrl4U1LwfdCCa+IrvFkmgw1PCAUXKWo0sURXWcI2muKJlgyFzhynCY4RBOsqCjoI1R5zREco0n2Vt09BQtYSizgKNHfUmUrQ5UOCh51BFcLmY7umhYqXKQomOop8bUnWNNQcIiBcYaC6xzMNOS8JQQfeqKBmmglB+97ok/lfk3ygaHSyZaCRTzRxQo6GzLfa2jWBPepw+UmT7SQEJyiyRkhBLMVOfcoMjcK0eZChfUNzFAUzCsEN5vP/X1uP/n/aoMX+K+nw/Hjr/9xOo7j7Pju61tLcgvJpTWXNbfN5jLpi6VfCOviTktKlFusQixdEKWmEBUKNaIpjZRSSOXSgzaaKLdabrm1/9nZ+/f+vd/vz/v9+Xy+zZ7PRorYoZqyLrCwQdEAixxVOEXNNnjX2nUSRlkqGmWowk8lxR50JPy9Bo6qJXaXwNvREBvnThPEPrewryLhcAnj5WE15Fqi8W7R1sAuEu86S4ENikItFN4xkv9Af4nXSnUVcLiA9xzesFpivRRVeFKtsMRaKBhuSbjOELnAUtlSQUpXgdfB4Z1oSbnFEetbQ0IrAe+Y+pqnDcEJFj6S8LDZzZHwY4e3XONNlARraomNEt2bkvGsosA3ioyHm+6jCMbI59wqt4eeara28IzEmyPgoRaUOEDhTVdEJhmCoTWfC0p8aNkCp0oYqih2iqGi4yXeMkOsn4LdLLnmKfh/YogjNsPebeFGR4m9BJHLzB61XQ3BtpISfS2FugsK9FAtLWX1dCRcrCnUp44CNzuCowUZmxSRgYaE6Za0W2u/E7CVXCiI/UOR8aAm1+OSyE3mOUcwyc1zBBeoX1kiKy0Zfxck1Gsyulti11i83QTBF5Kg3pDQThFMVHiPSlK+0cSedng/VaS8bOZbtsBcTcZAR8JP5KeqQ1OYKAi20njdNNRpgnsU//K+JnaXJaGTomr7aYIphoRn9aeShJWKEq9LcozSF7QleEfDI5LYm5bgVkFkRwVDBCVu0DDIkGupo8TZBq+/pMQURYErJQmPKGKjNDkWOLx7Jd5QizdUweIaKrlP7SwJDhZvONjLkOsBBX9UpGxnydhXkfBLQ8IxgojQbLFnJf81JytSljclYYyEFyx0kVBvKWOFJmONpshGAcsduQY5giVNCV51eOdJYo/pLhbvM0uDHSevNKRcrKZIqnCtJeEsO95RoqcgGK4ocZcho1tTYtcZvH41pNQ7vA0WrhIfOSraIIntIAi+NXWCErdbkvrWwjRLrt0NKUdL6KSOscTOdMSOUtBHwL6OLA0vNSdynaWQEnCpIvKaIrJJEbvHkmuNhn6OjM8VkSGSqn1uYJCGHnq9I3aLhNME3t6GjIkO7xrNFumpyTNX/NrwX7CrIRiqqWijI9JO4d1iieykyfiposQIQ8YjjsjlBh6oHWbwRjgYJQn2NgSnNycmJAk3NiXhx44Sxykihxm8ybUwT1OVKySc7vi3OXVkdBJ4AyXBeksDXG0IhgtYY0lY5ahCD0ehborIk5aUWRJviMA7Xt5kyRjonrXENkm8yYqgs8VzgrJmClK20uMM3jRJ0FiQICQF9hdETlLQWRIb5ki6WDfWRPobvO6a4GP5mcOrNzDFELtTkONLh9dXE8xypEg7z8A9jkhrQ6Fhjlg/QVktJXxt4WXzT/03Q8IaQWSqIuEvloQ2mqC9Jfi7wRul4RX3pSPlzpoVlmCtI2jvKHCFhjcM3sN6lqF6HxnKelLjXWbwrpR4xzuCrTUZx2qq9oAh8p6ixCUGr78g8oyjRAtB5CZFwi80VerVpI0h+IeBxa6Zg6kWvpDHaioYYuEsRbDC3eOmC2JvGYLeioxGknL2UATNJN6hmtj1DlpLvDVmocYbrGCVJKOrg4X6DgddLA203BKMFngdJJFtFd7vJLm6KEpc5yjQrkk7M80SGe34X24nSex1Ra5Omgb71JKyg8SrU3i/kARKwWpH0kOGhKkObyfd0ZGjvyXlAkVZ4xRbYJ2irFMkFY1SwyWxr2oo4zlNiV+7zmaweFpT4kR3kaDAFW6xpSqzJay05FtYR4HmZhc9UxKbbfF2V8RG1MBmSaE+kmC6JnaRXK9gsiXhJHl/U0qM0WTcbyhwkYIvFGwjSbjfwhiJt8ZSQU+Bd5+marPMOkVkD0muxYLIfEuhh60x/J92itguihJSEMySVPQnTewnEm+620rTQEMsOfo4/kP/0ARvWjitlpSX7GxBgcMEsd3EEeYWvdytd+Saawi6aCIj1CkGb6Aj9rwhx16Cf3vAwFy5pyLhVonXzy51FDpdEblbkdJbUcEPDEFzQ8qNmhzzLTmmKWKbFCXeEuRabp6rxbvAtLF442QjQ+wEA9eL1xSR7Q0JXzlSHjJ4exq89yR0laScJ/FW6z4a73pFMEfDiRZvuvijIt86RaSFOl01riV2mD1UEvxGk/Geg5aWwGki1zgKPG9J2U8PEg8qYvMsZeytiTRXBMslCU8JSlxi8EabjwUldlDNLfzTUmCgxWsjqWCOHavYAqsknKFIO0yQ61VL5AVFxk6WhEaCAkdJgt9aSkzXlKNX2jEa79waYuc7gq0N3GDJGCBhoiTXUEPsdknCUE1CK0fwsiaylSF2uiDyO4XX3pFhNd7R4itFGc0k/ElBZwWvq+GC6szVeEoS/MZ+qylwpKNKv9Z469UOjqCjwlusicyTxG6VpNxcQ8IncoR4RhLbR+NdpGGmJWOcIzJGUuKPGpQg8rrG21dOMqQssJQ4RxH5jaUqnZuQ0F4Q+cjxLwPtpZbIAk3QTJHQWBE5S1BokoVtDd6lhqr9UpHSUxMcIYl9pojsb8h4SBOsMQcqvOWC2E8EVehqiJ1hrrAEbQxeK0NGZ0Gkq+guSRgniM23bIHVkqwx4hiHd7smaOyglyIyQuM978j4VS08J/A2G1KeMBRo4fBaSNhKUEZfQewVQ/C1I+MgfbEleEzCUw7mKXI0M3hd1EESVji8x5uQ41nxs1q4RMJCCXs7Iq9acpxn22oSDnQ/sJTxsCbHIYZiLyhY05TY0ZLIOQrGaSJDDN4t8pVaIrsqqFdEegtizc1iTew5Q4ayBDMUsQMkXocaYkc0hZua412siZ1rSXlR460zRJ5SlHGe5j801RLMlJTxtaOM3Q1pvxJ45zUlWFD7rsAbpfEm1JHxG0eh8w2R7QQVzBUw28FhFp5QZzq8t2rx2joqulYTWSuJdTYfWwqMFMcovFmSyJPNyLhE4E10pHzYjOC3huArRa571ZsGajQpQx38SBP5pyZB6lMU3khDnp0MBV51BE9o2E+TY5Ml2E8S7C0o6w1xvCZjf0HkVEHCzFoyNmqC+9wdcqN+Tp7jSDheE9ws8Y5V0NJCn2bk2tqSY4okdrEhx1iDN8cSudwepWmAGXKcJXK65H9to8jYQRH7SBF01ESUJdd0TayVInaWhLkOjlXE5irKGOnI6GSWGCJa482zBI9rCr0jyTVcEuzriC1vcr6mwFGSiqy5zMwxBH/TJHwjSPhL8+01kaaSUuMFKTcLEvaUePcrSmwn8DZrgikWb7CGPxkSjhQwrRk57tctmxLsb9sZvL9LSlyuSLlWkqOjwduo8b6Uv1DkmudIeFF2dHCgxVtk8dpIvHpBxhEOdhKk7OLIUSdJ+cSRY57B+0DgGUUlNfpthTfGkauzxrvTsUUaCVhlKeteTXCoJDCa2NOKhOmC4G1H8JBd4OBZReSRGkqcb/CO1PyLJTLB4j1q8JYaIutEjSLX8YKM+a6phdMsdLFUoV5RTm9JSkuDN8WcIon0NZMNZWh1q8C7SJEwV5HxrmnnTrf3KoJBlmCYI2ilSLlfEvlE4011NNgjgthzEua0oKK7JLE7HZHlEl60BLMVFewg4EWNt0ThrVNEVkkiTwpKXSWJzdRENgvKGq4IhjsiezgSFtsfCUq8qki5S1LRQeYQQ4nemmCkImWMw3tFUoUBZk4NOeZYEp4XRKTGa6wJjrWNHBVJR4m3FCnbuD6aak2WsMTh3SZImGCIPKNgsDpVwnsa70K31lCFJZYcwwSMFcQulGTsZuEaSdBXkPGZhu0FsdUO73RHjq8MPGGIfaGIbVTk6iuI3GFgucHrIQkmWSJdBd7BBu+uOryWAhY7+Lki9rK5wtEQzWwvtbqGhIMFwWRJsElsY4m9IIg9L6lCX0VklaPAYkfkZEGDnOWowlBJjtMUkcGK4Lg6EtoZInMUBVYLgn0UsdmCyCz7gIGHFfk+k1QwTh5We7A9x+IdJ6CvIkEagms0hR50eH9UnTQJ+2oiKyVlLFUE+8gBGu8MQ3CppUHesnjTHN4QB/UGPhCTHLFPHMFrCqa73gqObUJGa03wgbhHkrCfpEpzNLE7JDS25FMKhlhKKWKfCgqstLCPu1zBXy0J2ztwjtixBu8UTRn9LVtkmCN2iyFhtME70JHRQ1KVZXqKI/KNIKYMCYs1GUMEKbM1bKOI9LDXC7zbHS+bt+1MTWS9odA9DtrYtpbImQJ2VHh/lisEwaHqUk1kjKTAKknkBEXkbkdMGwq0dnhzLJF3NJH3JVwrqOB4Sca2hti75nmJN0WzxS6UxDYoEpxpa4htVlRjkYE7DZGzJVU72uC9IyhQL4i8YfGWSYLLNcHXloyz7QhNifmKSE9JgfGmuyLhc403Xm9vqcp6gXe3xuuv8F6VJNxkyTHEkHG2g0aKXL0MsXc1bGfgas2//dCONXiNLCX+5mB7eZIl1kHh7ajwpikyzlUUWOVOsjSQlsS+M0R+pPje/dzBXRZGO0rMtgQrLLG9VSu9n6CMXS3BhwYmSoIBhsjNBmZbgusE9BCPCP5triU4VhNbJfE+swSP27aayE8tuTpYYjtrYjMVGZdp2NpS1s6aBnKSHDsbKuplKbHM4a0wMFd/5/DmGyKrJSUaW4IBrqUhx0vyfzTBBLPIUcnZdrAkNsKR0sWRspumSns6Ch0v/qqIbBYUWKvPU/CFoyrDJGwSNFhbA/MlzKqjrO80hRbpKx0Jewsi/STftwGSlKc1JZyAzx05dhLEdnfQvhZOqiHWWEAHC7+30FuRcZUgaO5gpaIK+xsiHRUsqaPElTV40xQZQ107Q9BZE1nryDVGU9ZSQ47bmhBpLcYpUt7S+xuK/FiT8qKjwXYw5ypS2iuCv7q1gtgjhuBuB8LCFY5cUuCNtsQOFcT+4Ih9JX+k8Ea6v0iCIRZOtCT0Et00JW5UeC85Cg0ScK0k411HcG1zKtre3SeITBRk7WfwDhEvaYLTHP9le0m8By0JDwn4TlLW/aJOvGHxdjYUes+ScZigCkYQdNdEOhkiezgShqkx8ueKjI8lDfK2oNiOFvrZH1hS+tk7NV7nOmLHicGWEgubkXKdwdtZknCLJXaCpkrjZBtLZFsDP9CdxWsSr05Sxl6CMmoFbCOgryX40uDtamB7SVmXW4Ihlgpmq+00tBKUUa83WbjLUNkzDmY7cow1JDygyPGlhgGKYKz4vcV7QBNbJIgM11TUqZaMdwTeSguH6rOaw1JRKzaaGyxVm2EJ/uCIrVWUcZUkcp2grMsEjK+DMwS59jQk3Kd6SEq1d0S6uVmO4Bc1lDXTUcHjluCXEq+1OlBDj1pi9zgiXxnKuE0SqTXwhqbETW6RggMEnGl/q49UT2iCzgJvRwVXS2K/d6+ZkyUl7jawSVLit46EwxVljDZwoSQ20sDBihztHfk2yA8NVZghiXwrYHQdfKAOtzsayjhY9bY0yE2CWEeJ9xfzO423xhL5syS2TFJofO2pboHob0nY4GiAgRrvGQEDa/FWSsoaaYl0syRsEt3kWoH3B01shCXhTUWe9w3Bt44SC9QCh3eShQctwbaK2ApLroGCMlZrYqvlY3qYhM0aXpFkPOuoqJ3Dm6fxXrGwVF9gCWZagjPqznfkuMKQ8DPTQRO8ZqG1hPGKEm9IgpGW4DZDgTNriTxvFiq+Lz+0cKfp4wj6OCK9JSnzNSn9LFU7UhKZZMnYwcJ8s8yRsECScK4j5UOB95HFO0CzhY4xJxuCix0lDlEUeMdS6EZBkTsUkZ4K74dugyTXS7aNgL8aqjDfkCE0ZbwkCXpaWCKhl8P7VD5jxykivSyxyZrYERbe168LYu9ZYh86IkscgVLE7tWPKmJv11CgoyJltMEbrohtVAQfO4ImltiHEroYEs7RxAarVpY8AwXMcMReFOTYWe5iiLRQxJ5Q8DtJ8LQhWOhIeFESPGsILhbNDRljNbHzNRlTFbk2S3L0NOS6V1KFJYKUbSTcIIhM0wQ/s2TM0SRMNcQmSap3jCH4yhJZKSkwyRHpYYgsFeQ4U7xoCB7VVOExhXepo9ABBsYbvGWKXPME3lyH95YioZ0gssQRWWbI+FaSMkXijZXwgiTlYdPdkNLaETxlyDVIwqeaEus0aTcYcg0RVOkpR3CSJqIddK+90JCxzsDVloyrFd5ZAr4TBKfaWa6boEA7C7s6EpYaeFPjveooY72mjIccLHJ9HUwVlDhKkmutJDJBwnp1rvulJZggKDRfbXAkvC/4l3ozQOG9a8lxjx0i7nV4jSXc7vhe3OwIxjgSHjdEhhsif9YkPGlus3iLFDnWOFhtCZbJg0UbQcIaR67JjthoCyMEZRwhiXWyxO5QxI6w5NhT4U1WsJvDO60J34fW9hwzwlKij6ZAW9ne4L0s8C6XeBMEkd/LQy1VucBRot6QMlbivaBhoBgjqGiCJNhsqVp/S2SsG6DIONCR0dXhvWbJ+MRRZJkkuEjgDXJjFQW6SSL7GXK8Z2CZg7cVsbWGoKmEpzQ5elpiy8Ryg7dMkLLUEauzeO86CuwlSOlgYLojZWeJ9xM3S1PWfEfKl5ISLQ0MEKR8YOB2QfCxJBjrKPCN4f9MkaSsqoVXJBmP7EpFZ9UQfOoOFwSzBN4MQ8LsGrymlipcJQhmy0GaQjPqCHaXRwuCZwRbqK2Fg9wlClZqYicrIgMdZfxTQ0c7TBIbrChxmuzoKG8XRaSrIhhiyNFJkrC7oIAWMEOQa5aBekPCRknCo4IKPrYkvCDI8aYmY7WFtprgekcJZ3oLIqssCSMtFbQTJKwXYy3BY5oCh2iKPCpJOE+zRdpYgi6O2KmOAgvVCYaU4ySRek1sgyFhJ403QFHiVEmJHwtybO1gs8Hr5+BETQX3War0qZngYGgtVZtoqd6vFSk/UwdZElYqyjrF4HXUeFspIi9IGKf4j92pKGAdCYMVsbcV3kRF0N+R8LUd5PCsIGWoxDtBkCI0nKofdJQxT+LtZflvuc8Q3CjwWkq8KwUpHzkK/NmSsclCL0nseQdj5FRH5CNHSgtLiW80Of5HU9Hhlsga9bnBq3fEVltKfO5IaSTmGjjc4J0otcP7QsJUSQM8pEj5/wCuUuC2DWz8AAAAAElFTkSuQmCC"); +} diff --git a/codemirror/theme/twilight.css b/codemirror/theme/twilight.css new file mode 100644 index 0000000..fd8944b --- /dev/null +++ b/codemirror/theme/twilight.css @@ -0,0 +1,26 @@ +.cm-s-twilight.CodeMirror { background: #141414; color: #f7f7f7; } /**/ +.cm-s-twilight .CodeMirror-selected { background: #323232 !important; } /**/ + +.cm-s-twilight .CodeMirror-gutters { background: #222; border-right: 1px solid #aaa; } +.cm-s-twilight .CodeMirror-linenumber { color: #aaa; } +.cm-s-twilight .CodeMirror-cursor { border-left: 1px solid white !important; } + +.cm-s-twilight .cm-keyword { color: #f9ee98; } /**/ +.cm-s-twilight .cm-atom { color: #FC0; } +.cm-s-twilight .cm-number { color: #ca7841; } /**/ +.cm-s-twilight .cm-def { color: #8DA6CE; } +.cm-s-twilight span.cm-variable-2, .cm-s-twilight span.cm-tag { color: #607392; } /**/ +.cm-s-twilight span.cm-variable-3, .cm-s-twilight span.cm-def { color: #607392; } /**/ +.cm-s-twilight .cm-operator { color: #cda869; } /**/ +.cm-s-twilight .cm-comment { color:#777; font-style:italic; font-weight:normal; } /**/ +.cm-s-twilight .cm-string { color:#8f9d6a; font-style:italic; } /**/ +.cm-s-twilight .cm-string-2 { color:#bd6b18 } /*?*/ +.cm-s-twilight .cm-meta { background-color:#141414; color:#f7f7f7; } /*?*/ +.cm-s-twilight .cm-error { border-bottom: 1px solid red; } +.cm-s-twilight .cm-builtin { color: #cda869; } /*?*/ +.cm-s-twilight .cm-tag { color: #997643; } /**/ +.cm-s-twilight .cm-attribute { color: #d6bb6d; } /*?*/ +.cm-s-twilight .cm-header { color: #FF6400; } +.cm-s-twilight .cm-hr { color: #AEAEAE; } +.cm-s-twilight .cm-link { color:#ad9361; font-style:italic; text-decoration:none; } /**/ + diff --git a/codemirror/theme/vibrant-ink.css b/codemirror/theme/vibrant-ink.css new file mode 100644 index 0000000..22024a4 --- /dev/null +++ b/codemirror/theme/vibrant-ink.css @@ -0,0 +1,27 @@ +/* Taken from the popular Visual Studio Vibrant Ink Schema */ + +.cm-s-vibrant-ink.CodeMirror { background: black; color: white; } +.cm-s-vibrant-ink .CodeMirror-selected { background: #35493c !important; } + +.cm-s-vibrant-ink .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; } +.cm-s-vibrant-ink .CodeMirror-linenumber { color: #d0d0d0; } +.cm-s-vibrant-ink .CodeMirror-cursor { border-left: 1px solid white !important; } + +.cm-s-vibrant-ink .cm-keyword { color: #CC7832; } +.cm-s-vibrant-ink .cm-atom { color: #FC0; } +.cm-s-vibrant-ink .cm-number { color: #FFEE98; } +.cm-s-vibrant-ink .cm-def { color: #8DA6CE; } +.cm-s-vibrant-ink span.cm-variable-2, .cm-s-cobalt span.cm-tag { color: #FFC66D } +.cm-s-vibrant-ink span.cm-variable-3, .cm-s-cobalt span.cm-def { color: #FFC66D } +.cm-s-vibrant-ink .cm-operator { color: #888; } +.cm-s-vibrant-ink .cm-comment { color: gray; font-weight: bold; } +.cm-s-vibrant-ink .cm-string { color: #A5C25C } +.cm-s-vibrant-ink .cm-string-2 { color: red } +.cm-s-vibrant-ink .cm-meta { color: #D8FA3C; } +.cm-s-vibrant-ink .cm-error { border-bottom: 1px solid red; } +.cm-s-vibrant-ink .cm-builtin { color: #8DA6CE; } +.cm-s-vibrant-ink .cm-tag { color: #8DA6CE; } +.cm-s-vibrant-ink .cm-attribute { color: #8DA6CE; } +.cm-s-vibrant-ink .cm-header { color: #FF6400; } +.cm-s-vibrant-ink .cm-hr { color: #AEAEAE; } +.cm-s-vibrant-ink .cm-link { color: blue; } diff --git a/codemirror/theme/xq-dark.css b/codemirror/theme/xq-dark.css new file mode 100644 index 0000000..fd9bb12 --- /dev/null +++ b/codemirror/theme/xq-dark.css @@ -0,0 +1,46 @@ +/* +Copyright (C) 2011 by MarkLogic Corporation +Author: Mike Brevoort + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +.cm-s-xq-dark.CodeMirror { background: #0a001f; color: #f8f8f8; } +.cm-s-xq-dark span.CodeMirror-selected { background: #a8f !important; } +.cm-s-xq-dark .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; } +.cm-s-xq-dark .CodeMirror-linenumber { color: #f8f8f8; } +.cm-s-xq-dark .CodeMirror-cursor { border-left: 1px solid white !important; } + +.cm-s-xq-dark span.cm-keyword {color: #FFBD40;} +.cm-s-xq-dark span.cm-atom {color: #6C8CD5;} +.cm-s-xq-dark span.cm-number {color: #164;} +.cm-s-xq-dark span.cm-def {color: #FFF; text-decoration:underline;} +.cm-s-xq-dark span.cm-variable {color: #FFF;} +.cm-s-xq-dark span.cm-variable-2 {color: #EEE;} +.cm-s-xq-dark span.cm-variable-3 {color: #DDD;} +.cm-s-xq-dark span.cm-property {} +.cm-s-xq-dark span.cm-operator {} +.cm-s-xq-dark span.cm-comment {color: gray;} +.cm-s-xq-dark span.cm-string {color: #9FEE00;} +.cm-s-xq-dark span.cm-meta {color: yellow;} +.cm-s-xq-dark span.cm-error {color: #f00;} +.cm-s-xq-dark span.cm-qualifier {color: #FFF700;} +.cm-s-xq-dark span.cm-builtin {color: #30a;} +.cm-s-xq-dark span.cm-bracket {color: #cc7;} +.cm-s-xq-dark span.cm-tag {color: #FFBD40;} +.cm-s-xq-dark span.cm-attribute {color: #FFF700;} diff --git a/course/judgestatus.php b/course/judgestatus.php new file mode 100644 index 0000000..bda6c86 --- /dev/null +++ b/course/judgestatus.php @@ -0,0 +1,102 @@ +config->perpageonfulllist; + + if (!$course = get_record('course', 'id', $block->instance->pageid)) { + error('course misconfigured'); + } + + require_login($course->id); + +/// Print the page header + if (!isset($CFG->scripts) || !is_array($CFG->scripts)) { + $CFG->scripts = array(); + $CFG->scripts[] = '/mod/programming/programming.js'; + } + $CFG->stylesheets[] = $CFG->wwwroot.'/mod/programming/programming.css'; + array_unshift($CFG->scripts, $CFG->wwwroot.'/mod/programming/js/MochiKit/MochiKit.js'); + + if ($course->category) { + $navigation = ''.$course->shortname.' ->'; + } else { + $navigation = ''; + } + + $strprogrammings = get_string('modulenameplural', 'programming'); + $strprogramming = get_string('modulename', 'programming'); + + $meta = ''; + foreach ($CFG->scripts as $script) { + $meta .= ''; + $meta .= "\n"; + } + + print_header( + $course->shortname.': '.get_string('programmingjudgestatus', 'block_programming_judge_status'), + $course->fullname, + $navigation.get_string('programmingjudgestatus', 'block_programming_judge_status'), + '', // focus + $meta, + true, + '', + '', + false); + +/// Print the main part of the page + $offset = min(10000, $perpage * $page); + $tops = programming_judge_status($block->instance->pageid, $totalcount, $offset, $perpage); + + echo '
    '; + echo '

    '.get_string('programmingjudgestatus', 'block_programming_judge_status').'

    '; + + $table = new flexible_table('programming-judge-status'); + $table->define_columns(array('number', 'user', 'name', 'result', 'timeused', 'memused', 'time')); + $table->define_headers(array( + get_string('no.', 'block_programming_judge_status'), + get_string('who', 'block_programming_judge_status'), + get_string('which', 'block_programming_judge_status'), + get_string('result', 'block_programming_judge_status'), + get_string('timeused', 'block_programming_judge_status'), + get_string('memused', 'block_programming_judge_status'), + get_string('submittime', 'block_programming_judge_status'), + )); + $table->set_attribute('cellspacing', '1'); + $table->set_attribute('cellpadding', '3'); + $table->set_attribute('id', 'programming-judge-status'); + $table->set_attribute('class', 'generaltable generalbox'); + $table->set_attribute('align', 'center'); + $table->define_baseurl($CFG->wwwroot.'/blocks/programming_judge_status/fulllist.php?id='.$id); + $table->pagesize($perpage, min(10000, $totalcount)); + $table->setup(); + + $i = $totalcount - $page * $perpage; + if ($tops) { + foreach ($tops as $t) { + $table->add_data(array( + $i--, + has_capability('block/programming_judge_status:view') ? ''.fullname($t->user).'' : '???', + "".$t->globalid.'.'.$t->pname.'', + "$t->judgeresult", + isset($t->timeused) ? sprintf('%6.3f', $t->timeused) : '', + isset($t->memused) ? $t->memused : '', + userdate($t->timemodified, '%Y-%m-%d %H:%M:%S'), + )); + } + } + + $table->print_html(); + + echo '
    '; + +/// Finish the page + $OUTPUT->footer($course); +?> diff --git a/course/resemble.php b/course/resemble.php new file mode 100644 index 0000000..ac4569a --- /dev/null +++ b/course/resemble.php @@ -0,0 +1,147 @@ +get_record('course', array('id'=>$id))) { + error('Course ID is incorrect'); + } + + require_login($course->id); + + + +/// Get all required strings + + $strprogrammings = get_string('modulenameplural', 'programming'); + $strprogramming = get_string('modulename', 'programming'); + + +/// Print the header + $title = get_string('resemble', 'programming'); + include_once('../pageheader.php'); + + $currenttab = 'resemble'; + include_once('../index_tabs.php'); + +/// Get all the appropriate data + + if (! $programmings = get_all_instances_in_course('programming', $course)) { + notice('There are no programmings', '../../course/view.php?id='.$course->id); + die; + } + +/// Print the list of instances (your module will probably extend this) + + $strname = get_string('name'); + $strsimilitudedegree = get_string('similitudedegree', 'programming'); + $strprogram1 = get_string('program1', 'programming'); + $strpercent1 = get_string('percent1', 'programming'); + $strprogram2 = get_string('program2', 'programming'); + $strpercent2 = get_string('percent2', 'programming'); + $strmatchedlines = get_string('matchedlines', 'programming'); + $strmediumdegree = get_string('mediumsimilitude', 'programming'); + $strhighdegree = get_string('highsimilitude', 'programming'); + + if (! $programmings = get_all_instances_in_course('programming', $course)) { + notice('There are no programmings', '../../course/view.php?id='.$course->id); + die; + } + $sql = "SELECT pr.*, p.name, ps1.userid AS userid1, ps2.userid AS userid2 + FROM {$CFG->prefix}programming_resemble pr, + {$CFG->prefix}programming p, + {$CFG->prefix}programming_submits ps1, + {$CFG->prefix}programming_submits ps2 + WHERE p.course = $id + AND pr.flag > 0 + AND pr.programmingid = p.id + AND ps1.programmingid = p.id + AND ps2.programmingid = p.id + AND pr.submitid1 = ps1.id + AND pr.submitid2 = ps2.id + AND (ps1.userid = $USER->id OR ps2.userid = $USER->id) + ORDER BY p.id"; + $rows = $DB->get_records_sql($sql); + $uids = array(); + if (is_array($rows)) { + foreach ($rows as $row) { + if (!in_array($row->userid1, $uids)) $uids[] = $row->userid1; + if (!in_array($row->userid2, $uids)) $uids[] = $row->userid2; + } + } + if (count($uids) > 0) { + $uids = implode(',', $uids); + $sql = "SELECT * FROM mdl_user WHERE id IN ($uids)"; + $users = $DB->get_records_sql($sql); + } else { + $users = array(); + } + + $table->head = array($strname, $strsimilitudedegree, $strprogram1, $strpercent1, $strprogram2, $strpercent2, $strmatchedlines); + $table->align = array('LEFT', 'CENTER', 'CENTER', 'CENTER', 'CENTER', 'CENTER', 'CENTER'); + foreach ($programmings as $programming) { + if (is_array($rows)) { + foreach ($rows as $row) { + if ($row->programmingid != $programming->id) continue; + + switch($row->flag) { + case PROGRAMMING_RESEMBLE_WARNED: + $styleclass1 = $styleclass2 = 'warned'; + $degree = $strmediumdegree; + break; + case PROGRAMMING_RESEMBLE_CONFIRMED: + $styleclass1 = $styleclass2 = 'confirmed'; + $degree = $strhighdegree; + break; + case PROGRAMMING_RESEMBLE_FLAG1: + $styleclass1 = 'confirmed'; + $styleclass2 = ''; + $degree = $strhighdegree; + break; + case PROGRAMMING_RESEMBLE_FLAG2: + $styleclass1 = ''; + $styleclass2 = 'confirmed'; + $degree = $strhighdegree; + break; + case PROGRAMMING_RESEMBLE_FLAG3: + $styleclass1 = $styleclass2 = 'flag3'; + $degree = $strhighdegree; + break; + default: + $styleclass1 = $styleclass2 = ''; + } + + $user1 = print_user_picture($row->userid1, $course->id, $users[$row->userid1]->picture, 0, true).fullname($users[$row->userid1]); + $user2 = print_user_picture($row->userid2, $course->id, $users[$row->userid2]->picture, 0, true).fullname($users[$row->userid2]); + + $table->data[] = array( + "$row->name", + $degree, + "$user1", + "$row->percent1", + "$user2", + "$row->percent2", + "$row->matchedcount"); + } + } + } + + echo '
    '; + echo '

    '.get_string('resemble', 'programming').'

    '; + if (is_array($rows)) { + print_table($table); + } else { + echo get_string('noresemble', 'programming'); + } + echo '
    '; + +/// Finish the page + + $OUTPUT->footer($course); + +?> diff --git a/course_testcase.php b/course_testcase.php new file mode 100644 index 0000000..9c1e5c7 --- /dev/null +++ b/course_testcase.php @@ -0,0 +1,210 @@ +'; + require ('../../config.php'); + + + if(!function_exists('bzcompress')){ + echo '请开启bz2服务'; + exit(); + } + +function file_list($source_dir,$target_dir){ + $init_memory = memory_get_usage(); + global $DB; + if(function_exists('set_time_limit')){ + set_time_limit(3000); + } + + $i=1; + $unsetcount=1; //没有下载到的案例 + $file_in_str = ''; + $file_out_str = ''; // 输出 字符串 + $file_in_sequence = 101; + $file_out_sequence = 102; //输出 序列号 + + $file_in_size = 0; + + if($handle = opendir($source_dir)){ // 打开路径 + while(false !== ($file = readdir($handle))){//循环读取目录中的文件名并赋值给$file + if($file != "." && $file != ".."){ //排除当前路径和前一路径 + if(is_dir($source_dir.'/'.$file)){ + //echo $source_dir.": ".$file."
    ";//去掉此行显示的是所有的非目录文件 + file_list($source_dir.'/'.$file,$target_dir); +// break 2;//只循环一个文件夹 + }else{ + // echo $source_dir . "/".$file."
    "; + $strNoName = strrev(strtok(strrev($source_dir), '/')); + $inoutID = ltrim(substr($strNoName,0,4),0); + $inoutFileName = substr($strNoName,4); + if(strstr($file, 'in')){ + $file_in_size = filesize($source_dir."/".$file) ;// 单个文件超过5m 则只转换 一个in和out + } + + /**读文件部分 方法1-- 占用内存较少 效率低**/ + $fp = fopen($source_dir."/".$file, "r"); + $buffer = ''; + if($fp){ + while(!feof($fp)){ + ob_flush(); + $buffer = fgets($fp,2048);//2m + + if(strstr($file, 'in')){ + $file_in_str .= $buffer;//输入的文件 + } + if(strstr($file, 'out')){ + $file_out_str .= $buffer;//输出的文件 + } + flush(); + } + fclose($fp); + + if(!is_dir($target_dir.'/'.$strNoName)){ + mkdir($target_dir.'/'.$strNoName, 0777); + } + if(!file_exists($target_dir.'/'.$strNoName.'/'.$file)){ + copy($source_dir.'/'.$file,$target_dir.'/'.$strNoName.'/'.$file); //拷贝到新目录 + unlink($source_dir.'/'.$file); //删除旧目录下的文件 + if(!isEmptyDir($source_dir)){ + rmdir($source_dir); //删除空的目录 + } + } + } + unset($buffer); + + if(strstr($file, 'in')){ + $file_in_sequence = str_replace($inoutFileName, "", $file); + $file_in_sequence = str_replace(".in", '', $file_in_sequence); + $file_in_str = str_replace("\r","",$file_in_str); + $file_in_str = str_replace("\n\n","",$file_in_str); + + } + if(strstr($file, 'out')){ + $file_out_sequence = str_replace($inoutFileName, "", $file); + $file_out_sequence = str_replace(".out", '', $file_out_sequence); + $file_out_str = str_replace("\r","",$file_out_str); + $file_out_str = str_replace("\n\n","",$file_out_str); + } + } + } + // 处理,入库 + $sql = ''; + while($file_in_sequence==$file_out_sequence & !empty($file_in_sequence)){ + + if($unsetcount>30){//此变量,必须为---偶数--- 每次不宜超过20个<有一些文件比较大,输入比较耗时> + redirectPage($init_memory); + } else if(empty($inoutFileName) || empty($inoutID)){ + $unsetcount++; + break 1; + } + $sql = "select name from {study_data_test} where in_out='$inoutFileName' and nob='$inoutID' "; + $programmingName = $DB->get_field_sql($sql); + if(!$programmingName){ + $unsetcount++; + break 1; + } + $programmingName = str_replace('] ', ']', $programmingName); + $sql = "select * from {programming} where name=? "; + $programming = $DB->get_record_sql($sql,array($programmingName)); + if(!$programming){ + $unsetcount++; + break 1; + } + + //判断该 测试案例是否存在 + $sql = "select * from {programming_tests} where programmingid=$programming->id and seq='$file_in_sequence'"; + $caseMsg = $DB->get_record_sql($sql); + + if ($caseMsg) { + echo '当前课程--'.$programmingName .'--'.$programming->id."--$file_in_sequence 已存在*****删除后,重新添加
    "; + /** unset($file_in_str);unset($file_out_str); + $file_in_str = '';$file_out_str = ''; // 输出 字符串 + $unsetcount++; + if($file_in_size>1024*1024*4){ + redirectPage(); + } + break 1;**/ + $DB->delete_records('programming_tests',array('id'=>$caseMsg->id)); + } + + $testcase = array(); + $testcase['programmingid'] = (int)$programming->id; // 这3个,在数据库里面读 + $testcase['timelimit'] = (int)$programming->timelimit; + $testcase['memlimit'] = (int)ceil($programming->memlimit/1024); + + $testcase['seq'] = $file_in_sequence; + $testcase['input'] = $file_in_str; + $testcase['output'] = $file_out_str; + + if (strlen($testcase['input']) > 1024) { + $testcase['gzinput'] = bzcompress($testcase['input']); + $testcase['input'] = mb_substr($testcase['input'], 0, 1024, 'UTF-8'); + }else{ + $testcase['gzinput'] = null; + } + if (strlen($testcase['output']) > 1024) { + $testcase['gzoutput'] = bzcompress($testcase['output']); + $testcase['output'] = mb_substr($testcase['output'], 0, 1024, 'UTF-8'); + }else{ + $testcase['gzoutput'] = null; + } + + $testcase['cmdargs'] = NULL; + + $testcase['nproc'] =0; + $testcase['pub'] = 1; + $testcase['weight'] = 1; + $testcase['memo'] = ''; + + $testcase['timemodified'] = time(); + + echo '当前课程--'.$programmingName ."--$file_in_sequence--"; + + $cmid = $DB->insert_record('programming_tests',$testcase); + + echo $cmid . '
    '; + unset($file_in_str);unset($file_out_str);unset($testcase); + //处理完成后,重置初始参数 + $file_in_str = ''; + $file_out_str = ''; // 输出 字符串 + $file_in_sequence = 101; + $file_out_sequence = 102; //输出 序列号 + + if($file_in_size> 1024*1024*4 ){// 单个文件超过3m 则只转换 一个in和out + redirectPage($init_memory); + } + } + $i++; + if($i>30){ //此变量,必须为---偶数--- 每次不宜超过20个<有一些文件比较大,输入比较耗时> + redirectPage($init_memory); + + } + + } + } +} + +$source_dir = "/www/ftpold"; +$target_dir = "/www/ftp"; + +file_list($source_dir,$target_dir); + +function isEmptyDir( $path ) +{ + $dh= opendir( $path ); + while(false !== ($f = readdir($dh))) + { + if($f != "." && $f != ".." ) + return true; + } + return false; +} +function redirectPage($init_memory){ + $page = 'course_testcase.php?asf='. rand(1, 999); + echo '3秒后跳转到下一页,如果没有跳转点击这里'; + $final_memory = memory_get_usage(); + $final_memory = ceil(($final_memory - $init_memory)/1024); + echo '
    当前使用的内存是:

    '.$final_memory.' kb

    '; + echo ''; + exit(); +} +?> diff --git a/course_testcase_check_valid.php b/course_testcase_check_valid.php new file mode 100644 index 0000000..fca6eda --- /dev/null +++ b/course_testcase_check_valid.php @@ -0,0 +1,68 @@ +'; + require ('../../config.php'); + +if(function_exists('set_time_limit')){ + set_time_limit(3000); +} +$buffer = ini_get('output_buffering'); +echo str_repeat(' ',$buffer+1); //防止浏览器缓存 +ob_end_flush(); //关闭缓存 +ini_set('memory_limit','1024M'); + echo '

    检测以下数据,输出bz2解压读出数据为-4:

    '; + $page=1; + //读1500条记录 + for($i=0;$i<10;$i++){ + $init_memory = memory_get_usage(); + ob_start(); + $pagesize = 100; + + //之前转换的方法 (测试的表) + $strsql="SELECT t.*,p.name,p.id,p.course FROM mdl_programming p join mdl_programming_tests t on t.programmingid=p.id where (t.gzinput is not null or t.gzoutput is not null ) limit " . ($page-1)*$pagesize.','.$pagesize . ""; + +// 新的转换方法 (服务器上最新的表,应该使用这个) +// $strsql="SELECT * FROM mdl_programming_tests t , mdl_programming p where t.programmingid=p.id limit " . ($page-1)*$pagesize.','.$pagesize . ""; + echo $strsql.'
    '; + echo '正在处理:'. ($page-1)*$pagesize.','.$pagesize .'条记录
    '; + flush; + // 执行sql查询 + $result = $DB->get_records_sql($strsql); + foreach($result as $key => $value){ + $obj = new stdClass(); + $obj = $value; + + //output + if(!is_null($obj->gzoutput)){ + $bz_output = ''; + $bz_output = bzdecompress($obj->gzoutput); + if($bz_output=='-4'){ + echo $obj->course.':'.$obj->id .'-'.$obj->name .'-'.$obj->seq . '--ouput--不正常的数据
    '; + flush; + } + } + //input + if(!is_null($obj->gzinput)){ + $bz_input = ''; + $bz_input = bzdecompress($obj->gzinput); + if($bz_input=='-4'){ + echo $obj->course.':'.$obj->id .'-'.$obj->name .'-'.$obj->seq.'--inpu--不正常的数据
    '; + flush; + } + } + unset($bz_output); unset($bz_input); unset($obj); + } + ob_flush(); + flush(); + + sleep(1); + $page++; + $final_memory = memory_get_usage(); + $final_memory = ceil(($final_memory - $init_memory)/1024); + echo '
    当前使用的内存是:

    '.$final_memory.' kb

    '; + flush; + } + + + +?> \ No newline at end of file diff --git a/course_testcase_v3.php b/course_testcase_v3.php new file mode 100644 index 0000000..196b1e3 --- /dev/null +++ b/course_testcase_v3.php @@ -0,0 +1,393 @@ +'; +require ('../../config.php'); + + +if(!function_exists('bzcompress')){ + echo '请开启bz2服务'; + exit(); +} + +set_time_limit(0); + + +//操作说明 +/** + * 操作前,先备份 mdl_programming_test表 + * 本机测试 全部通过,没有出现-4的问题。 + * 一个in 对应 一个out + + 存在问题: + 出现超时,可以刷新或者重启浏览器。必要时可以重启apache服务。 + + 需要设置的变量 + php.ini -- realpath_cache_size=16MB + php.ini -- output_buffering=40960; 大一些 默认是4096 + 如果要修改本页文件名,还需要更改redirectPage函数上的页面地址。*/ +/** + * 操作思路: + * 在源文件$source_dir上,每次取前10个文件夹循环 把所有子文件存在一个数组上 + * 根据数组上的名字 对比 programing表。 + * 读取文件后,移动文件到$target_dir上 + * 处理文件上的字符串,转换,清理。 + * 对programming_test操作 + * + * 如果文件上对应的题库,不存在programming表,则移动到noexists目录上。 + * 在windows,复制到$target_dir后,有一些(1-2)个文件,在$source_dir上无法删除 + * 则需要人工手动处理。 + * linux 情况未知。 + * + * 超大文件比如 0477px 可以手工处理 + */ +$source_dir = "/www/a"; +$target_dir = "/www/b"; + +$init_memory = memory_get_usage(); +$buffer = ini_get('output_buffering'); +echo str_repeat(' ',$buffer+1); //防止浏览器缓存 +ob_end_flush(); //关闭缓存 +$source_arr = array(); +$dirsize=0; +file_list($source_dir); + +get_testcase_io($source_arr,$target_dir); +redirectPage($init_memory); + +//批量去掉空格 +function rename_programming(){ + global $DB; + $sql = "select * from {programming}"; + $programminglist = $DB->get_records_sql($sql); + + if(!empty($programminglist)){ + foreach($programminglist as $v){ + if(strpos($v->name,']')){ + $newname = str_replace('] ', ']', $v->name); + echo $newname.'update**************
    '; + $update = array('id'=>$v->id,'name'=>$newname); + $DB->update_record_raw('programming', $update); + flush; + } + } + } +} + +//不使用这种方法 +function handle_programming_testcase($source_dir,$target_dir,$limit=10){ + global $DB; + //flag=0 未采集 + //test=0 未通过测试 + $sql = "SELECT * FROM {study_data_test} where name is not null and flag=0 and test=0 and id>1 limit $limit "; + echo $sql.'
    ';flush; + $testlist = $DB->get_records_sql($sql); + if(empty($testlist)){ + die('没有可以转换的test case'); + } + $testcase = array(); + foreach($testlist as $key=>$value){ + $filename_pre = str_pad($value->nob,4,0,STR_PAD_LEFT); + $filename = $filename_pre.$value->in_out; + $filepath = $source_dir . '/'.$filename; + $value->filepath=$filepath;; + $value->name = str_replace('] ', ']', $value->name); + $testcase[] = $value; + echo $value->name.'
    '; + } + unset($testlist); + flush; + // get_testcase_io($testcase,$source_dir,$target_dir); + +} + +function file_list($source_dir){ +global $source_arr,$dirsize; + $dirsize_limit=1024*1024*10;//每次处理10m的文件(已经很大了,数值更大,容易造成浏览器假死) + + if ($handle = opendir($source_dir)) { + while (false !== ($file = readdir($handle))) { + if ($file != "." && $file != "..") { + if (is_dir($source_dir . "/" . $file)) { + //echo $source_dir . ": " . $file . "
    "; //去掉此行显示的是所有的非目录文件 + file_list($source_dir . "/" . $file); + } else { + $str_index = strrpos($source_dir,'/'); + $tmp_str = $source_dir; + $dir_name = substr($tmp_str, $str_index); + $dir_name = trim($dir_name,'/'); + $filename = basename($source_dir . "/" . $file); + $path = dirname($source_dir . "/" . $file); + $source_arr[$dir_name]['dirname'] = $dir_name; + $source_arr[$dir_name]['filepath'] = $path; + $dirsize += filesize($source_dir . "/" . $file); + $source_arr[$dir_name]['filesize'] = $dirsize; + if(strrpos($filename, '.in')){ + $filename = str_replace('.in', '', $filename); + $source_arr[$dir_name]['filename'][] = $filename; + } + if(count($source_arr)>5 || $dirsize >= $dirsize_limit){ + break 1; + } + } + } + } + } + + $source_arr = array_slice($source_arr,0,2); + + return $source_arr; +} +function get_testcase_io($testcase,$target_dir){ + + global $DB; + + foreach($testcase as $key => $value){ + $filepath = $value['filepath']; + $strNoName = $value['dirname']; + + foreach($value['filename'] as $kx=>$vs){ + $buffer = $file_in_str = $file_out_str= ''; + $realName = $vs; + $trim_pre = substr($strNoName, 4); + $seq = str_replace($trim_pre, '', $vs); + $fp_in =fopen($filepath.'/'.$realName.'.in','r'); + if(!$fp_in){ + $fp_in = fopen($target_dir.'/'.$strNoName.'/'.$realName.'.in','r'); + //有可能in文件已经移动到target的可能(由于意外情况网页终止) + } + if($fp_in){ + $fp_out = fopen($filepath.'/'.$realName.'.out','r'); + if($fp_out){ + fclose($fp_out); + $file = $realName; + + //先判断是否存在课程,不存在则移走 + $programmingName = $trim_pre.'.in'; + $sql = "select * from {programming} where inputfile=?"; + + $programming = $DB->get_record_sql($sql,array($programmingName)); + + if(!$programming){ + echo $programmingName.' 这个课程不存在,文件将移动到'; + echo $target_dir.'/noexists/'.$strNoName.'
    '; + rmdirs($filepath, $target_dir); + unset($seq);unset($file_in_str);unset($file_out_str); + flush; + break 1; + } + + if($fp_in){ + $file = $realName . '.in'; + while(!feof($fp_in)){ + ob_flush(); + $buffer = fgets($fp_in,81920);//2m + $file_in_str .= $buffer;//输入的文件 + flush(); + } + $buffer = ''; + if($fp_in){ + pclose($fp_in); + } + if(!is_dir($target_dir.'/'.$strNoName)){ + mkdir($target_dir.'/'.$strNoName, 0777); + } + if(!file_exists($target_dir.'/'.$strNoName.'/'.$file)){ + copy($filepath.'/'.$file,$target_dir.'/'.$strNoName.'/'.$file); //拷贝到新目录 + unlink($filepath.'/'.$file); //删除旧目录下的文件 + if(!isEmptyDir($filepath)){ + rmdir($filepath); //删除空的目录 + } + } + $file_in_str = stripcslashes($file_in_str); + + $file_in_str = mb_ereg_replace('\r\n\r\n', '', $file_in_str); + $file_in_str = mb_ereg_replace('\r\n\n', '', $file_in_str); + $file_in_str = mb_ereg_replace(chr(13), '', $file_in_str); + $file_in_str = mb_ereg_replace('\n\n', '\n', $file_in_str); + } + $file = $realName; + $buffer = ''; + $fp_out = fopen($filepath.'/'.$realName.'.out','r'); + if($fp_out){ + $file .= '.out'; + while(!feof($fp_out)){ + $buffer = fgets($fp_out,40960);//2m + $file_out_str .= $buffer;//输入的文件 + ob_flush(); + flush(); + } + unset($buffer); + if($fp_out){ + fclose($fp_out); + } + + if(!is_dir($target_dir.'/'.$strNoName)){ + mkdir($target_dir.'/'.$strNoName, 0777); + } + + if(!file_exists($target_dir.'/'.$strNoName.'/'.$file)){ + copy($filepath.'/'.$file,$target_dir.'/'.$strNoName.'/'.$file); //拷贝到新目录 + unlink($filepath.'/'.$file); //删除旧目录下的文件 + if(!isEmptyDir($filepath)){ + rmdir($filepath); //删除空的目录 + } + } + $file_out_str = stripcslashes($file_out_str); + + $file_out_str = mb_ereg_replace('\r\n\r\n','',$file_out_str); + $file_out_str = mb_ereg_replace('\r\n\n','',$file_out_str); + $file_out_str = mb_ereg_replace(chr(13),'',$file_out_str); + $file_out_str = mb_ereg_replace('\n\n','\n',$file_out_str); + } + + //判断该 测试案例是否存在 + $sql = "select id from {programming_tests} where programmingid=$programming->id and seq='$seq' limit 1"; + $caseMsg = $DB->get_record_sql($sql); + + if ($caseMsg) { + echo '当前课程--'.$programming->name .'--'.$programming->id."--$seq 已存在*****删除后,重新添加
    "; + $DB->delete_records('programming_tests',array('id'=>$caseMsg->id)); + flush; + } + + $testcase = array(); + $testcase['programmingid'] = (int)$programming->id; // 这3个,在数据库里面读 + $testcase['timelimit'] = (int)$programming->timelimit; + $testcase['memlimit'] = (int)ceil($programming->memlimit/1024); + + $testcase['seq'] = $seq; + $testcase['input'] = $file_in_str; + $testcase['output'] = $file_out_str; + + if (strlen($testcase['input']) > 1024) { + $testcase['gzinput'] = bzcompress($testcase['input']); + $testcase['input'] = mb_substr($testcase['input'], 0, 1024, 'UTF-8'); + }else{ + $testcase['gzinput'] = null; + } + if (strlen($testcase['output']) > 1024) { + $testcase['gzoutput'] = bzcompress($testcase['output']); + $testcase['output'] = mb_substr($testcase['output'], 0, 1024, 'UTF-8'); + }else{ + $testcase['gzoutput'] = null; + } + + $testcase['cmdargs'] = NULL; + + $testcase['nproc'] =0; + $testcase['pub'] = 1; + $testcase['weight'] = 1; + $testcase['memo'] = ''; + + $testcase['timemodified'] = time(); + + echo '当前课程--'.$programming->name ."--$seq--"; + + $cmid = $DB->insert_record('programming_tests',$testcase); + + echo $cmid . '
    '; + unset($programming);unset($seq); + unset($file_in_str);unset($file_out_str);unset($testcase); + //处理完成后,重置初始参数 + $file_in_str = '';$file_out_str = ''; // 输出 字符串 + flush; + }else { + if($fp_out){ + fclose($fp_out); + } + if($fp_in){ + fclose($fp_in); + } + } + } else { + if($fp_in){ + fclose($fp_in); + } + } + } + unset($testcase[$key]); + } +} + +function isEmptyDir( $path ){ + $dh= opendir( $path ); + while(false !== ($f = readdir($dh))){ + if($f != "." && $f != ".." ) + return true; + } + return false; +} +function redirectPage($init_memory){ + global $dirsize; + $dirsize=0; + $page = 'course_testcase_v3.php?asf='. rand(1, 999); + echo '3秒后跳转到下一页,如果没有跳转点击这里'; + $final_memory = memory_get_usage(); + $final_memory = ceil(($final_memory - $init_memory)/1024); + echo '
    当前使用的内存是:

    '.$final_memory.' kb

    '; + echo ''; + flush; + exit(); +} + +function dir_path($path){ + $path = str_replace('\\','/',$path); + if(substr($path,-1)!='/'){ + $path = $path . '/'; + } + return $path; +} + +function dir_list($path,$exts,$list = array()){ + $path = dir_path($path); + $files = glob($path.'*.*'); + foreach($files as $v){ + if(!$exts || preg_match("/\.($exts)/i", $v)){ + $list[] = $v; + if(is_dir($v)){ + $list = dir_list($v, $exts, $list); + } + } + } + return $list; +} + +//移动文件夹 +function rmdirs($source,$dest){ + if(!is_dir($source)){ + return null; + } + $error = ''; + $source = str_replace('\\', '/', $source); + $dest = str_replace("\\", '/', $dest); + $filename = strrchr($source,'/'); + $filename = trim($filename,'/'); + + $source_arr = scandir($source); + chmod($source, 0777); + foreach($source_arr as $key=>$val){ + if($val == '.' || $val == '..'){ + unset($source_arr[$key]); + }else { + if(is_dir($source.'/'.$val)){ +// if(@rmdir($source.'/'.$val) == 'true'){} +// else +// rmdirs($source.'/'.$val,$dest); + }else{ + if(!is_dir($dest.'/noexists/'.$filename)){ + mkdir($dest.'/noexists/'.$filename, 0777, true); + } + copy($source.'/'.$val, $dest.'/noexists/'.$filename.'/'.$val); + if(!unlink($source.'/'.$val)){ + $error = '文件夹:'.$source.'的内容删除失败,请手动删除!
    '; + } + } + } + } + if(!empty($error)){ + echo $error; + } + if(!isEmptyDir($source)){ + @rmdir($source); + } + } +?> diff --git a/datafile/add.php b/datafile/add.php new file mode 100644 index 0000000..030c626 --- /dev/null +++ b/datafile/add.php @@ -0,0 +1,73 @@ +libdir.'/weblib.php'); + require_once('../lib.php'); + require_once('form.php'); + + $id = required_param('id', PARAM_INT); // programming ID + $params = array('id' => $id); + $PAGE->set_url('/mod/programming/datafile/list.php', $params); + + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + require_capability('mod/programming:edittestcase', $context); + + $mform = new datafile_form(); + if ($mform->is_cancelled()) { + redirect(new moodle_url('list.php', array('id' => $cm->id))); + + } else if ($data = $mform->get_data()) { + unset($data->id); + $data->programmingid = $programming->id; + + $data->seq = $DB->count_records('programming_datafile', array('programmingid' => $programming->id), 'MAX(seq)') + 1; + + $content = $mform->get_file_content('data'); + $data->data = bzcompress($content); + $data->datasize = strlen($content); + + if (!empty($data->usecheckdata)) { + $content = $mform->get_file_content('checkdata'); + $data->checkdata = bzcompress($content); + $data->checkdatasize = strlen($content); + } + + $data->timemodified = time(); + $DB->insert_record('programming_datafile', $data); + programming_datafile_adjust_sequence($programming->id); + + redirect(new moodle_url('list.php', array('id' => $cm->id)), get_string('datafileadded', 'programming')); + + } else { + /// Print the page header + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + + /// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('edittest', 'datafile', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + + /// Print page content + echo html_writer::tag('h2', $programming->name); + echo html_writer::tag('h3', get_string('adddatafile', 'programming').$OUTPUT->help_icon('datafile', 'programming')); + $mform->display(); + + /// Finish the page + echo $OUTPUT->footer($course); + } diff --git a/datafile/delete.php b/datafile/delete.php new file mode 100644 index 0000000..084135e --- /dev/null +++ b/datafile/delete.php @@ -0,0 +1,33 @@ + $id, 'datafile' => $datafile_id); + $PAGE->set_url('/mod/programming/datafile/delete.php', $params); + + if ($id) { + if (! $cm = get_coursemodule_from_id('programming', $id)) { + error('Course Module ID was incorrect'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + error('Course is misconfigured'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + error('Course module is incorrect'); + } + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + require_capability('mod/programming:edittestcase', $context); + + $DB->delete_records('programming_datafile', array('id' => $datafile_id)); + programming_datafile_adjust_sequence($programming->id); + redirect(new moodle_url('/mod/programming/datafile/list.php', array('id' => $cm->id)), get_string('datafiledeleted', 'programming'), 1); + +?> diff --git a/datafile/download.php b/datafile/download.php new file mode 100644 index 0000000..96b0af8 --- /dev/null +++ b/datafile/download.php @@ -0,0 +1,55 @@ + $id, 'datafile' => $datafile_id); + if ($checkdata) { + $params['checkdata'] = $checkdata; + } + $PAGE->set_url('/mod/programming/datafile/download.php', $params); + + if ($id) { + if (! $cm = get_coursemodule_from_id('programming', $id)) { + error('Course Module ID was incorrect'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + error('Course is misconfigured'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + error('Course module is incorrect'); + } + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + if ($checkdata) { + require_capability('mod/programming:viewhiddentestcase', $context); + } else { + require_capability('mod/programming:viewpubtestcase', $context); + } + + + $file = $DB->get_record('programming_datafile', array('id' => $datafile_id, 'programmingid' => $programming->id)); + if ($file) { + $content = bzdecompress($checkdata ? $file->checkdata : $file->data); + $size = $checkdata ? $file->checkdatasize : $file->datasize; + if ($file->isbinary) { + header('Content-Type: application/octec-stream'); + } else{ + header('Content-Type: plain/text'); + } + header("Content-Disposition: attachment; filename=$file->filename"); + header("Content-Length: $size"); + print $content; + } else { + header('HTTP/1.0 404 Not Found'); + echo 'Not Found'; + } +?> diff --git a/datafile/edit.php b/datafile/edit.php new file mode 100644 index 0000000..a01b9aa --- /dev/null +++ b/datafile/edit.php @@ -0,0 +1,82 @@ +libdir.'/weblib.php'); + require_once('../lib.php'); + require_once('form.php'); + + $id = required_param('id', PARAM_INT); // programming ID + $datafile_id = required_param('datafile', PARAM_INT); + $params = array('id' => $id, 'datafile' => $datafile_id); + $PAGE->set_url('/mod/programming/datafile/edit.php', $params); + + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + require_capability('mod/programming:edittestcase', $context); + + $mform = new datafile_form(); + if ($mform->is_cancelled()) { + redirect(new moodle_url('/mod/programming/datafile/list.php', array('id' => $cm->id))); + + } else if ($data = $mform->get_data()) { + $data->id = $data->datafile; + $content = $mform->get_file_content('data'); + if (!empty($content)) { + $data->datasize = strlen($content); + $data->data = bzcompress($content); + } else { + unset($data->datasize); + unset($data->data); + } + if (!empty($data->usecheckdata)) { + $content = $mform->get_file_content('checkdata'); + if (!empty($content)) { + $data->checkdatasize = strlen($content); + $data->checkdata = bzcompress($content); + } else { + unset($data->checkdatasize); + unset($data->checkdata); + } + } + + $data->timemodified = time(); + $DB->update_record('programming_datafile', $data); + + redirect(new moodle_url('/mod/programming/datafile/list.php', array('id' => $cm->id)), get_string('datafilemodified', 'programming')); + + } else { + $data = $DB->get_record('programming_datafile', array('id' => $datafile_id)); + $data->datafile = $data->id; + $data->id = $cm->id; + $mform->set_data($data); + + /// Print the page header + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + + /// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('edittest', 'datafile', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + + /// Print page content + echo html_writer::tag('h2', $programming->name); + echo html_writer::tag('h3', get_string('editdatafile', 'programming').$OUTPUT->help_icon('datafile', 'programming')); + $mform->display(); + + /// Finish the page + echo $OUTPUT->footer($course); + } diff --git a/datafile/form.php b/datafile/form.php new file mode 100644 index 0000000..e31bd26 --- /dev/null +++ b/datafile/form.php @@ -0,0 +1,59 @@ +libdir.'/formslib.php'); + +class datafile_form extends moodleform { + + function definition() { + global $CFG, $COURSE, $cm; + $mform =& $this->_form; + +//------------------------------------------------------------------------------- + $mform->addElement('hidden', 'id', $cm->id); + $mform->addElement('hidden', 'datafile'); + + $places = array(); + $mform->addElement('text', 'filename', get_string('filename', 'programming'), 'maxlength="50"'); + $filetype = array(); + $filetype[] = $mform->createElement('radio', 'isbinary', null, get_string('textfile', 'programming'), 0); + $filetype[] = $mform->createElement('radio', 'isbinary', null, get_string('binaryfile', 'programming'), 1); + $mform->addGroup($filetype, 'filetype', get_string('filetype', 'programming'), ' ', false); + $mform->addElement('filepicker', 'data', get_string('datafile', 'programming')); + $mform->addElement('checkbox', 'usecheckdata', get_string('usecheckdata', 'programming')); + $mform->addElement('filepicker', 'checkdata', get_string('datafileforcheck', 'programming')); + $mform->disabledIf('checkdata', 'usecheckdata'); + + $mform->addElement('textarea', 'memo', get_string('memo', 'programming'), 'rows="5" cols="50"'); + +// buttons + $this->add_action_buttons(); + } + + function validation($data, $files) { + $errors = array(); + /// filename should not be empty + if (empty($data['filename'])) { + $errors['filename'] = get_string('required'); + } else { + /// filename should only contain alpha, digit and underlins + if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $data['filename'])) { + $errors['filename'] = get_string('filenamechars', 'programming'); + } + + /// file name should not duplicate + if (empty($data['id']) && count_records_select('programming_datafile', "programmingid={$data['programmingid']} AND filename='{$data['filename']}'")) { + $errors['filename'] = get_string('datafilenamedupliate', 'programming'); + } + } + + if (empty($data['id']) && empty($files['data'])) { + $errors['data'] = get_string('required'); + } + + if (empty($data['id']) && !empty($data['usecheckdata']) && empty($files['checkdata'])) { + $errors['checkdata'] = get_string('required'); + } + + return $errors; + } + +} diff --git a/datafile/list.php b/datafile/list.php new file mode 100644 index 0000000..b53a3d7 --- /dev/null +++ b/datafile/list.php @@ -0,0 +1,117 @@ + $id); + $PAGE->set_url('/mod/programming/datafile/list.php', $params); + + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + require_capability('mod/programming:viewhiddentestcase', $context); + +/// Print the page header + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + +/// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('edittest', 'datafile', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + +/// Print page content + echo html_writer::tag('h2', $programming->name); + echo html_writer::tag('h3', get_string('datafiles', 'programming').$OUTPUT->help_icon('datafile', 'programming')); + print_datafile_table(); + +/// Finish the page + echo $OUTPUT->footer($course); + +function print_datafile_table() { + global $CFG, $DB, $OUTPUT, $cm, $params, $page, $perpage, $programming, $course, $language, $groupid; + + $table = new html_table(); + $table->head = array( + get_string('sequence', 'programming'), + get_string('filename', 'programming'), + get_string('filetype', 'programming'), + get_string('data', 'programming'), + get_string('checkdata', 'programming'), + get_string('action'), + ); + $table->data = array(); + + /**$table->set_attribute('id', 'presetcode-table'); + $table->set_attribute('class', 'generaltable generalbox'); + $table->set_attribute('align', 'center'); + $table->set_attribute('cellpadding', '3'); + $table->set_attribute('cellspacing', '1'); + $table->no_sorting('code');*/ + + $strpresstodownload = get_string('presstodownload', 'programming'); + $strbinaryfile = get_string('binaryfile', 'programming'); + $strtextfile = get_string('textfile', 'programming'); + $stredit = get_string('edit'); + $strdelete = get_string('delete'); + $strmoveup = get_string('moveup'); + $strmovedown = get_string('movedown'); + $files = $DB->get_records('programming_datafile', array('programmingid' => $programming->id), 'seq'); + if (is_array($files)) { + $files_count = count($files)-1; + $i = 0; + foreach ($files as $file) { + $data = array(); + $data[] = $file->seq; + $data[] = htmlentities($file->filename); + $data[] = $file->isbinary ? $strbinaryfile : $strtextfile; + $size = programming_format_codesize($file->datasize); + $url = new moodle_url('/mod/programming/datafile/download.php', array('id' => $cm->id, 'datafile' => $file->id)); + $data[] = $OUTPUT->action_link($url, $size, null, array('title' => $strpresstodownload)); + if ($file->checkdatasize) { + $size = programming_format_codesize($file->checkdatasize); + $url->param('checkdata', 1); + $data[] = $OUTPUT->action_link($url, $size, null, array('title' => $strpresstodownload)); + } else { + $data[] = get_string('n/a', 'programming'); + } + $url = new moodle_url('/mod/programming/datafile/edit.php', array('id' => $cm->id, 'datafile' => $file->id)); + $html = $OUTPUT->action_link($url, html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/edit'))), null, array('class' => 'icon edit', 'title' => $stredit)); + $url = new moodle_url('/mod/programming/datafile/delete.php', array('id' => $cm->id, 'datafile' => $file->id)); + $act = new confirm_action(get_string('deletedatafileconfirm', 'programming')); + $html .= $OUTPUT->action_link($url, html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/delete'))), $act, array('class' => 'icon delete', 'title' => $strdelete)); + if ($i > 0) { + $url = new moodle_url('/mod/programming/datafile/move.php', array('id' => $cm->id, 'datafile' => $file->id, 'direction' => 1)); + $html .= $OUTPUT->action_link($url, html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/up'))), null, array('class' => 'icon up', 'title' => $strmoveup)); + } + if ($i < $files_count) { + $url = new moodle_url('/mod/programming/datafile/move.php', array('id' => $cm->id, 'datafile' => $file->id, 'direction' => 2)); + $html .= $OUTPUT->action_link($url, html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/down'))), null, array('class' => 'icon down', 'title' => $strmovedown)); + } + $data[] = $html; + $table->data[] = $data; + $i++; + } + + echo html_writer::table($table); + } else { + echo html_writer::tag('p', get_string('nodatafile', 'programming')); + } + echo html_writer::tag('p', $OUTPUT->action_link(new moodle_url('/mod/programming/datafile/add.php', array('id' => $cm->id)), get_string('adddatafile', 'programming'))); +} + +?> diff --git a/datafile/move.php b/datafile/move.php new file mode 100644 index 0000000..706a284 --- /dev/null +++ b/datafile/move.php @@ -0,0 +1,33 @@ + $id, 'datafile' => $datafile_id, 'direction' => $direction); + $PAGE->set_url('/mod/programming/datafile/move.php', $params); + + if ($id) { + if (! $cm = get_coursemodule_from_id('programming', $id)) { + error('Course Module ID was incorrect'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + error('Course is misconfigured'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + error('Course module is incorrect'); + } + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + require_capability('mod/programming:edittestcase', $context); + + programming_datafile_adjust_sequence($programming->id, $datafile_id, $direction); + redirect(new moodle_url('/mod/programming/datafile/list.php', array('id' => $cm->id)), get_string('datafilemoved', 'programming'), 1); + +?> diff --git a/db/access.php b/db/access.php new file mode 100644 index 0000000..b948d50 --- /dev/null +++ b/db/access.php @@ -0,0 +1,279 @@ + array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_PREVENT, + 'teacher' => CAP_PREVENT, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_PREVENT, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:viewcontent' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_ALLOW, + 'student' => CAP_ALLOW, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_ALLOW, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:viewcontentatanytime' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_PREVENT, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_PREVENT, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:submitprogram' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_ALLOW, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_ALLOW, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:submitatanytime' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_PREVENT, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_PREVENT, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:submitforothers' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_PREVENT, + 'teacher' => CAP_PREVENT, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_PREVENT, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:deleteothersubmit' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_PREVENT, + 'teacher' => CAP_PREVENT, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_PREVENT, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:viewdetailresult' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_ALLOW, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_ALLOW, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:viewdetailresultincontest' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_PREVENT, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_ALLOW, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:viewsummaryresult' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_ALLOW, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_ALLOW, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:viewhistory' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_ALLOW, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_ALLOW, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:edittestcase' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_PREVENT, + 'teacher' => CAP_PREVENT, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_PREVENT, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:viewpubtestcase' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_ALLOW, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_ALLOW, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:viewhiddentestcase' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_PREVENT, + 'teacher' => CAP_PREVENT, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_PREVENT, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:viewotherprogram' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_PREVENT, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_PREVENT, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:viewotherresult' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_PREVENT, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_PREVENT, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:viewreport' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_ALLOW, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_ALLOW, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:viewresemble' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_ALLOW, + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_ALLOW, + 'admin' => CAP_ALLOW + ) + ), + 'mod/programming:editresemble' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_PREVENT, + 'teacher' => CAP_PREVENT, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_PREVENT, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:updateresemble' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_PREVENT, + 'teacher' => CAP_PREVENT, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_PREVENT, + 'admin' => CAP_ALLOW + ) + ), + + 'mod/programming:rejudge' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'legacy' => array( + 'guest' => CAP_PREVENT, + 'student' => CAP_PREVENT, + 'teacher' => CAP_PREVENT, + 'editingteacher' => CAP_ALLOW, + 'coursecreator' => CAP_PREVENT, + 'admin' => CAP_ALLOW + ) + ), + +); + +?> diff --git a/db/install.php b/db/install.php new file mode 100644 index 0000000..a0c6129 --- /dev/null +++ b/db/install.php @@ -0,0 +1,60 @@ +. + +/** + * This file replaces the legacy STATEMENTS section in db/install.xml, + * lib.php/modulename_install() post installation hook and partially defaults.php + * + * @package mod + * @subpackage programming + * @copyright 2011 Your Name + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +/** + * Post installation procedure + * + * @see upgrade_plugins_modules() + */ +function xmldb_programming_install() { + global $DB; + $sql="insert into {programming_languages} (name, description, sourceext, headerext) VALUES ('gcc-3.3', 'C (GCC 3.3)', '.c', '.h')"; + $DB->execute($sql); + $sql="insert into {programming_languages} (name, description, sourceext, headerext) VALUES ('g++-3.3', 'C++ (G++ 3.3)', '.cpp .cxx', '.h .hpp')"; + $DB->execute($sql); + $sql="insert into {programming_languages} (name, description, sourceext, headerext) VALUES ('java-1.5', 'Java (Sun JDK 5)', '.java', NULL)"; + $DB->execute($sql); + $sql="insert into {programming_languages} (name, description, sourceext, headerext) VALUES ('java-1.6', 'Java (Sun JDK 6)', '.java', NULL)"; + $DB->execute($sql); + $sql="insert into {programming_languages} (name, description, sourceext, headerext) VALUES ('fpc-2.2', 'Pascal (Free Pascal 2)', '.pas', NULL)"; + $DB->execute($sql); + $sql="insert into {programming_languages} (name, description, sourceext, headerext) VALUES ('python-2.5', 'Python 2.5', '.py', NULL)"; + $DB->execute($sql); + $sql="insert into {programming_languages} (name, description, sourceext, headerext) VALUES ('gmcs-2.0', 'C# (Mono 2.0)', '.cs', NULL)"; + $DB->execute($sql); + $sql="insert into {programming_languages} (name, description, sourceext, headerext) VALUES ('bash-3', 'Bash (Bash 3)', '.sh', NULL)"; + $DB->execute($sql); + $DB->set_field('modules', 'visible', 0, array('name'=>'programming')); +} + +/** + * Post installation recovery procedure + * + * @see upgrade_plugins_modules() + */ +function xmldb_programming_install_recovery() { +} diff --git a/db/install.xml b/db/install.xml new file mode 100644 index 0000000..ac930e9 --- /dev/null +++ b/db/install.xml @@ -0,0 +1,250 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + + + +
    diff --git a/db/mysql.php b/db/mysql.php new file mode 100644 index 0000000..759761e --- /dev/null +++ b/db/mysql.php @@ -0,0 +1,121 @@ +prefix}programming_tests` ADD `weight` TINYINT(3) NOT NULL DEFAULT '3'"); + + } + + if ($oldversion < 2005100103) { + + execute_sql("ALTER TABLE `{$CFG->prefix}programming` ADD `keeplatestonly` TINYINT(3) NOT NULL DEFAULT 0 AFTER attempts"); + + } + + if ($oldversion < 2006030412) { + + execute_sql("ALTER TABLE `{$CFG->prefix}programming` ADD `timediscount` INT(10) NOT NULL DEFAULT '130000000' AFTER `memlimit`"); + execute_sql("ALTER TABLE `{$CFG->prefix}programming` ADD `discount` FLOAT NOT NULL DEFAULT '8' AFTER `timediscount`"); + + } + + if ($oldversion < 2006040200) { + + // Add new columns to test results + execute_sql("ALTER TABLE `{$CFG->prefix}programming_test_results` ADD `status` INT(10) NOT NULL DEFAULT '0' AFTER `passed`"); + execute_sql("ALTER TABLE `{$CFG->prefix}programming_test_results` ADD `stderr` TEXT NULL AFTER `output`"); + execute_sql("ALTER TABLE `{$CFG->prefix}programming_test_results` CHANGE `output` `output` TEXT NULL"); + + // Change the type of column language of submits + execute_sql("UPDATE `{$CFG->prefix}programming_submits` set language=1 where language='c89' or language='c99'"); + execute_sql("UPDATE `{$CFG->prefix}programming_submits` set language=2 where language='c++98'"); + execute_sql("ALTER TABLE `{$CFG->prefix}programming_submits` CHANGE `language` `language` INT(10) NULL"); + + // Create a table for languages + execute_sql("CREATE TABLE {$CFG->prefix}programming_languages ( id int(10) NOT NULL auto_increment, name varchar(20) NOT NULL, PRIMARY KEY (id)) COMMENT='programming language'"); + execute_sql("INSERT INTO {$CFG->prefix}programming_languages VALUES (1, 'gcc-3.3')"); + execute_sql("INSERT INTO {$CFG->prefix}programming_languages VALUES (2, 'g++-3.3')"); + + } + + if ($oldversion < 2006040312) { + // Add new columns to test results + execute_sql("ALTER TABLE `{$CFG->prefix}programming_test_results` ADD exitcode TINYINT(3) NOT NULL DEFAULT '0' AFTER `status`"); + execute_sql("ALTER TABLE `{$CFG->prefix}programming_test_results` ADD signal TINYINT(3) NOT NULL DEFAULT '0' AFTER `exitcode`"); + execute_sql("ALTER TABLE `{$CFG->prefix}programming_test_results` DROP `status`"); + } + + if ($oldversion < 2006040512) { + execute_sql(" + CREATE TABLE {$CFG->prefix}programming_langlimit ( + id int(10) NOT NULL AUTO_INCREMENT, + programmingid int(10) NOT NULL, + languageid int(10) NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY programminglanguage(programmingid, languageid), + UNIQUE KEY languageprogramming(languageid, programmingid) + ) COMMENT='programming language limit'; + "); + } + + if ($oldversion < 2006040617) { + execute_sql("ALTER TABLE `{$CFG->prefix}programming_tests` CHANGE `input` `input` MEDIUMTEXT NOT NULL"); + execute_sql("ALTER TABLE `{$CFG->prefix}programming_tests` CHANGE `output` `output` MEDIUMTEXT NOT NULL"); + } + + if ($oldversion < 2006062300) { + execute_sql(" + CREATE TABLE `{$CFG->prefix}programming_resemble` ( + id int(10) NOT NULL auto_increment, + programmingid int(10) NOT NULL default '0', + matchedcount int(4) NOT NULL default '0', + matchedlines text, + submitid1 int(10) NOT NULL default '0', + percent1 int(2) NOT NULL default '0', + submitid2 int(10) NOT NULL default '0', + percent2 int(2) NOT NULL default '0', + flag tinyint(2) NOT NULL default '0', + PRIMARY KEY (id), + KEY proglines (programmingid, flag, matchedcount) + ) COMMENT='resemble info returned by moss'; + "); + } + + if ($oldversion < 2006070301) { + execute_sql("ALTER TABLE `{$CFG->prefix}programming` ADD `generatortype` tinyint(1) NOT NULL DEFAULT '0'"); + execute_sql("ALTER TABLE `{$CFG->prefix}programming` CHANGE `generator` `generator` TEXT"); + execute_sql("ALTER TABLE `{$CFG->prefix}programming` ADD `validatortype` tinyint(1) NOT NULL DEFAULT '0'"); + execute_sql("ALTER TABLE `{$CFG->prefix}programming` CHANGE `validator` `validator` TEXT"); + } + + if ($oldversion < 2006112801) { + execute_sql("ALTER TABLE `{$CFG->prefix}programming_submits` ADD `codelines` int(10) NOT NULL default '0' AFTER `code`"); + execute_sql("ALTER TABLE `{$CFG->prefix}programming_submits` ADD `codesize` int(10) NOT NULL default '0' AFTER `codelines`"); + execute_sql("UPDATE `{$CFG->prefix}programming_submits` SET codesize = CHAR_LENGTH(code)"); + execute_sql("UPDATE `{$CFG->prefix}programming_submits` SET codelines = codesize - CHAR_LENGTH(REPLACE(code, '\n', ''))"); + } + + if ($oldversion < 2006112802) { + execute_sql("ALTER TABLE `{$CFG->prefix}programming` ADD `showmode` TINYINT(1) NOT NULL DEFAULT '1'"); + } + + if ($oldversion < 2006121001) { + execute_sql("ALTER TABLE `{$CFG->prefix}programming_test_results` CHANGE `output` `output` TEXT CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL"); + execute_sql("ALTER TABLE `{$CFG->prefix}programming_test_results` CHANGE `stderr` `stderr` TEXT CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL"); + } + + return true; +} + +?> diff --git a/db/upgrade.php b/db/upgrade.php new file mode 100644 index 0000000..1d8593e --- /dev/null +++ b/db/upgrade.php @@ -0,0 +1,92 @@ +get_manager(); +/// And upgrade begins here. For each one, you'll need one +/// block of code similar to the next one. Please, delete +/// this comment lines once this file start handling proper +/// upgrade code. + +/// if ($result && $oldversion < YYYYMMDD00) { //New version in version.php +/// $result = result of "/lib/ddllib.php" function calls +/// } +//2012051101 + //2011062402 is the latest version fits for moodle1.9x + if ($result && $oldversion < 2011062402) { + $prefix = $DB->get_prefix(); + $sql = "ALTER TABLE `{$prefix}programming` CHANGE COLUMN `description` `intro` longtext NOT NULL,"; + $sql .= "CHANGE COLUMN `descformat` `introformat` tinyint(2) NOT NULL DEFAULT 0;"; + $DB->change_database_structure($sql); + upgrade_mod_savepoint(true, 2011062402, 'programming'); + + } + + if ($result && $oldversion < 2012081804) { + $prefix = $DB->get_prefix(); + $sql = "ALTER TABLE {$prefix}programming_presetcode CHANGE COLUMN presetcodeforcheck presetcodeforcheck LONGTEXT NULL;"; + $DB->change_database_structure($sql); + upgrade_mod_savepoint(true, 2012081804, 'programming'); + } +//2012080803 + if ($result && $oldversion < 2012081903) { + $prefix = $DB->get_prefix(); + $sql = "ALTER TABLE {$prefix}programming_datafile CHANGE COLUMN checkdatasize checkdatasize bigint(10) NULL, CHANGE COLUMN checkdata checkdata longblob NULL;"; + $DB->change_database_structure($sql); + upgrade_mod_savepoint(true, 2012081903, 'programming'); + } + //2012122601 + if ($result && $oldversion < 2012122601) { + $table = new xmldb_table('programming_languages'); + $field = new xmldb_field('langmode', XMLDB_TYPE_CHAR, '50', null, + null, null, null, 'headerext'); + + // add field langmode for programming_languages . + if (!$dbman->field_exists($table, $field)) { + $dbman->add_field($table, $field); + // Set the cutoffdate to the duedate if preventlatesubmissions was enabled. + $sql = "UPDATE {programming_languages} SET langmode = 'text/x-csrc' WHERE name = 'gcc-3.3'"; + $DB->execute($sql); + $sql = "UPDATE {programming_languages} SET langmode = 'text/x-c++src' WHERE name = 'g++-3.3'"; + $DB->execute($sql); + $sql = "UPDATE {programming_languages} SET langmode = 'text/x-java' WHERE name = 'java-1.5'"; + $DB->execute($sql); + $sql = "UPDATE {programming_languages} SET langmode = 'text/x-java' WHERE name = 'java-1.6'"; + $DB->execute($sql); + $sql = "UPDATE {programming_languages} SET langmode = 'text/x-pascal' WHERE name = 'fpc-2.2'"; + $DB->execute($sql); + $sql = "UPDATE {programming_languages} SET langmode = 'text/x-python' WHERE name = 'python-2.5'"; + $DB->execute($sql); + $sql = "UPDATE {programming_languages} SET langmode = 'text/x-csharp' WHERE name = 'gmcs-2.0'"; + $DB->execute($sql); + $sql = "UPDATE {programming_languages} SET langmode = 'text/x-sh' WHERE name = 'bash-3'"; + $DB->execute($sql); + } + upgrade_mod_savepoint(true, 2012122601, 'programming'); + } + + + return $result; +} + +?> diff --git a/deletesubmit.php b/deletesubmit.php new file mode 100644 index 0000000..2ded2f2 --- /dev/null +++ b/deletesubmit.php @@ -0,0 +1,95 @@ +get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); +} + +if (!$programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); +} +$context = context_module::instance($cm->id); + +require_login($course->id, true, $cm); +require_capability('mod/programming:deleteothersubmit', $context); + +/// Print the page header +/// Print the page header +$PAGE->set_title($programming->name); +$PAGE->set_heading(format_string($course->fullname)); +$PAGE->requires->css('/mod/programming/styles.css'); +$PAGE->requires->css('/mod/programming/js/dp/SyntaxHighlighter.css'); +$PAGE->requires->js('/mod/programming/js/dp/shCore.js'); +$PAGE->requires->js('/mod/programming/js/dp/shBrushCSharp.js'); +echo $OUTPUT->header(); + +/// Print tabs +$renderer = $PAGE->get_renderer('mod_programming'); +$tabs = programming_navtab('history', null, $course, $programming, $cm); +echo $renderer->render_navtab($tabs); + + +/// Print the main part of the page +if ($confirm) { + foreach ($submitid as $sid) { + $submit = $DB->get_record('programming_submits', array('id' => $sid)); + if ($submit) + programming_delete_submit($submit); + } + + echo '
    '; + echo '

    ' . get_string('deleted') . '

    '; + echo '

    ' . get_string('continue') . '

    '; + echo '
    '; +} else { + echo ''; + echo '
    '; + echo '

    ' . get_string('deletesubmitconfirm', 'programming') . '

    '; + echo '
      '; + foreach ($submitid as $sid) { + $submit = $DB->get_record('programming_submits', array('id' => $sid)); + $tm = userdate($submit->timemodified); + $user = fullname($DB->get_record('user', array('id' => $submit->userid))); + echo "
    • $sid $user $tm
    • "; + } + echo '
    '; + echo '
    '; + foreach ($submitid as $sid) { + echo ""; + } + echo ""; + echo ""; + echo ''; + echo ""; + echo ' '; + echo ''; + + echo '
    '; + echo '
    '; +} + +/// Finish the page +$OUTPUT->footer($course); +?> diff --git a/history.php b/history.php new file mode 100644 index 0000000..1e27698 --- /dev/null +++ b/history.php @@ -0,0 +1,91 @@ + $id); + if ($userid) { + $params['userid'] = $userid; + } + if ($submitid) { + $params['submitid'] = $submitid; + } + $PAGE->set_url('/mod/programming/history.php', $params); + + if($a){ + if (! $cm = get_coursemodule_from_instance('programming', $a)) { + print_error('invalidcoursemodule'); + } + }else{ + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + require_capability('mod/programming:viewhistory', $context); + if ($userid != 0 && $userid != $USER->id) { + require_capability('mod/programming:viewotherprogram', $context); + } + + if (!$userid) $userid = $USER->id; + + $submits = $DB->get_records('programming_submits', array('programmingid' => $programming->id, 'userid' => $userid), 'id DESC'); + if ($programming->presetcode) { + if (is_array($submits)) { + foreach ($submits as $submit) { + $submit->code = programming_format_code($programming, $submit); + } + } + } + + +/// Print the page header + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + $PAGE->requires->css('/mod/programming/styles.css'); + $PAGE->requires->css('/mod/programming/js/dp/SyntaxHighlighter.css'); + $PAGE->requires->js('/mod/programming/js/dp/shCore.js'); + $PAGE->requires->js('/mod/programming/js/dp/shBrushCSharp.js'); + echo $OUTPUT->header(); + +/// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('history', null, $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + +/// Print page content + echo html_writer::tag('h2', $programming->name); + if ($USER->id != $userid) { + $u = $DB->get_record('user', array('id' => $userid)); + echo html_writer::tag('h3', get_string('viewsubmithistoryof', 'programming', fullname($u))); + } else { + echo html_writer::tag('h3', get_string('viewsubmithistory', 'programming')); + } + + include_once('history.tpl.php'); + + $PAGE->requires->js_init_call('M.mod_programming.init_history'); + $PAGE->requires->js_init_call('M.mod_programming.init_fetch_code'); + +/// Finish the page + echo $OUTPUT->footer($course); + +?> diff --git a/history.tpl.php b/history.tpl.php new file mode 100644 index 0000000..eb56b9a --- /dev/null +++ b/history.tpl.php @@ -0,0 +1,45 @@ + + + + + + + +
    +
    + +
    + + + id == $submitid) + $currentsubmit = $submit; + ?> + + + + + + +
    + timemodified, '%Y-%m-%d %H:%M:%S'); ?> +
    + +
    +
    +
    +
    + +
    +
    + + + + + diff --git a/history_diff.php b/history_diff.php new file mode 100644 index 0000000..890984a --- /dev/null +++ b/history_diff.php @@ -0,0 +1,67 @@ +get_record('course', array('id' => $cm->course))) { + error('Course is misconfigured'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + error('Course module is incorrect'); + } + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + require_capability('mod/programming:viewhistory', $context); + + $submit1 = $DB->get_record('programming_submits', array('id' => $s1)); + $submit2 = $DB->get_record('programming_submits', array('id' => $s2)); + + if ($submit1->userid != $USER->id || $submit2->userid != $USER->id) { + require_capability('mod/programming:viewotherprogram', $context); + } + +/// Print the page header + $pagename = get_string('submithistory', 'programming'); + $CFG->scripts[] = '/mod/programming/js/dp/shCore.js'; + $CFG->scripts[] = '/mod/programming/js/dp/shBrushCSharp.js'; + $CFG->stylesheets[] = '/mod/programming/js/dp/SyntaxHighlighter.css'; + include_once('pageheader.php'); + +/// Print tabs + $currenttab = 'history'; + include_once('tabs.php'); + +/// Print page content + + ini_set("include_path", ".:./lib"); + require_once('Text/Diff.php'); + require_once('text_diff_render_html.php'); + + $lines1 = explode("\n", $submit1->code); + $lines2 = explode("\n", $submit2->code); + + $diff = new Text_Diff('auto', array($lines1, $lines2)); + + $renderer = new Text_Diff_Renderer_html(); + + echo '
    ';
    +    echo $renderer->render($diff);
    +    echo '
    '; + +/// Finish the page + $OUTPUT->footer($course); + +?> diff --git a/history_fetch_code.php b/history_fetch_code.php new file mode 100644 index 0000000..1997f15 --- /dev/null +++ b/history_fetch_code.php @@ -0,0 +1,31 @@ +get_record('programming_submits', array('id' => $submitid)); + if (! $programming = $DB->get_record('programming', array('id' => $submit->programmingid))) { + error('Course module is incorrect'); + } + if ($submit->userid != $USER->id) { + if (! $course = $DB->get_record('course', array('id' => $programming->course))) { + error('Course is misconfigured'); + } + if (! $cm = get_coursemodule_from_instance('programming', $programming->id, $course->id)) { + error('Course Module ID was incorrect'); + } + $context = context_module::instance($cm->id); + require_login($course->id); + if (!has_capability('mod/programming:viewotherprogram', $context)) { + $submit = null; + } + } + if ($programming->presetcode) { + $submit->code = programming_format_code($programming, $submit); + } + + if ($submit) { + echo str_replace("\r\n", "\r", $submit->code); + } +?> diff --git a/index.php b/index.php new file mode 100644 index 0000000..10037ac --- /dev/null +++ b/index.php @@ -0,0 +1,167 @@ +libdir.'/gradelib.php'); + + $id = required_param('id', PARAM_INT); // course + if (!$course = $DB->get_record('course', array('id'=>$id))) { + print_error('Course ID is incorrect'); + } + require_login($course); +/// Get all required strings + + $strprogrammings = get_string('modulenameplural', 'programming'); + $strprogramming = get_string('modulename', 'programming'); + + $PAGE->set_url('/mod/programming/index.php', array('id' => $id)); + $PAGE->set_title('programming'); + $PAGE->set_heading('programming heading'); + $PAGE->set_pagelayout('incourse'); + $PAGE->set_context(context_course::instance($id)); + $PAGE->navbar->add($strprogrammings); + + echo $OUTPUT->header(); + + + + +/* +/// Print the header + $title = ''; + include_once('pageheader.php'); + +//*/ + $currenttab = 'result'; + include_once('index_tabs.php'); + $table = new html_table(); +/// Get all the appropriate data + + if (! $programmings = get_all_instances_in_course('programming', $course)) { + notice('There are no programmings', '../../course/view.php?id='.$course->id); + die; + } + +/// Print the list of instances (your module will probably extend this) + + $timenow = time(); + $strname = get_string('name'); + $strweek = get_string('week'); + $strtopic = get_string('topic'); + $strlinecount = get_string('linecount', 'programming'); + $strtotal = get_string('total', 'programming'); + $strjudgeresult = get_string('judgeresult', 'programming'); + $strna = get_string('n/a', 'programming'); + $strglobalid = get_string('globalid', 'programming'); + $strsubmitcount = get_string('submitcount', 'programming'); + $strlanguage = get_string('language', 'programming'); + + $params = array($id, $USER->id); + $sql = "SELECT p.id, submitcount, + ps.id AS submitid, codelines, codesize, ps.timemodified, + ps.status AS status, pl.name AS lang + FROM {programming} AS p, + {programming_result} AS pr, + {programming_submits} AS ps, + {programming_languages} AS pl + WHERE p.course = ? + AND p.id = pr.programmingid + AND pr.userid= ? + AND pr.latestsubmitid=ps.id + AND ps.language=pl.id"; + $submits = $DB->get_records_sql($sql, $params); + + if (is_array($submits)) { + foreach($submits as $submit) { + if ($submit->status == PROGRAMMING_STATUS_COMPILEFAIL) { + $submit->judgeresult = get_string('CE', 'programming'); + } + else if ($submit->status == PROGRAMMING_STATUS_FINISH) { + $tr = $DB->get_records('programming_test_results', array('submitid'=>$submit->submitid)); + $submit->judgeresult = programming_contest_get_judgeresult($tr); + } + } + } else { + $submits = array(); + } + + if ($course->format == 'weeks') { + $table->head = array ($strweek); + $table->align = array ('CENTER'); + } else if ($course->format == 'topics') { + $table->head = array ($strtopic); + $table->align = array ('CENTER'); + } else if ($course->format == 'proglist') { + $table->head = array($strglobalid); + $table->align = array('CENTER'); + } else { + $table->head = array (); + $table->align = array (); + } + $table->head = array_merge($table->head, array($strname, $strjudgeresult, $strlanguage, $strlinecount, $strsubmitcount)); + $table->align = array_merge($table->align, array('LEFT', 'CENTER', 'CENTER', 'CENTER', 'CENTER')); + + $totallines = $totalsubmit = 0; + foreach ($programmings as $programming) { + $submit = null; + if (array_key_exists($programming->id, $submits)) { + $submit = $submits[$programming->id]; + } + + if ($submit) { + $totallines += $submit->codelines; + $totalsubmit += $submit->submitcount; + } + + $link = $resultlink = $countlink = $langlink = $codelink = ''; + if (!$programming->visible) { + //Show dimmed if the mod is hidden + $link = "coursemodule\">$programming->name"; + if ($submit) { + $resultlink = ''.$submit->judgeresult.''; + $countlink = ''.$submit->submitcount.''; + $langlink = ''.$submit->lang.''; + $codelink= ''.$submit->codelines.''; + } + } else { + //Show normal if the mod is visible + $link = "coursemodule\">$programming->name"; + if ($submit) { + $resultlink = ''.$submit->judgeresult.''; + $countlink = ''.$submit->submitcount.''; + $langlink = ''.$submit->lang.''; + $codelink= ''.$submit->codelines.''; + } + } + + if ($course->format == 'weeks' or $course->format == 'topics') { + $section = array($programming->section); + } else if ($course->format == 'proglist') { + $section = array($programming->globalid); + } else { + $section = array(); + } + if ($submit) { + $table->data[] = array_merge($section, array($link, $resultlink, $langlink, $codelink, $countlink)); + } else { + $table->data[] = array_merge($section, array($link, '', '', '', '')); + } + } + + if (in_array($course->format, array('weeks', 'topics', 'proglist'))) { + $table->data[] = array($strtotal, '', '', '', $totallines, $totalsubmit); + } else { + $table->data[] = array($strtotal, '', '', $totallines, $totalsubmit); + } + + echo '
    '; + echo '

    '.get_string('result', 'programming').'

    '; + echo html_writer::table($table); + echo '
    '; + echo $OUTPUT->footer(); + + +?> diff --git a/index_tabs.php b/index_tabs.php new file mode 100644 index 0000000..6cca715 --- /dev/null +++ b/index_tabs.php @@ -0,0 +1,40 @@ +wwwroot/mod/programming/index.php?id=$id", get_string('result','programming'), '', true); + $row[] = new tabobject('resemble', "$CFG->wwwroot/mod/programming/course/resemble.php?id=$id", get_string('resemble','programming'), '', true); + $tabs[] = $row; + + /***************************** + * stolen code from quiz report + *****************************/ + if ($currenttab == 'templates' and isset($mode)) { + $inactive[] = 'templates'; + $templatelist = array ('listtemplate', 'singletemplate', 'addtemplate', 'rsstemplate', 'csstemplate'); + + $row = array(); + $currenttab =''; + foreach ($templatelist as $template) { + $row[] = new tabobject($template, "templates.php?d=$data->id&mode=$template", + get_string($template, 'data')); + if ($template == $mode) { + $currenttab = $template; + } + } + $tabs[] = $row; + } + +/// Print out the tabs and continue! + + // if (!isguest()) { + print_tabs($tabs, $currenttab, $inactive); +// } + +?> diff --git a/js/Tests.html b/js/Tests.html new file mode 100644 index 0000000..71eb63f --- /dev/null +++ b/js/Tests.html @@ -0,0 +1,339 @@ + + + + dp.SyntaxHighlighter testing + + + + + + + + + +

    Smart Tabs & First Line

    + + + +

    C Sharp

    + + + +

    JavaScript

    + + + +

    Visual Basic

    + + + +

    XML / HTML

    + + + +

    PHP

    + + + +

    SQL

    + + + +

    Delphi

    + + + +

    Python

    + + + +

    Auto Overflow Test

    + +400px +
    + + + +
    + + + + + + + + + + + + + + + diff --git a/js/dp/SyntaxHighlighter.css b/js/dp/SyntaxHighlighter.css new file mode 100644 index 0000000..70387f1 --- /dev/null +++ b/js/dp/SyntaxHighlighter.css @@ -0,0 +1,184 @@ +.dp-highlighter +{ + font-family: "Consolas", "Courier New", Courier, mono, serif; + font-size: 1em; + background-color: #E7E5DC; + width: 99%; + margin: 18px 0 18px 0 !important; + padding-top: 1px; /* adds a little border on top when controls are hidden */ +} + +/* clear styles */ +.dp-highlighter ol, +.dp-highlighter ol li, +.dp-highlighter ol li span +{ + margin: 0; + padding: 0; + border: none; +} + +.dp-highlighter a, +.dp-highlighter a:hover +{ + background: none; + border: none; + padding: 0; + margin: 0; +} + +.dp-highlighter .bar +{ + padding-left: 45px; +} + +.dp-highlighter.collapsed .bar, +.dp-highlighter.nogutter .bar +{ + padding-left: 0px; +} + +.dp-highlighter ol +{ + list-style: decimal; /* for ie */ + background-color: #fff; + margin: 0px 0px 1px 45px !important; /* 1px bottom margin seems to fix occasional Firefox scrolling */ + padding: 0px; + color: #5C5C5C; +} + +.dp-highlighter.nogutter ol, +.dp-highlighter.nogutter ol li +{ + list-style: none !important; + margin-left: 0px !important; +} + +.dp-highlighter ol li, +.dp-highlighter .columns div +{ + list-style: decimal-leading-zero; /* better look for others, override cascade from OL */ + list-style-position: outside !important; + border-left: 3px solid #6CE26C; + background-color: #F8F8F8; + color: #5C5C5C; + padding: 0 3px 0 10px !important; + margin: 0 !important; + line-height: 14px; +} + +.dp-highlighter.nogutter ol li, +.dp-highlighter.nogutter .columns div +{ + border: 0; +} + +.dp-highlighter .columns +{ + background-color: #F8F8F8; + color: gray; + overflow: hidden; + width: 100%; +} + +.dp-highlighter .columns div +{ + padding-bottom: 5px; +} + +.dp-highlighter ol li.alt +{ + background-color: #FFF; + color: inherit; +} + +.dp-highlighter ol li span +{ + color: black; + background-color: inherit; +} + +/* Adjust some properties when collapsed */ + +.dp-highlighter.collapsed ol +{ + margin: 0px; +} + +.dp-highlighter.collapsed ol li +{ + display: none; +} + +/* Additional modifications when in print-view */ + +.dp-highlighter.printing +{ + border: none; +} + +.dp-highlighter.printing .tools +{ + display: none !important; +} + +.dp-highlighter.printing li +{ + display: list-item !important; +} + +/* Styles for the tools */ + +.dp-highlighter .tools +{ + padding: 3px 8px 3px 10px; + font: 0.9em Verdana, Geneva, Arial, Helvetica, sans-serif; + color: silver; + background-color: #f8f8f8; + padding-bottom: 10px; + border-left: 3px solid #6CE26C; +} + +.dp-highlighter.nogutter .tools +{ + border-left: 0; +} + +.dp-highlighter.collapsed .tools +{ + border-bottom: 0; +} + +.dp-highlighter .tools a +{ + font-size: 0.9em; + color: #a0a0a0; + background-color: inherit; + text-decoration: none; + margin-right: 10px; +} + +.dp-highlighter .tools a:hover +{ + color: red; + background-color: inherit; + text-decoration: underline; +} + +/* About dialog styles */ + +.dp-about { background-color: #fff; color: #333; margin: 0px; padding: 0px; } +.dp-about table { width: 100%; height: 100%; font-size: 0.9em; font-family: Tahoma, Verdana, Arial, sans-serif !important; } +.dp-about td { padding: 10px; vertical-align: top; } +.dp-about .copy { border-bottom: 1px solid #ACA899; height: 95%; } +.dp-about .title { color: red; background-color: inherit; font-weight: bold; } +.dp-about .para { margin: 0 0 4px 0; } +.dp-about .footer { background-color: #ECEADB; color: #333; border-top: 1px solid #fff; text-align: right; } +.dp-about .close { font-size: 0.9em; font-family: Tahoma, Verdana, Arial, sans-serif !important; background-color: #ECEADB; color: #333; width: 60px; height: 22px; } + +/* Language specific styles */ + +.dp-highlighter .comment, .dp-highlighter .comments { color: #008200; background-color: inherit; } +.dp-highlighter .string { color: blue; background-color: inherit; } +.dp-highlighter .keyword { color: #069; font-weight: bold; background-color: inherit; } +.dp-highlighter .preprocessor { color: gray; background-color: inherit; } diff --git a/js/dp/shBrushCSharp.js b/js/dp/shBrushCSharp.js new file mode 100644 index 0000000..b8beffb --- /dev/null +++ b/js/dp/shBrushCSharp.js @@ -0,0 +1,32 @@ +dp.sh.Brushes.CSharp = function() +{ + var keywords = 'abstract as base bool break byte case catch char checked class const ' + + 'continue decimal default delegate do double else enum event explicit ' + + 'extern false finally fixed float for foreach get goto if implicit in int ' + + 'interface internal is lock long namespace new null object operator out ' + + 'override params private protected public readonly ref return sbyte sealed set ' + + 'short sizeof stackalloc static string struct switch this throw true try ' + + 'typeof uint ulong unchecked unsafe ushort using virtual void while'; + + this.regexList = [ + // There's a slight problem with matching single line comments and figuring out + // a difference between // and ///. Using lookahead and lookbehind solves the + // problem, unfortunately JavaScript doesn't support lookbehind. So I'm at a + // loss how to translate that regular expression to JavaScript compatible one. +// { regex: new RegExp('(?) + | () + | (<)*(\w+)*\s*(\w+)\s*=\s*(".*?"|'.*?'|\w+)(/*>)* + | () + */ + var index = 0; + var match = null; + var regex = null; + + // Match CDATA in the following format + // (\<|<)\!\[[\w\s]*?\[(.|\s)*?\]\](\>|>) + this.GetMatches(new RegExp('(\<|<)\\!\\[[\\w\\s]*?\\[(.|\\s)*?\\]\\](\>|>)', 'gm'), 'cdata'); + + // Match comments + // (\<|<)!--\s*.*?\s*--(\>|>) + this.GetMatches(new RegExp('(\<|<)!--\\s*.*?\\s*--(\>|>)', 'gm'), 'comments'); + + // Match attributes and their values + // (:|\w+)\s*=\s*(".*?"|\'.*?\'|\w+)* + regex = new RegExp('([:\\w-\.]+)\\s*=\\s*(".*?"|\'.*?\'|\\w+)*|(\\w+)', 'gm'); // Thanks to Tomi Blinnikka of Yahoo! for fixing namespaces in attributes + while((match = regex.exec(this.code)) != null) + { + if(match[1] == null) + { + continue; + } + + push(this.matches, new dp.sh.Match(match[1], match.index, 'attribute')); + + // if xml is invalid and attribute has no property value, ignore it + if(match[2] != undefined) + { + push(this.matches, new dp.sh.Match(match[2], match.index + match[0].indexOf(match[2]), 'attribute-value')); + } + } + + // Match opening and closing tag brackets + // (\<|<)/*\?*(?!\!)|/*\?*(\>|>) + this.GetMatches(new RegExp('(\<|<)/*\\?*(?!\\!)|/*\\?*(\>|>)', 'gm'), 'tag'); + + // Match tag names + // (\<|<)/*\?*\s*(\w+) + regex = new RegExp('(?:\<|<)/*\\?*\\s*([:\\w-\.]+)', 'gm'); + while((match = regex.exec(this.code)) != null) + { + push(this.matches, new dp.sh.Match(match[1], match.index + match[0].indexOf(match[1]), 'tag-name')); + } +} diff --git a/js/dp/shCore.js b/js/dp/shCore.js new file mode 100644 index 0000000..2571084 --- /dev/null +++ b/js/dp/shCore.js @@ -0,0 +1,705 @@ +/** + * Code Syntax Highlighter. + * Version 1.5.1 + * Copyright (C) 2004-2007 Alex Gorbatchev. + * http://www.dreamprojections.com/syntaxhighlighter/ + * + * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + * + * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to + * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +// +// create namespaces +// +var dp = { + sh : + { + Toolbar : {}, + Utils : {}, + RegexLib: {}, + Brushes : {}, + Strings : { + AboutDialog : 'About...

    dp.SyntaxHighlighter

    Version: {V}

    http://www.dreamprojections.com/syntaxhighlighter

    ©2004-2007 Alex Gorbatchev.
    ' + }, + ClipboardSwf : null, + Version : '1.5.1' + } +}; + +// make an alias +dp.SyntaxHighlighter = dp.sh; + +// +// Toolbar functions +// + +dp.sh.Toolbar.Commands = { + ExpandSource: { + label: '+ expand source', + check: function(highlighter) { return highlighter.collapse; }, + func: function(sender, highlighter) + { + sender.parentNode.removeChild(sender); + highlighter.div.className = highlighter.div.className.replace('collapsed', ''); + } + }, + + // opens a new windows and puts the original unformatted source code inside. + ViewSource: { + label: 'view plain', + func: function(sender, highlighter) + { + var code = dp.sh.Utils.FixForBlogger(highlighter.originalCode).replace(/' + code + ''); + wnd.document.close(); + } + }, + + // Copies the original source code in to the clipboard. Uses either IE only method or Flash object if ClipboardSwf is set + CopyToClipboard: { + label: 'copy to clipboard', + check: function() { return window.clipboardData != null || dp.sh.ClipboardSwf != null; }, + func: function(sender, highlighter) + { + var code = dp.sh.Utils.FixForBlogger(highlighter.originalCode) + .replace(/</g,'<') + .replace(/>/g,'>') + .replace(/&/g,'&') + ; + + if(window.clipboardData) + { + window.clipboardData.setData('text', code); + } + else if(dp.sh.ClipboardSwf != null) + { + var flashcopier = highlighter.flashCopier; + + if(flashcopier == null) + { + flashcopier = document.createElement('div'); + highlighter.flashCopier = flashcopier; + highlighter.div.appendChild(flashcopier); + } + + flashcopier.innerHTML = ''; + } + + alert('The code is in your clipboard now'); + } + }, + + // creates an invisible iframe, puts the original source code inside and prints it + PrintSource: { + label: 'print', + func: function(sender, highlighter) + { + var iframe = document.createElement('IFRAME'); + var doc = null; + + // this hides the iframe + iframe.style.cssText = 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;'; + + document.body.appendChild(iframe); + doc = iframe.contentWindow.document; + + dp.sh.Utils.CopyStyles(doc, window.document); + doc.write('
    ' + highlighter.div.innerHTML + '
    '); + doc.close(); + + iframe.contentWindow.focus(); + iframe.contentWindow.print(); + + alert('Printing...'); + + document.body.removeChild(iframe); + } + }, + + About: { + label: '?', + func: function(highlighter) + { + var wnd = window.open('', '_blank', 'dialog,width=350,height=200,scrollbars=0'); + var doc = wnd.document; + + dp.sh.Utils.CopyStyles(doc, window.document); + + doc.write(dp.sh.Strings.AboutDialog.replace('{V}', dp.sh.Version)); + doc.close(); + wnd.focus(); + } + } +}; + +// creates a
    with all toolbar links +dp.sh.Toolbar.Create = function(highlighter) +{ + var div = document.createElement('DIV'); + + div.className = 'tools'; + + for(var name in dp.sh.Toolbar.Commands) + { + var cmd = dp.sh.Toolbar.Commands[name]; + + if(cmd.check != null && !cmd.check(highlighter)) + continue; + + div.innerHTML += '' + cmd.label + ''; + } + + return div; +} + +// executes toolbar command by name +dp.sh.Toolbar.Command = function(name, sender) +{ + var n = sender; + + while(n != null && n.className.indexOf('dp-highlighter') == -1) + n = n.parentNode; + + if(n != null) + dp.sh.Toolbar.Commands[name].func(sender, n.highlighter); +} + +// copies all from 'target' window to 'dest' +dp.sh.Utils.CopyStyles = function(destDoc, sourceDoc) +{ + var links = sourceDoc.getElementsByTagName('link'); + + for(var i = 0; i < links.length; i++) + if(links[i].rel.toLowerCase() == 'stylesheet') + destDoc.write(''); +} + +dp.sh.Utils.FixForBlogger = function(str) +{ + return (dp.sh.isBloggerMode == true) ? str.replace(/|<br\s*\/?>/gi, '\n') : str; +} + +// +// Common reusable regular expressions +// +dp.sh.RegexLib = { + MultiLineCComments : new RegExp('/\\*[\\s\\S]*?\\*/', 'gm'), + SingleLineCComments : new RegExp('//.*$', 'gm'), + SingleLinePerlComments : new RegExp('#.*$', 'gm'), + DoubleQuotedString : new RegExp('"(?:\\.|(\\\\\\")|[^\\""\\n])*"','g'), + SingleQuotedString : new RegExp("'(?:\\.|(\\\\\\')|[^\\''\\n])*'", 'g') +}; + +// +// Match object +// +dp.sh.Match = function(value, index, css) +{ + this.value = value; + this.index = index; + this.length = value.length; + this.css = css; +} + +// +// Highlighter object +// +dp.sh.Highlighter = function() +{ + this.noGutter = false; + this.addControls = true; + this.collapse = false; + this.tabsToSpaces = true; + this.wrapColumn = 80; + this.showColumns = true; +} + +// static callback for the match sorting +dp.sh.Highlighter.SortCallback = function(m1, m2) +{ + // sort matches by index first + if(m1.index < m2.index) + return -1; + else if(m1.index > m2.index) + return 1; + else + { + // if index is the same, sort by length + if(m1.length < m2.length) + return -1; + else if(m1.length > m2.length) + return 1; + } + return 0; +} + +dp.sh.Highlighter.prototype.CreateElement = function(name) +{ + var result = document.createElement(name); + result.highlighter = this; + return result; +} + +// gets a list of all matches for a given regular expression +dp.sh.Highlighter.prototype.GetMatches = function(regex, css) +{ + var index = 0; + var match = null; + + while((match = regex.exec(this.code)) != null) + this.matches[this.matches.length] = new dp.sh.Match(match[0], match.index, css); +} + +dp.sh.Highlighter.prototype.AddBit = function(str, css) +{ + if(str == null || str.length == 0) + return; + + var span = this.CreateElement('SPAN'); + +// str = str.replace(/&/g, '&'); + str = str.replace(/ /g, ' '); + str = str.replace(//g, '>'); + str = str.replace(/\n/gm, ' 
    '); + + // when adding a piece of code, check to see if it has line breaks in it + // and if it does, wrap individual line breaks with span tags + if(css != null) + { + if((/br/gi).test(str)) + { + var lines = str.split(' 
    '); + + for(var i = 0; i < lines.length; i++) + { + span = this.CreateElement('SPAN'); + span.className = css; + span.innerHTML = lines[i]; + + this.div.appendChild(span); + + // don't add a
    for the last line + if(i + 1 < lines.length) + this.div.appendChild(this.CreateElement('BR')); + } + } + else + { + span.className = css; + span.innerHTML = str; + this.div.appendChild(span); + } + } + else + { + span.innerHTML = str; + this.div.appendChild(span); + } +} + +// checks if one match is inside any other match +dp.sh.Highlighter.prototype.IsInside = function(match) +{ + if(match == null || match.length == 0) + return false; + + for(var i = 0; i < this.matches.length; i++) + { + var c = this.matches[i]; + + if(c == null) + continue; + + if((match.index > c.index) && (match.index < c.index + c.length)) + return true; + } + + return false; +} + +dp.sh.Highlighter.prototype.ProcessRegexList = function() +{ + for(var i = 0; i < this.regexList.length; i++) + this.GetMatches(this.regexList[i].regex, this.regexList[i].css); +} + +dp.sh.Highlighter.prototype.ProcessSmartTabs = function(code) +{ + var lines = code.split('\n'); + var result = ''; + var tabSize = 4; + var tab = '\t'; + + // This function inserts specified amount of spaces in the string + // where a tab is while removing that given tab. + function InsertSpaces(line, pos, count) + { + var left = line.substr(0, pos); + var right = line.substr(pos + 1, line.length); // pos + 1 will get rid of the tab + var spaces = ''; + + for(var i = 0; i < count; i++) + spaces += ' '; + + return left + spaces + right; + } + + // This function process one line for 'smart tabs' + function ProcessLine(line, tabSize) + { + if(line.indexOf(tab) == -1) + return line; + + var pos = 0; + + while((pos = line.indexOf(tab)) != -1) + { + // This is pretty much all there is to the 'smart tabs' logic. + // Based on the position within the line and size of a tab, + // calculate the amount of spaces we need to insert. + var spaces = tabSize - pos % tabSize; + + line = InsertSpaces(line, pos, spaces); + } + + return line; + } + + // Go through all the lines and do the 'smart tabs' magic. + for(var i = 0; i < lines.length; i++) + result += ProcessLine(lines[i], tabSize) + '\n'; + + return result; +} + +dp.sh.Highlighter.prototype.SwitchToList = function() +{ + // thanks to Lachlan Donald from SitePoint.com for this
    tag fix. + var html = this.div.innerHTML.replace(/<(br)\/?>/gi, '\n'); + var lines = html.split('\n'); + + if(this.addControls == true) + this.bar.appendChild(dp.sh.Toolbar.Create(this)); + + // add columns ruler + if(this.showColumns) + { + var div = this.CreateElement('div'); + var columns = this.CreateElement('div'); + var showEvery = 10; + var i = 1; + + while(i <= 150) + { + if(i % showEvery == 0) + { + div.innerHTML += i; + i += (i + '').length; + } + else + { + div.innerHTML += '·'; + i++; + } + } + + columns.className = 'columns'; + columns.appendChild(div); + this.bar.appendChild(columns); + } + + for(var i = 0, lineIndex = this.firstLine; i < lines.length - 1; i++, lineIndex++) + { + var li = this.CreateElement('LI'); + var span = this.CreateElement('SPAN'); + + // uses .line1 and .line2 css styles for alternating lines + li.className = (i % 2 == 0) ? 'alt' : ''; + span.innerHTML = lines[i] + ' '; + + li.appendChild(span); + this.ol.appendChild(li); + } + + this.div.innerHTML = ''; +} + +dp.sh.Highlighter.prototype.Highlight = function(code) +{ + function Trim(str) + { + return str.replace(/^\s*(.*?)[\s\n]*$/g, '$1'); + } + + function Chop(str) + { + return str.replace(/\n*$/, '').replace(/^\n*/, ''); + } + + function Unindent(str) + { + var lines = dp.sh.Utils.FixForBlogger(str).split('\n'); + var indents = new Array(); + var regex = new RegExp('^\\s*', 'g'); + var min = 1000; + + // go through every line and check for common number of indents + for(var i = 0; i < lines.length && min > 0; i++) + { + if(Trim(lines[i]).length == 0) + continue; + + var matches = regex.exec(lines[i]); + + if(matches != null && matches.length > 0) + min = Math.min(matches[0].length, min); + } + + // trim minimum common number of white space from the begining of every line + if(min > 0) + for(var i = 0; i < lines.length; i++) + lines[i] = lines[i].substr(min); + + return lines.join('\n'); + } + + // This function returns a portions of the string from pos1 to pos2 inclusive + function Copy(string, pos1, pos2) + { + return string.substr(pos1, pos2 - pos1); + } + + var pos = 0; + + if(code == null) + code = ''; + + this.originalCode = code; + this.code = Chop(Unindent(code)); + this.div = this.CreateElement('DIV'); + this.bar = this.CreateElement('DIV'); + this.ol = this.CreateElement('OL'); + this.matches = new Array(); + + this.div.className = 'dp-highlighter'; + this.div.highlighter = this; + + this.bar.className = 'bar'; + + // set the first line + this.ol.start = this.firstLine; + + if(this.CssClass != null) + this.ol.className = this.CssClass; + + if(this.collapse) + this.div.className += ' collapsed'; + + if(this.noGutter) + this.div.className += ' nogutter'; + + // replace tabs with spaces + if(this.tabsToSpaces == true) + this.code = this.ProcessSmartTabs(this.code); + + this.ProcessRegexList(); + + // if no matches found, add entire code as plain text + if(this.matches.length == 0) + { + this.AddBit(this.code, null); + this.SwitchToList(); + this.div.appendChild(this.bar); + this.div.appendChild(this.ol); + return; + } + + // sort the matches + this.matches = this.matches.sort(dp.sh.Highlighter.SortCallback); + + // The following loop checks to see if any of the matches are inside + // of other matches. This process would get rid of highligted strings + // inside comments, keywords inside strings and so on. + for(var i = 0; i < this.matches.length; i++) + if(this.IsInside(this.matches[i])) + this.matches[i] = null; + + // Finally, go through the final list of matches and pull the all + // together adding everything in between that isn't a match. + for(var i = 0; i < this.matches.length; i++) + { + var match = this.matches[i]; + + if(match == null || match.length == 0) + continue; + + this.AddBit(Copy(this.code, pos, match.index), null); + this.AddBit(match.value, match.css); + + pos = match.index + match.length; + } + + this.AddBit(this.code.substr(pos), null); + + this.SwitchToList(); + this.div.appendChild(this.bar); + this.div.appendChild(this.ol); +} + +dp.sh.Highlighter.prototype.GetKeywords = function(str) +{ + return '\\b' + str.replace(/ /g, '\\b|\\b') + '\\b'; +} + +dp.sh.BloggerMode = function() +{ + dp.sh.isBloggerMode = true; +} + +// highlightes all elements identified by name and gets source code from specified property +dp.sh.HighlightAll = function(name, showGutter /* optional */, showControls /* optional */, collapseAll /* optional */, firstLine /* optional */, showColumns /* optional */) +{ + function FindValue() + { + var a = arguments; + + for(var i = 0; i < a.length; i++) + { + if(a[i] == null) + continue; + + if(typeof(a[i]) == 'string' && a[i] != '') + return a[i] + ''; + + if(typeof(a[i]) == 'object' && a[i].value != '') + return a[i].value + ''; + } + + return null; + } + + function IsOptionSet(value, list) + { + for(var i = 0; i < list.length; i++) + if(list[i] == value) + return true; + + return false; + } + + function GetOptionValue(name, list, defaultValue) + { + var regex = new RegExp('^' + name + '\\[(\\w+)\\]$', 'gi'); + var matches = null; + + for(var i = 0; i < list.length; i++) + if((matches = regex.exec(list[i])) != null) + return matches[1]; + + return defaultValue; + } + + function FindTagsByName(list, name, tagName) + { + var tags = document.getElementsByTagName(tagName); + + for(var i = 0; i < tags.length; i++) + if(tags[i].getAttribute('name') == name) + list.push(tags[i]); + } + + var elements = []; + var highlighter = null; + var registered = {}; + var propertyName = 'innerHTML'; + + // for some reason IE doesn't find
     by name, however it does see them just fine by tag name... 
    +	FindTagsByName(elements, name, 'pre');
    +	FindTagsByName(elements, name, 'textarea');
    +
    +	if(elements.length == 0)
    +		return;
    +
    +	// register all brushes
    +	for(var brush in dp.sh.Brushes)
    +	{
    +		var aliases = dp.sh.Brushes[brush].Aliases;
    +
    +		if(aliases == null)
    +			continue;
    +		
    +		for(var i = 0; i < aliases.length; i++)
    +			registered[aliases[i]] = brush;
    +	}
    +
    +	for(var i = 0; i < elements.length; i++)
    +	{
    +		var element = elements[i];
    +		var options = FindValue(
    +				element.attributes['class'], element.className, 
    +				element.attributes['language'], element.language
    +				);
    +		var language = '';
    +		
    +		if(options == null)
    +			continue;
    +		
    +		options = options.split(':');
    +		
    +		language = options[0].toLowerCase();
    +
    +		if(registered[language] == null)
    +			continue;
    +		
    +		// instantiate a brush
    +		highlighter = new dp.sh.Brushes[registered[language]]();
    +		
    +		// hide the original element
    +		element.style.display = 'none';
    +
    +		highlighter.noGutter = (showGutter == null) ? IsOptionSet('nogutter', options) : !showGutter;
    +		highlighter.addControls = (showControls == null) ? !IsOptionSet('nocontrols', options) : showControls;
    +		highlighter.collapse = (collapseAll == null) ? IsOptionSet('collapse', options) : collapseAll;
    +		highlighter.showColumns = (showColumns == null) ? IsOptionSet('showcolumns', options) : showColumns;
    +
    +		// write out custom brush style
    +		var headNode = document.getElementsByTagName('head')[0];
    +		if(highlighter.Style && headNode)
    +		{
    +			var styleNode = document.createElement('style');
    +			styleNode.setAttribute('type', 'text/css');
    +
    +			if(styleNode.styleSheet) // for IE
    +			{
    +				styleNode.styleSheet.cssText = highlighter.Style;
    +			}
    +			else // for everyone else
    +			{
    +				var textNode = document.createTextNode(highlighter.Style);
    +				styleNode.appendChild(textNode);
    +			}
    +
    +			headNode.appendChild(styleNode);
    +		}
    +		
    +		// first line idea comes from Andrew Collington, thanks!
    +		highlighter.firstLine = (firstLine == null) ? parseInt(GetOptionValue('firstline', options, 1)) : firstLine;
    +
    +		highlighter.Highlight(element[propertyName]);
    +		
    +		highlighter.source = element;
    +
    +		element.parentNode.insertBefore(highlighter.div, element);
    +	}	
    +}
    diff --git a/js/jquery-1.3.1.js b/js/jquery-1.3.1.js
    new file mode 100644
    index 0000000..3a4badd
    --- /dev/null
    +++ b/js/jquery-1.3.1.js
    @@ -0,0 +1,4241 @@
    +/*!
    + * jQuery JavaScript Library v1.3.1
    + * http://jquery.com/
    + *
    + * Copyright (c) 2009 John Resig
    + * Dual licensed under the MIT and GPL licenses.
    + * http://docs.jquery.com/License
    + *
    + * Date: 2009-01-21 20:42:16 -0500 (Wed, 21 Jan 2009)
    + * Revision: 6158
    + */
    +(function(){
    +
    +var 
    +	// Will speed up references to window, and allows munging its name.
    +	window = this,
    +	// Will speed up references to undefined, and allows munging its name.
    +	undefined,
    +	// Map over jQuery in case of overwrite
    +	_jQuery = window.jQuery,
    +	// Map over the $ in case of overwrite
    +	_$ = window.$,
    +
    +	jQuery = window.jQuery = window.$ = function( selector, context ) {
    +		// The jQuery object is actually just the init constructor 'enhanced'
    +		return new jQuery.fn.init( selector, context );
    +	},
    +
    +	// A simple way to check for HTML strings or ID strings
    +	// (both of which we optimize for)
    +	quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
    +	// Is it a simple selector
    +	isSimple = /^.[^:#\[\.,]*$/;
    +
    +jQuery.fn = jQuery.prototype = {
    +	init: function( selector, context ) {
    +		// Make sure that a selection was provided
    +		selector = selector || document;
    +
    +		// Handle $(DOMElement)
    +		if ( selector.nodeType ) {
    +			this[0] = selector;
    +			this.length = 1;
    +			this.context = selector;
    +			return this;
    +		}
    +		// Handle HTML strings
    +		if ( typeof selector === "string" ) {
    +			// Are we dealing with HTML string or an ID?
    +			var match = quickExpr.exec( selector );
    +
    +			// Verify a match, and that no context was specified for #id
    +			if ( match && (match[1] || !context) ) {
    +
    +				// HANDLE: $(html) -> $(array)
    +				if ( match[1] )
    +					selector = jQuery.clean( [ match[1] ], context );
    +
    +				// HANDLE: $("#id")
    +				else {
    +					var elem = document.getElementById( match[3] );
    +
    +					// Handle the case where IE and Opera return items
    +					// by name instead of ID
    +					if ( elem && elem.id != match[3] )
    +						return jQuery().find( selector );
    +
    +					// Otherwise, we inject the element directly into the jQuery object
    +					var ret = jQuery( elem || [] );
    +					ret.context = document;
    +					ret.selector = selector;
    +					return ret;
    +				}
    +
    +			// HANDLE: $(expr, [context])
    +			// (which is just equivalent to: $(content).find(expr)
    +			} else
    +				return jQuery( context ).find( selector );
    +
    +		// HANDLE: $(function)
    +		// Shortcut for document ready
    +		} else if ( jQuery.isFunction( selector ) )
    +			return jQuery( document ).ready( selector );
    +
    +		// Make sure that old selector state is passed along
    +		if ( selector.selector && selector.context ) {
    +			this.selector = selector.selector;
    +			this.context = selector.context;
    +		}
    +
    +		return this.setArray(jQuery.makeArray(selector));
    +	},
    +
    +	// Start with an empty selector
    +	selector: "",
    +
    +	// The current version of jQuery being used
    +	jquery: "1.3.1",
    +
    +	// The number of elements contained in the matched element set
    +	size: function() {
    +		return this.length;
    +	},
    +
    +	// Get the Nth element in the matched element set OR
    +	// Get the whole matched element set as a clean array
    +	get: function( num ) {
    +		return num === undefined ?
    +
    +			// Return a 'clean' array
    +			jQuery.makeArray( this ) :
    +
    +			// Return just the object
    +			this[ num ];
    +	},
    +
    +	// Take an array of elements and push it onto the stack
    +	// (returning the new matched element set)
    +	pushStack: function( elems, name, selector ) {
    +		// Build a new jQuery matched element set
    +		var ret = jQuery( elems );
    +
    +		// Add the old object onto the stack (as a reference)
    +		ret.prevObject = this;
    +
    +		ret.context = this.context;
    +
    +		if ( name === "find" )
    +			ret.selector = this.selector + (this.selector ? " " : "") + selector;
    +		else if ( name )
    +			ret.selector = this.selector + "." + name + "(" + selector + ")";
    +
    +		// Return the newly-formed element set
    +		return ret;
    +	},
    +
    +	// Force the current matched set of elements to become
    +	// the specified array of elements (destroying the stack in the process)
    +	// You should use pushStack() in order to do this, but maintain the stack
    +	setArray: function( elems ) {
    +		// Resetting the length to 0, then using the native Array push
    +		// is a super-fast way to populate an object with array-like properties
    +		this.length = 0;
    +		Array.prototype.push.apply( this, elems );
    +
    +		return this;
    +	},
    +
    +	// Execute a callback for every element in the matched set.
    +	// (You can seed the arguments with an array of args, but this is
    +	// only used internally.)
    +	each: function( callback, args ) {
    +		return jQuery.each( this, callback, args );
    +	},
    +
    +	// Determine the position of an element within
    +	// the matched set of elements
    +	index: function( elem ) {
    +		// Locate the position of the desired element
    +		return jQuery.inArray(
    +			// If it receives a jQuery object, the first element is used
    +			elem && elem.jquery ? elem[0] : elem
    +		, this );
    +	},
    +
    +	attr: function( name, value, type ) {
    +		var options = name;
    +
    +		// Look for the case where we're accessing a style value
    +		if ( typeof name === "string" )
    +			if ( value === undefined )
    +				return this[0] && jQuery[ type || "attr" ]( this[0], name );
    +
    +			else {
    +				options = {};
    +				options[ name ] = value;
    +			}
    +
    +		// Check to see if we're setting style values
    +		return this.each(function(i){
    +			// Set all the styles
    +			for ( name in options )
    +				jQuery.attr(
    +					type ?
    +						this.style :
    +						this,
    +					name, jQuery.prop( this, options[ name ], type, i, name )
    +				);
    +		});
    +	},
    +
    +	css: function( key, value ) {
    +		// ignore negative width and height values
    +		if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
    +			value = undefined;
    +		return this.attr( key, value, "curCSS" );
    +	},
    +
    +	text: function( text ) {
    +		if ( typeof text !== "object" && text != null )
    +			return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
    +
    +		var ret = "";
    +
    +		jQuery.each( text || this, function(){
    +			jQuery.each( this.childNodes, function(){
    +				if ( this.nodeType != 8 )
    +					ret += this.nodeType != 1 ?
    +						this.nodeValue :
    +						jQuery.fn.text( [ this ] );
    +			});
    +		});
    +
    +		return ret;
    +	},
    +
    +	wrapAll: function( html ) {
    +		if ( this[0] ) {
    +			// The elements to wrap the target around
    +			var wrap = jQuery( html, this[0].ownerDocument ).clone();
    +
    +			if ( this[0].parentNode )
    +				wrap.insertBefore( this[0] );
    +
    +			wrap.map(function(){
    +				var elem = this;
    +
    +				while ( elem.firstChild )
    +					elem = elem.firstChild;
    +
    +				return elem;
    +			}).append(this);
    +		}
    +
    +		return this;
    +	},
    +
    +	wrapInner: function( html ) {
    +		return this.each(function(){
    +			jQuery( this ).contents().wrapAll( html );
    +		});
    +	},
    +
    +	wrap: function( html ) {
    +		return this.each(function(){
    +			jQuery( this ).wrapAll( html );
    +		});
    +	},
    +
    +	append: function() {
    +		return this.domManip(arguments, true, function(elem){
    +			if (this.nodeType == 1)
    +				this.appendChild( elem );
    +		});
    +	},
    +
    +	prepend: function() {
    +		return this.domManip(arguments, true, function(elem){
    +			if (this.nodeType == 1)
    +				this.insertBefore( elem, this.firstChild );
    +		});
    +	},
    +
    +	before: function() {
    +		return this.domManip(arguments, false, function(elem){
    +			this.parentNode.insertBefore( elem, this );
    +		});
    +	},
    +
    +	after: function() {
    +		return this.domManip(arguments, false, function(elem){
    +			this.parentNode.insertBefore( elem, this.nextSibling );
    +		});
    +	},
    +
    +	end: function() {
    +		return this.prevObject || jQuery( [] );
    +	},
    +
    +	// For internal use only.
    +	// Behaves like an Array's .push method, not like a jQuery method.
    +	push: [].push,
    +
    +	find: function( selector ) {
    +		if ( this.length === 1 && !/,/.test(selector) ) {
    +			var ret = this.pushStack( [], "find", selector );
    +			ret.length = 0;
    +			jQuery.find( selector, this[0], ret );
    +			return ret;
    +		} else {
    +			var elems = jQuery.map(this, function(elem){
    +				return jQuery.find( selector, elem );
    +			});
    +
    +			return this.pushStack( /[^+>] [^+>]/.test( selector ) ?
    +				jQuery.unique( elems ) :
    +				elems, "find", selector );
    +		}
    +	},
    +
    +	clone: function( events ) {
    +		// Do the clone
    +		var ret = this.map(function(){
    +			if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
    +				// IE copies events bound via attachEvent when
    +				// using cloneNode. Calling detachEvent on the
    +				// clone will also remove the events from the orignal
    +				// In order to get around this, we use innerHTML.
    +				// Unfortunately, this means some modifications to
    +				// attributes in IE that are actually only stored
    +				// as properties will not be copied (such as the
    +				// the name attribute on an input).
    +				var clone = this.cloneNode(true),
    +					container = document.createElement("div");
    +				container.appendChild(clone);
    +				return jQuery.clean([container.innerHTML])[0];
    +			} else
    +				return this.cloneNode(true);
    +		});
    +
    +		// Need to set the expando to null on the cloned set if it exists
    +		// removeData doesn't work here, IE removes it from the original as well
    +		// this is primarily for IE but the data expando shouldn't be copied over in any browser
    +		var clone = ret.find("*").andSelf().each(function(){
    +			if ( this[ expando ] !== undefined )
    +				this[ expando ] = null;
    +		});
    +
    +		// Copy the events from the original to the clone
    +		if ( events === true )
    +			this.find("*").andSelf().each(function(i){
    +				if (this.nodeType == 3)
    +					return;
    +				var events = jQuery.data( this, "events" );
    +
    +				for ( var type in events )
    +					for ( var handler in events[ type ] )
    +						jQuery.event.add( clone[ i ], type, events[ type ][ handler ], events[ type ][ handler ].data );
    +			});
    +
    +		// Return the cloned set
    +		return ret;
    +	},
    +
    +	filter: function( selector ) {
    +		return this.pushStack(
    +			jQuery.isFunction( selector ) &&
    +			jQuery.grep(this, function(elem, i){
    +				return selector.call( elem, i );
    +			}) ||
    +
    +			jQuery.multiFilter( selector, jQuery.grep(this, function(elem){
    +				return elem.nodeType === 1;
    +			}) ), "filter", selector );
    +	},
    +
    +	closest: function( selector ) {
    +		var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null;
    +
    +		return this.map(function(){
    +			var cur = this;
    +			while ( cur && cur.ownerDocument ) {
    +				if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) )
    +					return cur;
    +				cur = cur.parentNode;
    +			}
    +		});
    +	},
    +
    +	not: function( selector ) {
    +		if ( typeof selector === "string" )
    +			// test special case where just one selector is passed in
    +			if ( isSimple.test( selector ) )
    +				return this.pushStack( jQuery.multiFilter( selector, this, true ), "not", selector );
    +			else
    +				selector = jQuery.multiFilter( selector, this );
    +
    +		var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
    +		return this.filter(function() {
    +			return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector;
    +		});
    +	},
    +
    +	add: function( selector ) {
    +		return this.pushStack( jQuery.unique( jQuery.merge(
    +			this.get(),
    +			typeof selector === "string" ?
    +				jQuery( selector ) :
    +				jQuery.makeArray( selector )
    +		)));
    +	},
    +
    +	is: function( selector ) {
    +		return !!selector && jQuery.multiFilter( selector, this ).length > 0;
    +	},
    +
    +	hasClass: function( selector ) {
    +		return !!selector && this.is( "." + selector );
    +	},
    +
    +	val: function( value ) {
    +		if ( value === undefined ) {			
    +			var elem = this[0];
    +
    +			if ( elem ) {
    +				if( jQuery.nodeName( elem, 'option' ) )
    +					return (elem.attributes.value || {}).specified ? elem.value : elem.text;
    +				
    +				// We need to handle select boxes special
    +				if ( jQuery.nodeName( elem, "select" ) ) {
    +					var index = elem.selectedIndex,
    +						values = [],
    +						options = elem.options,
    +						one = elem.type == "select-one";
    +
    +					// Nothing was selected
    +					if ( index < 0 )
    +						return null;
    +
    +					// Loop through all the selected options
    +					for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
    +						var option = options[ i ];
    +
    +						if ( option.selected ) {
    +							// Get the specifc value for the option
    +							value = jQuery(option).val();
    +
    +							// We don't need an array for one selects
    +							if ( one )
    +								return value;
    +
    +							// Multi-Selects return an array
    +							values.push( value );
    +						}
    +					}
    +
    +					return values;				
    +				}
    +
    +				// Everything else, we just grab the value
    +				return (elem.value || "").replace(/\r/g, "");
    +
    +			}
    +
    +			return undefined;
    +		}
    +
    +		if ( typeof value === "number" )
    +			value += '';
    +
    +		return this.each(function(){
    +			if ( this.nodeType != 1 )
    +				return;
    +
    +			if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) )
    +				this.checked = (jQuery.inArray(this.value, value) >= 0 ||
    +					jQuery.inArray(this.name, value) >= 0);
    +
    +			else if ( jQuery.nodeName( this, "select" ) ) {
    +				var values = jQuery.makeArray(value);
    +
    +				jQuery( "option", this ).each(function(){
    +					this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
    +						jQuery.inArray( this.text, values ) >= 0);
    +				});
    +
    +				if ( !values.length )
    +					this.selectedIndex = -1;
    +
    +			} else
    +				this.value = value;
    +		});
    +	},
    +
    +	html: function( value ) {
    +		return value === undefined ?
    +			(this[0] ?
    +				this[0].innerHTML :
    +				null) :
    +			this.empty().append( value );
    +	},
    +
    +	replaceWith: function( value ) {
    +		return this.after( value ).remove();
    +	},
    +
    +	eq: function( i ) {
    +		return this.slice( i, +i + 1 );
    +	},
    +
    +	slice: function() {
    +		return this.pushStack( Array.prototype.slice.apply( this, arguments ),
    +			"slice", Array.prototype.slice.call(arguments).join(",") );
    +	},
    +
    +	map: function( callback ) {
    +		return this.pushStack( jQuery.map(this, function(elem, i){
    +			return callback.call( elem, i, elem );
    +		}));
    +	},
    +
    +	andSelf: function() {
    +		return this.add( this.prevObject );
    +	},
    +
    +	domManip: function( args, table, callback ) {
    +		if ( this[0] ) {
    +			var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(),
    +				scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ),
    +				first = fragment.firstChild,
    +				extra = this.length > 1 ? fragment.cloneNode(true) : fragment;
    +
    +			if ( first )
    +				for ( var i = 0, l = this.length; i < l; i++ )
    +					callback.call( root(this[i], first), i > 0 ? extra.cloneNode(true) : fragment );
    +			
    +			if ( scripts )
    +				jQuery.each( scripts, evalScript );
    +		}
    +
    +		return this;
    +		
    +		function root( elem, cur ) {
    +			return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
    +				(elem.getElementsByTagName("tbody")[0] ||
    +				elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
    +				elem;
    +		}
    +	}
    +};
    +
    +// Give the init function the jQuery prototype for later instantiation
    +jQuery.fn.init.prototype = jQuery.fn;
    +
    +function evalScript( i, elem ) {
    +	if ( elem.src )
    +		jQuery.ajax({
    +			url: elem.src,
    +			async: false,
    +			dataType: "script"
    +		});
    +
    +	else
    +		jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
    +
    +	if ( elem.parentNode )
    +		elem.parentNode.removeChild( elem );
    +}
    +
    +function now(){
    +	return +new Date;
    +}
    +
    +jQuery.extend = jQuery.fn.extend = function() {
    +	// copy reference to target object
    +	var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;
    +
    +	// Handle a deep copy situation
    +	if ( typeof target === "boolean" ) {
    +		deep = target;
    +		target = arguments[1] || {};
    +		// skip the boolean and the target
    +		i = 2;
    +	}
    +
    +	// Handle case when target is a string or something (possible in deep copy)
    +	if ( typeof target !== "object" && !jQuery.isFunction(target) )
    +		target = {};
    +
    +	// extend jQuery itself if only one argument is passed
    +	if ( length == i ) {
    +		target = this;
    +		--i;
    +	}
    +
    +	for ( ; i < length; i++ )
    +		// Only deal with non-null/undefined values
    +		if ( (options = arguments[ i ]) != null )
    +			// Extend the base object
    +			for ( var name in options ) {
    +				var src = target[ name ], copy = options[ name ];
    +
    +				// Prevent never-ending loop
    +				if ( target === copy )
    +					continue;
    +
    +				// Recurse if we're merging object values
    +				if ( deep && copy && typeof copy === "object" && !copy.nodeType )
    +					target[ name ] = jQuery.extend( deep, 
    +						// Never move original objects, clone them
    +						src || ( copy.length != null ? [ ] : { } )
    +					, copy );
    +
    +				// Don't bring in undefined values
    +				else if ( copy !== undefined )
    +					target[ name ] = copy;
    +
    +			}
    +
    +	// Return the modified object
    +	return target;
    +};
    +
    +// exclude the following css properties to add px
    +var	exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
    +	// cache defaultView
    +	defaultView = document.defaultView || {},
    +	toString = Object.prototype.toString;
    +
    +jQuery.extend({
    +	noConflict: function( deep ) {
    +		window.$ = _$;
    +
    +		if ( deep )
    +			window.jQuery = _jQuery;
    +
    +		return jQuery;
    +	},
    +
    +	// See test/unit/core.js for details concerning isFunction.
    +	// Since version 1.3, DOM methods and functions like alert
    +	// aren't supported. They return false on IE (#2968).
    +	isFunction: function( obj ) {
    +		return toString.call(obj) === "[object Function]";
    +	},
    +
    +	isArray: function( obj ) {
    +		return toString.call(obj) === "[object Array]";
    +	},
    +
    +	// check if an element is in a (or is an) XML document
    +	isXMLDoc: function( elem ) {
    +		return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
    +			!!elem.ownerDocument && jQuery.isXMLDoc( elem.ownerDocument );
    +	},
    +
    +	// Evalulates a script in a global context
    +	globalEval: function( data ) {
    +		data = jQuery.trim( data );
    +
    +		if ( data ) {
    +			// Inspired by code by Andrea Giammarchi
    +			// http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
    +			var head = document.getElementsByTagName("head")[0] || document.documentElement,
    +				script = document.createElement("script");
    +
    +			script.type = "text/javascript";
    +			if ( jQuery.support.scriptEval )
    +				script.appendChild( document.createTextNode( data ) );
    +			else
    +				script.text = data;
    +
    +			// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
    +			// This arises when a base node is used (#2709).
    +			head.insertBefore( script, head.firstChild );
    +			head.removeChild( script );
    +		}
    +	},
    +
    +	nodeName: function( elem, name ) {
    +		return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
    +	},
    +
    +	// args is for internal usage only
    +	each: function( object, callback, args ) {
    +		var name, i = 0, length = object.length;
    +
    +		if ( args ) {
    +			if ( length === undefined ) {
    +				for ( name in object )
    +					if ( callback.apply( object[ name ], args ) === false )
    +						break;
    +			} else
    +				for ( ; i < length; )
    +					if ( callback.apply( object[ i++ ], args ) === false )
    +						break;
    +
    +		// A special, fast, case for the most common use of each
    +		} else {
    +			if ( length === undefined ) {
    +				for ( name in object )
    +					if ( callback.call( object[ name ], name, object[ name ] ) === false )
    +						break;
    +			} else
    +				for ( var value = object[0];
    +					i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
    +		}
    +
    +		return object;
    +	},
    +
    +	prop: function( elem, value, type, i, name ) {
    +		// Handle executable functions
    +		if ( jQuery.isFunction( value ) )
    +			value = value.call( elem, i );
    +
    +		// Handle passing in a number to a CSS property
    +		return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ?
    +			value + "px" :
    +			value;
    +	},
    +
    +	className: {
    +		// internal only, use addClass("class")
    +		add: function( elem, classNames ) {
    +			jQuery.each((classNames || "").split(/\s+/), function(i, className){
    +				if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
    +					elem.className += (elem.className ? " " : "") + className;
    +			});
    +		},
    +
    +		// internal only, use removeClass("class")
    +		remove: function( elem, classNames ) {
    +			if (elem.nodeType == 1)
    +				elem.className = classNames !== undefined ?
    +					jQuery.grep(elem.className.split(/\s+/), function(className){
    +						return !jQuery.className.has( classNames, className );
    +					}).join(" ") :
    +					"";
    +		},
    +
    +		// internal only, use hasClass("class")
    +		has: function( elem, className ) {
    +			return elem && jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
    +		}
    +	},
    +
    +	// A method for quickly swapping in/out CSS properties to get correct calculations
    +	swap: function( elem, options, callback ) {
    +		var old = {};
    +		// Remember the old values, and insert the new ones
    +		for ( var name in options ) {
    +			old[ name ] = elem.style[ name ];
    +			elem.style[ name ] = options[ name ];
    +		}
    +
    +		callback.call( elem );
    +
    +		// Revert the old values
    +		for ( var name in options )
    +			elem.style[ name ] = old[ name ];
    +	},
    +
    +	css: function( elem, name, force ) {
    +		if ( name == "width" || name == "height" ) {
    +			var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];
    +
    +			function getWH() {
    +				val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
    +				var padding = 0, border = 0;
    +				jQuery.each( which, function() {
    +					padding += parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
    +					border += parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
    +				});
    +				val -= Math.round(padding + border);
    +			}
    +
    +			if ( jQuery(elem).is(":visible") )
    +				getWH();
    +			else
    +				jQuery.swap( elem, props, getWH );
    +
    +			return Math.max(0, val);
    +		}
    +
    +		return jQuery.curCSS( elem, name, force );
    +	},
    +
    +	curCSS: function( elem, name, force ) {
    +		var ret, style = elem.style;
    +
    +		// We need to handle opacity special in IE
    +		if ( name == "opacity" && !jQuery.support.opacity ) {
    +			ret = jQuery.attr( style, "opacity" );
    +
    +			return ret == "" ?
    +				"1" :
    +				ret;
    +		}
    +
    +		// Make sure we're using the right name for getting the float value
    +		if ( name.match( /float/i ) )
    +			name = styleFloat;
    +
    +		if ( !force && style && style[ name ] )
    +			ret = style[ name ];
    +
    +		else if ( defaultView.getComputedStyle ) {
    +
    +			// Only "float" is needed here
    +			if ( name.match( /float/i ) )
    +				name = "float";
    +
    +			name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();
    +
    +			var computedStyle = defaultView.getComputedStyle( elem, null );
    +
    +			if ( computedStyle )
    +				ret = computedStyle.getPropertyValue( name );
    +
    +			// We should always get a number back from opacity
    +			if ( name == "opacity" && ret == "" )
    +				ret = "1";
    +
    +		} else if ( elem.currentStyle ) {
    +			var camelCase = name.replace(/\-(\w)/g, function(all, letter){
    +				return letter.toUpperCase();
    +			});
    +
    +			ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];
    +
    +			// From the awesome hack by Dean Edwards
    +			// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
    +
    +			// If we're not dealing with a regular pixel number
    +			// but a number that has a weird ending, we need to convert it to pixels
    +			if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
    +				// Remember the original values
    +				var left = style.left, rsLeft = elem.runtimeStyle.left;
    +
    +				// Put in the new values to get a computed value out
    +				elem.runtimeStyle.left = elem.currentStyle.left;
    +				style.left = ret || 0;
    +				ret = style.pixelLeft + "px";
    +
    +				// Revert the changed values
    +				style.left = left;
    +				elem.runtimeStyle.left = rsLeft;
    +			}
    +		}
    +
    +		return ret;
    +	},
    +
    +	clean: function( elems, context, fragment ) {
    +		context = context || document;
    +
    +		// !context.createElement fails in IE with an error but returns typeof 'object'
    +		if ( typeof context.createElement === "undefined" )
    +			context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
    +
    +		// If a single string is passed in and it's a single tag
    +		// just do a createElement and skip the rest
    +		if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
    +			var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
    +			if ( match )
    +				return [ context.createElement( match[1] ) ];
    +		}
    +
    +		var ret = [], scripts = [], div = context.createElement("div");
    +
    +		jQuery.each(elems, function(i, elem){
    +			if ( typeof elem === "number" )
    +				elem += '';
    +
    +			if ( !elem )
    +				return;
    +
    +			// Convert html string into DOM nodes
    +			if ( typeof elem === "string" ) {
    +				// Fix "XHTML"-style tags in all browsers
    +				elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
    +					return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
    +						all :
    +						front + ">";
    +				});
    +
    +				// Trim whitespace, otherwise indexOf won't work as expected
    +				var tags = jQuery.trim( elem ).toLowerCase();
    +
    +				var wrap =
    +					// option or optgroup
    +					!tags.indexOf("", "" ] ||
    +
    +					!tags.indexOf("", "" ] ||
    +
    +					tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
    +					[ 1, "", "
    " ] || + + !tags.indexOf("", "" ] || + + // matched above + (!tags.indexOf("", "" ] || + + !tags.indexOf("", "" ] || + + // IE can't serialize and + + + + + + + +

    XMLRPC +
    + / +
    + JSONRPC Debugger (based on the PHP-XMLRPC library) +

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

    Target server

    Address:Port: + Path:
    + + + + + + + + + +

    Action

    List available methods onclick="switchaction();"/>Describe method onclick="switchaction();"/>Execute method onclick="switchaction();"/>Generate stub for method call onclick="switchaction();"/>
    + + + + + + + + + + + + +

    Method

    Name:Payload:
    +
    +
    Msg id: +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

    Client options

    Show debug info: + Timeout:Protocol:
    AUTH:Username:Pwd:Type
    SSL:Verify Host's CN:Verify Cert: />CA Cert file:
    PROXY:Server:Proxy user:Proxy pwd:
    COMPRESSION:Request:Response:
    COOKIES:Format: 'cookie1=value1, cookie2=value2'
    + +
    + + diff --git a/lib/phpxmlrpc/debugger/index.php b/lib/phpxmlrpc/debugger/index.php new file mode 100644 index 0000000..eff10ea --- /dev/null +++ b/lib/phpxmlrpc/debugger/index.php @@ -0,0 +1,21 @@ + + + + + XMLRPC Debugger + + + + + + diff --git a/lib/phpxmlrpc/demo/client/agesort.php b/lib/phpxmlrpc/demo/client/agesort.php new file mode 100644 index 0000000..90622d2 --- /dev/null +++ b/lib/phpxmlrpc/demo/client/agesort.php @@ -0,0 +1,68 @@ + +xmlrpc - Agesort demo + +

    Agesort demo

    + +

    Send an array of 'name' => 'age' pairs to the server that will send it back sorted.

    + +

    The source code demonstrates basic lib usage, including handling of xmlrpc arrays and structs

    + +

    + 24, "Edd" => 45, "Joe" => 37, "Fred" => 27); +print "This is the input data:
    ";
    +foreach($inAr as $key => $val) {
    +    print $key . ", " . $val . "\n";
    +}
    +print "
    "; + +// create parameters from the input array: an xmlrpc array of xmlrpc structs +$p = array(); +foreach ($inAr as $key => $val) { + $p[] = new PhpXmlRpc\Value( + array( + "name" => new PhpXmlRpc\Value($key), + "age" => new PhpXmlRpc\Value($val, "int") + ), + "struct" + ); +} +$v = new PhpXmlRpc\Value($p, "array"); +print "Encoded into xmlrpc format it looks like this:
    \n" . htmlentities($v->serialize()) . "
    \n"; + +// create client and message objects +$req = new PhpXmlRpc\Request('examples.sortByAge', array($v)); +$client = new PhpXmlRpc\Client("http://phpxmlrpc.sourceforge.net/server.php"); + +// set maximum debug level, to have the complete communication printed to screen +$client->setDebug(2); + +// send request +print "Now sending request (detailed debug info follows)"; +$resp = $client->send($req); + +// check response for errors, and take appropriate action +if (!$resp->faultCode()) { + print "The server gave me these results:
    ";
    +    $value = $resp->value();
    +    foreach ($value as $struct) {
    +        $name = $struct["name"];
    +        $age = $struct["age"];
    +        print htmlspecialchars($name->scalarval()) . ", " . htmlspecialchars($age->scalarval()) . "\n";
    +    }
    +
    +    print "
    For nerds: I got this value back
    " .
    +        htmlentities($resp->serialize()) . "

    \n"; +} else { + print "An error occurred:
    ";
    +    print "Code: " . htmlspecialchars($resp->faultCode()) .
    +        "\nReason: '" . htmlspecialchars($resp->faultString()) . '\'

    '; +} + +?> + + diff --git a/lib/phpxmlrpc/demo/client/getstatename.php b/lib/phpxmlrpc/demo/client/getstatename.php new file mode 100644 index 0000000..69ce3e0 --- /dev/null +++ b/lib/phpxmlrpc/demo/client/getstatename.php @@ -0,0 +1,43 @@ + +xmlrpc - Getstatename demo + +

    Getstatename demo

    + +

    Send a U.S. state number to the server and get back the state name

    + +

    The code demonstrates usage of automatic encoding/decoding of php variables into xmlrpc values

    +encode($stateNo)) + ); + print "Sending the following request:
    \n\n" . htmlentities($req->serialize()) . "\n\n
    Debug info of server data follows...\n\n"; + $client = new PhpXmlRpc\Client("http://phpxmlrpc.sourceforge.net/server.php"); + $client->setDebug(1); + $r = $client->send($req); + if (!$r->faultCode()) { + $v = $r->value(); + print "
    State number " . $stateNo . " is " + . htmlspecialchars($encoder->decode($v)) . "
    "; + } else { + print "An error occurred: "; + print "Code: " . htmlspecialchars($r->faultCode()) + . " Reason: '" . htmlspecialchars($r->faultString()) . "'

    "; + } +} else { + $stateNo = ""; +} + +print "
    +
    +

    Enter a state number to query its name

    "; + +?> + + diff --git a/lib/phpxmlrpc/demo/client/introspect.php b/lib/phpxmlrpc/demo/client/introspect.php new file mode 100644 index 0000000..7870a94 --- /dev/null +++ b/lib/phpxmlrpc/demo/client/introspect.php @@ -0,0 +1,86 @@ + +xmlrpc - Introspect demo + +

    Introspect demo

    +

    Query server for available methods and their description

    +

    The code demonstrates usage of multicall and introspection methods

    +faultCode() + . " Reason: '" . $r->faultString() . "'
    "; +} + +$client = new PhpXmlRpc\Client("http://phpxmlrpc.sourceforge.net/server.php"); + +// First off, let's retrieve the list of methods available on the remote server +print "

    methods available at http://" . $client->server . $client->path . "

    \n"; +$req = new PhpXmlRpc\Request('system.listMethods'); +$resp = $client->send($req); + +if ($resp->faultCode()) { + display_error($resp); +} else { + $v = $resp->value(); + + // Then, retrieve the signature and help text of each available method + foreach ($v as $methodName) { + print "

    " . $methodName->scalarval() . "

    \n"; + // build messages first, add params later + $m1 = new PhpXmlRpc\Request('system.methodHelp'); + $m2 = new PhpXmlRpc\Request('system.methodSignature'); + $val = new PhpXmlRpc\Value($methodName->scalarval(), "string"); + $m1->addParam($val); + $m2->addParam($val); + // Send multiple requests in one http call. + // If server does not support multicall, client will automatically fall back to 2 separate calls + $ms = array($m1, $m2); + $rs = $client->send($ms); + if ($rs[0]->faultCode()) { + display_error($rs[0]); + } else { + $val = $rs[0]->value(); + $txt = $val->scalarval(); + if ($txt != "") { + print "

    Documentation

    ${txt}

    \n"; + } else { + print "

    No documentation available.

    \n"; + } + } + if ($rs[1]->faultCode()) { + display_error($rs[1]); + } else { + print "

    Signature

    \n"; + // note: using PhpXmlRpc\Encoder::decode() here would lead to cleaner code + $val = $rs[1]->value(); + if ($val->kindOf() == "array") { + foreach ($val as $x) { + $ret = $x[0]; + print "" . $ret->scalarval() . " " + . $methodName->scalarval() . "("; + if ($x->count() > 1) { + for ($k = 1; $k < $x->count(); $k++) { + $y = $x[$k]; + print $y->scalarval(); + if ($k < $x->count() - 1) { + print ", "; + } + } + } + print ")
    \n"; + } + } else { + print "Signature unknown\n"; + } + print "

    \n"; + } + } +} +?> + + diff --git a/lib/phpxmlrpc/demo/client/mail.php b/lib/phpxmlrpc/demo/client/mail.php new file mode 100644 index 0000000..9486e09 --- /dev/null +++ b/lib/phpxmlrpc/demo/client/mail.php @@ -0,0 +1,66 @@ + + +xmlrpc - Mail demo + +

    Mail demo

    + +

    This form enables you to send mail via an XML-RPC server. + When you press Send this page will reload, showing you the XML-RPC request sent to the host server, the + XML-RPC response received and the internal evaluation done by the PHP implementation.

    + +

    You can find the source to this page here: mail.php
    + And the source to a functionally identical mail-by-XML-RPC server in the file server.php included with the library (look for the 'mail_send' + method)

    +setDebug(2); + $resp = $client->send($req); + if (!$resp->faultCode()) { + print "Mail sent OK
    \n"; + } else { + print ""; + print "Mail send failed
    \n"; + print "Fault: "; + print "Code: " . htmlspecialchars($resp->faultCode()) . + " Reason: '" . htmlspecialchars($resp->faultString()) . "'
    "; + print "
    "; + } +} +?> +
    + From
    +
    + To
    + Cc
    + Bcc
    +
    + Subject +
    + Body
    + +
    + + diff --git a/lib/phpxmlrpc/demo/client/proxy.php b/lib/phpxmlrpc/demo/client/proxy.php new file mode 100644 index 0000000..7173db0 --- /dev/null +++ b/lib/phpxmlrpc/demo/client/proxy.php @@ -0,0 +1,60 @@ + +xmlrpc - Proxy demo + +

    proxy demo

    +

    Query server using a 'proxy' object

    +

    The code demonstrates usage for the terminally lazy. For a more complete proxy, look at at the Wrapper class

    +client = $client; + } + + /** + * Translates any method call to an xmlrpc call. + * + * @author Toth Istvan + * + * @param string $name remote function name. Will be prefixed + * @param array $arguments + * + * @return mixed + * + * @throws Exception + */ + function __call($name, $arguments) + { + $encoder = new PhpXmlRpc\Encoder(); + $valueArray = array(); + foreach ($arguments as $parameter) { + $valueArray[] = $encoder->encode($parameter); + } + + // just in case this was set to something else + $this->client->return_type = 'phpvals'; + + $resp = $this->client->send(new PhpXmlRpc\Request($this->prefix.$name, $valueArray)); + + if ($resp->faultCode()) { + throw new Exception($resp->faultString(), $resp->faultCode()); + } else { + return $resp->value(); + } + } + +} + +$stateNo = rand(1, 51); +$proxy = new PhpXmlRpcProxy(new \PhpXmlRpc\Client('http://phpxmlrpc.sourceforge.net/server.php')); +$stateName = $proxy->getStateName($stateNo); + +echo "State $stateNo is ".htmlspecialchars($stateName); \ No newline at end of file diff --git a/lib/phpxmlrpc/demo/client/which.php b/lib/phpxmlrpc/demo/client/which.php new file mode 100644 index 0000000..5d33215 --- /dev/null +++ b/lib/phpxmlrpc/demo/client/which.php @@ -0,0 +1,30 @@ + +xmlrpc - Which toolkit demo + +

    Which toolkit demo

    +

    Query server for toolkit information

    +

    The code demonstrates usage of the PhpXmlRpc\Encoder class

    +send($req); +if (!$resp->faultCode()) { + $encoder = new PhpXmlRpc\Encoder(); + $value = $encoder->decode($resp->value()); + print "
    ";
    +    print "name: " . htmlspecialchars($value["toolkitName"]) . "\n";
    +    print "version: " . htmlspecialchars($value["toolkitVersion"]) . "\n";
    +    print "docs: " . htmlspecialchars($value["toolkitDocsUrl"]) . "\n";
    +    print "os: " . htmlspecialchars($value["toolkitOperatingSystem"]) . "\n";
    +    print "
    "; +} else { + print "An error occurred: "; + print "Code: " . htmlspecialchars($resp->faultCode()) . " Reason: '" . htmlspecialchars($resp->faultString()) . "'\n"; +} +?> + + diff --git a/lib/phpxmlrpc/demo/client/wrap.php b/lib/phpxmlrpc/demo/client/wrap.php new file mode 100644 index 0000000..c13c55d --- /dev/null +++ b/lib/phpxmlrpc/demo/client/wrap.php @@ -0,0 +1,53 @@ + +xmlrpc - Webservice wrappper demo + +

    Webservice wrappper demo

    + +

    Wrap methods exposed by server into php functions

    + +

    The code demonstrates usage of some the most automagic client usage possible:
    + 1) client that returns php values instead of xmlrpc value objects
    + 2) wrapping of remote methods into php functions
    + See also proxy.php for an alternative take +

    +return_type = 'phpvals'; // let client give us back php values instead of xmlrpcvals +$resp = $client->send(new PhpXmlRpc\Request('system.listMethods')); +if ($resp->faultCode()) { + echo "

    Server methods list could not be retrieved: error {$resp->faultCode()} '" . htmlspecialchars($resp->faultString()) . "'

    \n"; +} else { + echo "

    Server methods list retrieved, now wrapping it up...

    \n
      \n"; + flush(); + + $callable = false; + $wrapper = new PhpXmlRpc\Wrapper(); + foreach ($resp->value() as $methodName) { + // $resp->value is an array of strings + if ($methodName == 'examples.getStateName') { + $callable = $wrapper->wrapXmlrpcMethod($client, $methodName); + if ($callable) { + echo "
    • Remote server method " . htmlspecialchars($methodName) . " wrapped into php function
    • \n"; + } else { + echo "
    • Remote server method " . htmlspecialchars($methodName) . " could not be wrapped!
    • \n"; + } + break; + } + } + echo "
    \n"; + flush(); + + if ($callable) { + echo "Now testing function for remote method to convert U.S. state number into state name"; + $stateNum = rand(1, 51); + // the 2nd parameter gets added to the closure - it is teh debug level to be used for the client + $stateName = $callable($stateNum, 2); + } +} +?> + + diff --git a/lib/phpxmlrpc/demo/demo1.xml b/lib/phpxmlrpc/demo/demo1.xml new file mode 100644 index 0000000..eeb6a69 --- /dev/null +++ b/lib/phpxmlrpc/demo/demo1.xml @@ -0,0 +1,60 @@ + + + + + + + + thearray + + + + + ABCDEFHIJ + + + 1234 + + + 1 + + + + + + + theint + + 23 + + + + thestring + + foobarwhizz + + + + thestruct + + + + one + + 1 + + + + two + + 2 + + + + + + + + + + diff --git a/lib/phpxmlrpc/demo/demo2.xml b/lib/phpxmlrpc/demo/demo2.xml new file mode 100644 index 0000000..3289caf --- /dev/null +++ b/lib/phpxmlrpc/demo/demo2.xml @@ -0,0 +1,10 @@ + + + + + + South Dakota's own + + + + diff --git a/lib/phpxmlrpc/demo/demo3.xml b/lib/phpxmlrpc/demo/demo3.xml new file mode 100644 index 0000000..ed94aab --- /dev/null +++ b/lib/phpxmlrpc/demo/demo3.xml @@ -0,0 +1,21 @@ + + + + + + + faultCode + + 4 + + + + faultString + + Too many parameters. + + + + + + diff --git a/lib/phpxmlrpc/demo/server/discuss.php b/lib/phpxmlrpc/demo/server/discuss.php new file mode 100644 index 0000000..ac65209 --- /dev/null +++ b/lib/phpxmlrpc/demo/server/discuss.php @@ -0,0 +1,99 @@ +decode($req); + $msgID = $n[0]; + $name = $n[1]; + $comment = $n[2]; + + $dbh = dba_open("/tmp/comments.db", "c", "db2"); + if ($dbh) { + $countID = "${msgID}_count"; + if (dba_exists($countID, $dbh)) { + $count = dba_fetch($countID, $dbh); + } else { + $count = 0; + } + // add the new comment in + dba_insert($msgID . "_comment_${count}", $comment, $dbh); + dba_insert($msgID . "_name_${count}", $name, $dbh); + $count++; + dba_replace($countID, $count, $dbh); + dba_close($dbh); + } else { + $err = "Unable to open comments database."; + } + // if we generated an error, create an error return response + if ($err) { + return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err); + } else { + // otherwise, we create the right response + return new PhpXmlRpc\Response(new PhpXmlRpc\Value($count, "int")); + } +} + +$getComments_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcString)); + +$getComments_doc = 'Returns an array of comments for a given ID, which +is the sole argument. Each array item is a struct containing name +and comment text.'; + +function getComments($req) +{ + $err = ""; + $ra = array(); + $encoder = new PhpXmlRpc\Encoder(); + $msgID = $encoder->decode($req->getParam(0)); + $dbh = dba_open("/tmp/comments.db", "r", "db2"); + if ($dbh) { + $countID = "${msgID}_count"; + if (dba_exists($countID, $dbh)) { + $count = dba_fetch($countID, $dbh); + for ($i = 0; $i < $count; $i++) { + $name = dba_fetch("${msgID}_name_${i}", $dbh); + $comment = dba_fetch("${msgID}_comment_${i}", $dbh); + // push a new struct onto the return array + $ra[] = array( + "name" => $name, + "comment" => $comment, + ); + } + } + } + // if we generated an error, create an error return response + if ($err) { + return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err); + } else { + // otherwise, we create the right response + return new PhpXmlRpc\Response($encoder->encode($ra)); + } +} + +$srv = new PhpXmlRpc\Server(array( + "discuss.addComment" => array( + "function" => "addComment", + "signature" => $addComment_sig, + "docstring" => $addComment_doc, + ), + "discuss.getComments" => array( + "function" => "getComments", + "signature" => $getComments_sig, + "docstring" => $getComments_doc, + ), +)); diff --git a/lib/phpxmlrpc/demo/server/proxy.php b/lib/phpxmlrpc/demo/server/proxy.php new file mode 100644 index 0000000..6e791f4 --- /dev/null +++ b/lib/phpxmlrpc/demo/server/proxy.php @@ -0,0 +1,88 @@ +decode($req->getParam(0)); + $client = new PhpXmlRpc\Client($url); + + if ($req->getNumParams() > 3) { + // we have to set some options onto the client. + // Note that if we do not untaint the received values, warnings might be generated... + $options = $encoder->decode($req->getParam(3)); + foreach ($options as $key => $val) { + switch ($key) { + case 'Cookie': + break; + case 'Credentials': + break; + case 'RequestCompression': + $client->setRequestCompression($val); + break; + case 'SSLVerifyHost': + $client->setSSLVerifyHost($val); + break; + case 'SSLVerifyPeer': + $client->setSSLVerifyPeer($val); + break; + case 'Timeout': + $timeout = (integer)$val; + break; + } // switch + } + } + + // build call for remote server + /// @todo find a way to forward client info (such as IP) to server, either + /// - as xml comments in the payload, or + /// - using std http header conventions, such as X-forwarded-for... + $reqMethod = $encoder->decode($req->getParam(1)); + $pars = $req->getParam(2); + $req = new PhpXmlRpc\Request($reqMethod); + foreach ($pars as $par) { + $req->addParam($par); + } + + // add debug info into response we give back to caller + PhpXmlRpc\Server::xmlrpc_debugmsg("Sending to server $url the payload: " . $req->serialize()); + + return $client->send($req, $timeout); +} + +// run the server +$server = new PhpXmlRpc\Server( + array( + 'xmlrpcproxy.call' => array( + 'function' => 'forward_request', + 'signature' => array( + array('mixed', 'string', 'string', 'array'), + array('mixed', 'string', 'string', 'array', 'struct'), + ), + 'docstring' => 'forwards xmlrpc calls to remote servers. Returns remote method\'s response. Accepts params: remote server url (might include basic auth credentials), method name, array of params, and (optionally) a struct containing call options', + ), + ) +); diff --git a/lib/phpxmlrpc/demo/server/server.php b/lib/phpxmlrpc/demo/server/server.php new file mode 100644 index 0000000..b18cf46 --- /dev/null +++ b/lib/phpxmlrpc/demo/server/server.php @@ -0,0 +1,981 @@ +hello = 'world'; + return $obj; + } +} + +// a PHP version of the state-number server +// send me an integer and i'll sell you a state + +$stateNames = array( + "Alabama", "Alaska", "Arizona", "Arkansas", "California", + "Colorado", "Columbia", "Connecticut", "Delaware", "Florida", + "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", + "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", + "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", + "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", + "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", + "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", + "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming", +); + +$findstate_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcInt)); +$findstate_doc = 'When passed an integer between 1 and 51 returns the +name of a US state, where the integer is the index of that state name +in an alphabetic order.'; + +function findState($req) +{ + global $stateNames; + + $err = ""; + // get the first param + $sno = $req->getParam(0); + + // param must be there and of the correct type: server object does the validation for us + + // extract the value of the state number + $snv = $sno->scalarval(); + // look it up in our array (zero-based) + if (isset($stateNames[$snv - 1])) { + $stateName = $stateNames[$snv - 1]; + } else { + // not there, so complain + $err = "I don't have a state for the index '" . $snv . "'"; + } + + // if we generated an error, create an error return response + if ($err) { + return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err); + } else { + // otherwise, we create the right response with the state name + return new PhpXmlRpc\Response(new Value($stateName)); + } +} + +/** + * Inner code of the state-number server. + * Used to test wrapping of PHP functions into xmlrpc methods. + * + * @param integer $stateNo the state number + * + * @return string the name of the state (or error description) + * + * @throws Exception if state is not found + */ +function inner_findstate($stateNo) +{ + global $stateNames; + + if (isset($stateNames[$stateNo - 1])) { + return $stateNames[$stateNo - 1]; + } else { + // not, there so complain + throw new Exception("I don't have a state for the index '" . $stateNo . "'", PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser); + } +} + +$wrapper = new PhpXmlRpc\Wrapper(); + +$findstate2_sig = $wrapper->wrapPhpFunction('inner_findstate'); + +$findstate3_sig = $wrapper->wrapPhpFunction(array('xmlrpcServerMethodsContainer', 'findState')); + +$obj = new xmlrpcServerMethodsContainer(); +$findstate4_sig = $wrapper->wrapPhpFunction(array($obj, 'findstate')); + +$findstate5_sig = $wrapper->wrapPhpFunction('xmlrpcServerMethodsContainer::findState', '', array('return_source' => true)); +eval($findstate5_sig['source']); + +$findstate6_sig = $wrapper->wrapPhpFunction('inner_findstate', '', array('return_source' => true)); +eval($findstate6_sig['source']); + +$findstate7_sig = $wrapper->wrapPhpFunction(array('xmlrpcServerMethodsContainer', 'findState'), '', array('return_source' => true)); +eval($findstate7_sig['source']); + +$obj = new xmlrpcServerMethodsContainer(); +$findstate8_sig = $wrapper->wrapPhpFunction(array($obj, 'findstate'), '', array('return_source' => true)); +eval($findstate8_sig['source']); + +$findstate9_sig = $wrapper->wrapPhpFunction('xmlrpcServerMethodsContainer::findState', '', array('return_source' => true)); +eval($findstate9_sig['source']); + +$findstate10_sig = array( + "function" => function ($req) { return findState($req); }, + "signature" => $findstate_sig, + "docstring" => $findstate_doc, +); + +$findstate11_sig = $wrapper->wrapPhpFunction(function ($stateNo) { return inner_findstate($stateNo); }); + +$c = new xmlrpcServerMethodsContainer; +$moreSignatures = $wrapper->wrapPhpClass($c, array('prefix' => 'tests.', 'method_type' => 'all')); + +$returnObj_sig = $wrapper->wrapPhpFunction(array($c, 'returnObject'), '', array('encode_php_objs' => true)); + +// used to test signatures with NULL params +$findstate12_sig = array( + array(Value::$xmlrpcString, Value::$xmlrpcInt, Value::$xmlrpcNull), + array(Value::$xmlrpcString, Value::$xmlrpcNull, Value::$xmlrpcInt), +); + +function findStateWithNulls($req) +{ + $a = $req->getParam(0); + $b = $req->getParam(1); + + if ($a->scalartyp() == Value::$xmlrpcNull) + return new PhpXmlRpc\Response(new Value(inner_findstate($b->scalarval()))); + else + return new PhpXmlRpc\Response(new Value(inner_findstate($a->scalarval()))); +} + +$addtwo_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcInt, Value::$xmlrpcInt)); +$addtwo_doc = 'Add two integers together and return the result'; +function addTwo($req) +{ + $s = $req->getParam(0); + $t = $req->getParam(1); + + return new PhpXmlRpc\Response(new Value($s->scalarval() + $t->scalarval(), Value::$xmlrpcInt)); +} + +$addtwodouble_sig = array(array(Value::$xmlrpcDouble, Value::$xmlrpcDouble, Value::$xmlrpcDouble)); +$addtwodouble_doc = 'Add two doubles together and return the result'; +function addTwoDouble($req) +{ + $s = $req->getParam(0); + $t = $req->getParam(1); + + return new PhpXmlRpc\Response(new Value($s->scalarval() + $t->scalarval(), Value::$xmlrpcDouble)); +} + +$stringecho_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcString)); +$stringecho_doc = 'Accepts a string parameter, returns the string.'; +function stringEcho($req) +{ + // just sends back a string + return new PhpXmlRpc\Response(new Value($req->getParam(0)->scalarval())); +} + +$echoback_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcString)); +$echoback_doc = 'Accepts a string parameter, returns the entire incoming payload'; +function echoBack($req) +{ + // just sends back a string with what i got sent to me, just escaped, that's all + $s = "I got the following message:\n" . $req->serialize(); + + return new PhpXmlRpc\Response(new Value($s)); +} + +$echosixtyfour_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcBase64)); +$echosixtyfour_doc = 'Accepts a base64 parameter and returns it decoded as a string'; +function echoSixtyFour($req) +{ + // Accepts an encoded value, but sends it back as a normal string. + // This is to test that base64 encoding is working as expected + $incoming = $req->getParam(0); + + return new PhpXmlRpc\Response(new Value($incoming->scalarval(), Value::$xmlrpcString)); +} + +$bitflipper_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)); +$bitflipper_doc = 'Accepts an array of booleans, and returns them inverted'; +function bitFlipper($req) +{ + $v = $req->getParam(0); + $rv = new Value(array(), Value::$xmlrpcArray); + + foreach ($v as $b) { + if ($b->scalarval()) { + $rv[] = new Value(false, Value::$xmlrpcBoolean); + } else { + $rv[] = new Value(true, Value::$xmlrpcBoolean); + } + } + + return new PhpXmlRpc\Response($rv); +} + +// Sorting demo +// +// send me an array of structs thus: +// +// Dave 35 +// Edd 45 +// Fred 23 +// Barney 37 +// +// and I'll return it to you in sorted order + +function agesorter_compare($a, $b) +{ + global $agesorter_arr; + + // don't even ask me _why_ these come padded with hyphens, I couldn't tell you :p + $a = str_replace("-", "", $a); + $b = str_replace("-", "", $b); + + if ($agesorter_arr[$a] == $agesorter_arr[$b]) { + return 0; + } + + return ($agesorter_arr[$a] > $agesorter_arr[$b]) ? -1 : 1; +} + +$agesorter_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)); +$agesorter_doc = 'Send this method an array of [string, int] structs, eg: +
    + Dave   35
    + Edd    45
    + Fred   23
    + Barney 37
    +
    +And the array will be returned with the entries sorted by their numbers. +'; +function ageSorter($req) +{ + global $agesorter_arr, $s; + + PhpXmlRpc\Server::xmlrpc_debugmsg("Entering 'agesorter'"); + // get the parameter + $sno = $req->getParam(0); + // error string for [if|when] things go wrong + $err = ""; + $agar = array(); + + $max = $sno->count(); + PhpXmlRpc\Server::xmlrpc_debugmsg("Found $max array elements"); + foreach ($sno as $i => $rec) { + if ($rec->kindOf() != "struct") { + $err = "Found non-struct in array at element $i"; + break; + } + // extract name and age from struct + $n = $rec["name"]; + $a = $rec["age"]; + // $n and $a are xmlrpcvals, + // so get the scalarval from them + $agar[$n->scalarval()] = $a->scalarval(); + } + + // create the output value + $v = new Value(array(), Value::$xmlrpcArray); + + $agesorter_arr = $agar; + // hack, must make global as uksort() won't + // allow us to pass any other auxiliary information + uksort($agesorter_arr, 'agesorter_compare'); + while (list($key, $val) = each($agesorter_arr)) { + // recreate each struct element + $v[] = new Value( + array( + "name" => new Value($key), + "age" => new Value($val, "int") + ), + Value::$xmlrpcStruct + ); + } + + if ($err) { + return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err); + } else { + return new PhpXmlRpc\Response($v); + } +} + +// signature and instructions, place these in the dispatch map +$mailsend_sig = array(array( + Value::$xmlrpcBoolean, Value::$xmlrpcString, Value::$xmlrpcString, + Value::$xmlrpcString, Value::$xmlrpcString, Value::$xmlrpcString, + Value::$xmlrpcString, Value::$xmlrpcString, +)); +$mailsend_doc = 'mail.send(recipient, subject, text, sender, cc, bcc, mimetype)
    +recipient, cc, and bcc are strings, comma-separated lists of email addresses, as described above.
    +subject is a string, the subject of the message.
    +sender is a string, it\'s the email address of the person sending the message. This string can not be +a comma-separated list, it must contain a single email address only.
    +text is a string, it contains the body of the message.
    +mimetype, a string, is a standard MIME type, for example, text/plain. +'; +// WARNING; this functionality depends on the sendmail -t option +// it may not work with Windows machines properly; particularly +// the Bcc option. Sneak on your friends at your own risk! +function mailSend($req) +{ + $err = ""; + + $mTo = $req->getParam(0); + $mSub = $req->getParam(1); + $mBody = $req->getParam(2); + $mFrom = $req->getParam(3); + $mCc = $req->getParam(4); + $mBcc = $req->getParam(5); + $mMime = $req->getParam(6); + + if ($mTo->scalarval() == "") { + $err = "Error, no 'To' field specified"; + } + + if ($mFrom->scalarval() == "") { + $err = "Error, no 'From' field specified"; + } + + $msgHdr = "From: " . $mFrom->scalarval() . "\n"; + $msgHdr .= "To: " . $mTo->scalarval() . "\n"; + + if ($mCc->scalarval() != "") { + $msgHdr .= "Cc: " . $mCc->scalarval() . "\n"; + } + if ($mBcc->scalarval() != "") { + $msgHdr .= "Bcc: " . $mBcc->scalarval() . "\n"; + } + if ($mMime->scalarval() != "") { + $msgHdr .= "Content-type: " . $mMime->scalarval() . "\n"; + } + $msgHdr .= "X-Mailer: XML-RPC for PHP mailer 1.0"; + + if ($err == "") { + if (!mail("", + $mSub->scalarval(), + $mBody->scalarval(), + $msgHdr) + ) { + $err = "Error, could not send the mail."; + } + } + + if ($err) { + return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err); + } else { + return new PhpXmlRpc\Response(new Value(true, Value::$xmlrpcBoolean)); + } +} + +$getallheaders_sig = array(array(Value::$xmlrpcStruct)); +$getallheaders_doc = 'Returns a struct containing all the HTTP headers received with the request. Provides limited functionality with IIS'; +function getAllHeaders_xmlrpc($req) +{ + $encoder = new PhpXmlRpc\Encoder(); + + if (function_exists('getallheaders')) { + return new PhpXmlRpc\Response($encoder->encode(getallheaders())); + } else { + $headers = array(); + // IIS: poor man's version of getallheaders + foreach ($_SERVER as $key => $val) { + if (strpos($key, 'HTTP_') === 0) { + $key = ucfirst(str_replace('_', '-', strtolower(substr($key, 5)))); + $headers[$key] = $val; + } + } + + return new PhpXmlRpc\Response($encoder->encode($headers)); + } +} + +$setcookies_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcStruct)); +$setcookies_doc = 'Sends to client a response containing a single \'1\' digit, and sets to it http cookies as received in the request (array of structs describing a cookie)'; +function setCookies($req) +{ + $encoder = new PhpXmlRpc\Encoder(); + $cookies = $req->getParam(0); + foreach ($cookies as $name => $value) { + $cookieDesc = $encoder->decode($value); + setcookie($name, @$cookieDesc['value'], @$cookieDesc['expires'], @$cookieDesc['path'], @$cookieDesc['domain'], @$cookieDesc['secure']); + } + + return new PhpXmlRpc\Response(new Value(1, Value::$xmlrpcInt)); +} + +$getcookies_sig = array(array(Value::$xmlrpcStruct)); +$getcookies_doc = 'Sends to client a response containing all http cookies as received in the request (as struct)'; +function getCookies($req) +{ + $encoder = new PhpXmlRpc\Encoder(); + return new PhpXmlRpc\Response($encoder->encode($_COOKIE)); +} + +$v1_arrayOfStructs_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcArray)); +$v1_arrayOfStructs_doc = 'This handler takes a single parameter, an array of structs, each of which contains at least three elements named moe, larry and curly, all s. Your handler must add all the struct elements named curly and return the result.'; +function v1_arrayOfStructs($req) +{ + $sno = $req->getParam(0); + $numCurly = 0; + foreach ($sno as $str) { + foreach ($str as $key => $val) { + if ($key == "curly") { + $numCurly += $val->scalarval(); + } + } + } + + return new PhpXmlRpc\Response(new Value($numCurly, Value::$xmlrpcInt)); +} + +$v1_easyStruct_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcStruct)); +$v1_easyStruct_doc = 'This handler takes a single parameter, a struct, containing at least three elements named moe, larry and curly, all <i4>s. Your handler must add the three numbers and return the result.'; +function v1_easyStruct($req) +{ + $sno = $req->getParam(0); + $moe = $sno["moe"]; + $larry = $sno["larry"]; + $curly = $sno["curly"]; + $num = $moe->scalarval() + $larry->scalarval() + $curly->scalarval(); + + return new PhpXmlRpc\Response(new Value($num, Value::$xmlrpcInt)); +} + +$v1_echoStruct_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcStruct)); +$v1_echoStruct_doc = 'This handler takes a single parameter, a struct. Your handler must return the struct.'; +function v1_echoStruct($req) +{ + $sno = $req->getParam(0); + + return new PhpXmlRpc\Response($sno); +} + +$v1_manyTypes_sig = array(array( + Value::$xmlrpcArray, Value::$xmlrpcInt, Value::$xmlrpcBoolean, + Value::$xmlrpcString, Value::$xmlrpcDouble, Value::$xmlrpcDateTime, + Value::$xmlrpcBase64, +)); +$v1_manyTypes_doc = 'This handler takes six parameters, and returns an array containing all the parameters.'; +function v1_manyTypes($req) +{ + return new PhpXmlRpc\Response(new Value( + array( + $req->getParam(0), + $req->getParam(1), + $req->getParam(2), + $req->getParam(3), + $req->getParam(4), + $req->getParam(5) + ), + Value::$xmlrpcArray + )); +} + +$v1_moderateSizeArrayCheck_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcArray)); +$v1_moderateSizeArrayCheck_doc = 'This handler takes a single parameter, which is an array containing between 100 and 200 elements. Each of the items is a string, your handler must return a string containing the concatenated text of the first and last elements.'; +function v1_moderateSizeArrayCheck($req) +{ + $ar = $req->getParam(0); + $sz = $ar->count(); + $first = $ar[0]; + $last = $ar[$sz - 1]; + + return new PhpXmlRpc\Response(new Value($first->scalarval() . + $last->scalarval(), Value::$xmlrpcString)); +} + +$v1_simpleStructReturn_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcInt)); +$v1_simpleStructReturn_doc = 'This handler takes one parameter, and returns a struct containing three elements, times10, times100 and times1000, the result of multiplying the number by 10, 100 and 1000.'; +function v1_simpleStructReturn($req) +{ + $sno = $req->getParam(0); + $v = $sno->scalarval(); + + return new PhpXmlRpc\Response(new Value( + array( + "times10" => new Value($v * 10, Value::$xmlrpcInt), + "times100" => new Value($v * 100, Value::$xmlrpcInt), + "times1000" => new Value($v * 1000, Value::$xmlrpcInt) + ), + Value::$xmlrpcStruct + )); +} + +$v1_nestedStruct_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcStruct)); +$v1_nestedStruct_doc = 'This handler takes a single parameter, a struct, that models a daily calendar. At the top level, there is one struct for each year. Each year is broken down into months, and months into days. Most of the days are empty in the struct you receive, but the entry for April 1, 2000 contains a least three elements named moe, larry and curly, all <i4>s. Your handler must add the three numbers and return the result.'; +function v1_nestedStruct($req) +{ + $sno = $req->getParam(0); + + $twoK = $sno["2000"]; + $april = $twoK["04"]; + $fools = $april["01"]; + $curly = $fools["curly"]; + $larry = $fools["larry"]; + $moe = $fools["moe"]; + + return new PhpXmlRpc\Response(new Value($curly->scalarval() + $larry->scalarval() + $moe->scalarval(), Value::$xmlrpcInt)); +} + +$v1_countTheEntities_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcString)); +$v1_countTheEntities_doc = 'This handler takes a single parameter, a string, that contains any number of predefined entities, namely <, >, & \' and ".
    Your handler must return a struct that contains five fields, all numbers: ctLeftAngleBrackets, ctRightAngleBrackets, ctAmpersands, ctApostrophes, ctQuotes.'; +function v1_countTheEntities($req) +{ + $sno = $req->getParam(0); + $str = $sno->scalarval(); + $gt = 0; + $lt = 0; + $ap = 0; + $qu = 0; + $amp = 0; + for ($i = 0; $i < strlen($str); $i++) { + $c = substr($str, $i, 1); + switch ($c) { + case ">": + $gt++; + break; + case "<": + $lt++; + break; + case "\"": + $qu++; + break; + case "'": + $ap++; + break; + case "&": + $amp++; + break; + default: + break; + } + } + + return new PhpXmlRpc\Response(new Value( + array( + "ctLeftAngleBrackets" => new Value($lt, Value::$xmlrpcInt), + "ctRightAngleBrackets" => new Value($gt, Value::$xmlrpcInt), + "ctAmpersands" => new Value($amp, Value::$xmlrpcInt), + "ctApostrophes" => new Value($ap, Value::$xmlrpcInt), + "ctQuotes" => new Value($qu, Value::$xmlrpcInt) + ), + Value::$xmlrpcStruct + )); +} + +// trivial interop tests +// http://www.xmlrpc.com/stories/storyReader$1636 + +$i_echoString_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcString)); +$i_echoString_doc = "Echoes string."; + +$i_echoStringArray_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)); +$i_echoStringArray_doc = "Echoes string array."; + +$i_echoInteger_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcInt)); +$i_echoInteger_doc = "Echoes integer."; + +$i_echoIntegerArray_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)); +$i_echoIntegerArray_doc = "Echoes integer array."; + +$i_echoFloat_sig = array(array(Value::$xmlrpcDouble, Value::$xmlrpcDouble)); +$i_echoFloat_doc = "Echoes float."; + +$i_echoFloatArray_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)); +$i_echoFloatArray_doc = "Echoes float array."; + +$i_echoStruct_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcStruct)); +$i_echoStruct_doc = "Echoes struct."; + +$i_echoStructArray_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)); +$i_echoStructArray_doc = "Echoes struct array."; + +$i_echoValue_doc = "Echoes any value back."; +$i_echoValue_sig = array(array(Value::$xmlrpcValue, Value::$xmlrpcValue)); + +$i_echoBase64_sig = array(array(Value::$xmlrpcBase64, Value::$xmlrpcBase64)); +$i_echoBase64_doc = "Echoes base64."; + +$i_echoDate_sig = array(array(Value::$xmlrpcDateTime, Value::$xmlrpcDateTime)); +$i_echoDate_doc = "Echoes dateTime."; + +function i_echoParam($req) +{ + $s = $req->getParam(0); + + return new PhpXmlRpc\Response($s); +} + +function i_echoString($req) +{ + return i_echoParam($req); +} + +function i_echoInteger($req) +{ + return i_echoParam($req); +} + +function i_echoFloat($req) +{ + return i_echoParam($req); +} + +function i_echoStruct($req) +{ + return i_echoParam($req); +} + +function i_echoStringArray($req) +{ + return i_echoParam($req); +} + +function i_echoIntegerArray($req) +{ + return i_echoParam($req); +} + +function i_echoFloatArray($req) +{ + return i_echoParam($req); +} + +function i_echoStructArray($req) +{ + return i_echoParam($req); +} + +function i_echoValue($req) +{ + return i_echoParam($req); +} + +function i_echoBase64($req) +{ + return i_echoParam($req); +} + +function i_echoDate($req) +{ + return i_echoParam($req); +} + +$i_whichToolkit_sig = array(array(Value::$xmlrpcStruct)); +$i_whichToolkit_doc = "Returns a struct containing the following strings: toolkitDocsUrl, toolkitName, toolkitVersion, toolkitOperatingSystem."; + +function i_whichToolkit($req) +{ + global $SERVER_SOFTWARE; + $ret = array( + "toolkitDocsUrl" => "http://phpxmlrpc.sourceforge.net/", + "toolkitName" => PhpXmlRpc\PhpXmlRpc::$xmlrpcName, + "toolkitVersion" => PhpXmlRpc\PhpXmlRpc::$xmlrpcVersion, + "toolkitOperatingSystem" => isset($SERVER_SOFTWARE) ? $SERVER_SOFTWARE : $_SERVER['SERVER_SOFTWARE'], + ); + + $encoder = new PhpXmlRpc\Encoder(); + return new PhpXmlRpc\Response($encoder->encode($ret)); +} + +$object = new xmlrpcServerMethodsContainer(); +$signatures = array( + "examples.getStateName" => array( + "function" => "findState", + "signature" => $findstate_sig, + "docstring" => $findstate_doc, + ), + "examples.sortByAge" => array( + "function" => "ageSorter", + "signature" => $agesorter_sig, + "docstring" => $agesorter_doc, + ), + "examples.addtwo" => array( + "function" => "addTwo", + "signature" => $addtwo_sig, + "docstring" => $addtwo_doc, + ), + "examples.addtwodouble" => array( + "function" => "addTwoDouble", + "signature" => $addtwodouble_sig, + "docstring" => $addtwodouble_doc, + ), + "examples.stringecho" => array( + "function" => "stringEcho", + "signature" => $stringecho_sig, + "docstring" => $stringecho_doc, + ), + "examples.echo" => array( + "function" => "echoBack", + "signature" => $echoback_sig, + "docstring" => $echoback_doc, + ), + "examples.decode64" => array( + "function" => "echoSixtyFour", + "signature" => $echosixtyfour_sig, + "docstring" => $echosixtyfour_doc, + ), + "examples.invertBooleans" => array( + "function" => "bitFlipper", + "signature" => $bitflipper_sig, + "docstring" => $bitflipper_doc, + ), + // signature omitted on purpose + "tests.generatePHPWarning" => array( + "function" => array($object, "phpWarningGenerator"), + ), + // signature omitted on purpose + "tests.raiseException" => array( + "function" => array($object, "exceptionGenerator"), + ), + // Greek word 'kosme'. NB: NOT a valid ISO8859 string! + // NB: we can only register this when setting internal encoding to UTF-8, or it will break system.listMethods + "tests.utf8methodname." . 'κόσμε' => array( + "function" => "stringEcho", + "signature" => $stringecho_sig, + "docstring" => $stringecho_doc, + ), + /*"tests.iso88591methodname." . chr(224) . chr(252) . chr(232) => array( + "function" => "stringEcho", + "signature" => $stringecho_sig, + "docstring" => $stringecho_doc, + ),*/ + "examples.getallheaders" => array( + "function" => 'getAllHeaders_xmlrpc', + "signature" => $getallheaders_sig, + "docstring" => $getallheaders_doc, + ), + "examples.setcookies" => array( + "function" => 'setCookies', + "signature" => $setcookies_sig, + "docstring" => $setcookies_doc, + ), + "examples.getcookies" => array( + "function" => 'getCookies', + "signature" => $getcookies_sig, + "docstring" => $getcookies_doc, + ), + "mail.send" => array( + "function" => "mailSend", + "signature" => $mailsend_sig, + "docstring" => $mailsend_doc, + ), + "validator1.arrayOfStructsTest" => array( + "function" => "v1_arrayOfStructs", + "signature" => $v1_arrayOfStructs_sig, + "docstring" => $v1_arrayOfStructs_doc, + ), + "validator1.easyStructTest" => array( + "function" => "v1_easyStruct", + "signature" => $v1_easyStruct_sig, + "docstring" => $v1_easyStruct_doc, + ), + "validator1.echoStructTest" => array( + "function" => "v1_echoStruct", + "signature" => $v1_echoStruct_sig, + "docstring" => $v1_echoStruct_doc, + ), + "validator1.manyTypesTest" => array( + "function" => "v1_manyTypes", + "signature" => $v1_manyTypes_sig, + "docstring" => $v1_manyTypes_doc, + ), + "validator1.moderateSizeArrayCheck" => array( + "function" => "v1_moderateSizeArrayCheck", + "signature" => $v1_moderateSizeArrayCheck_sig, + "docstring" => $v1_moderateSizeArrayCheck_doc, + ), + "validator1.simpleStructReturnTest" => array( + "function" => "v1_simpleStructReturn", + "signature" => $v1_simpleStructReturn_sig, + "docstring" => $v1_simpleStructReturn_doc, + ), + "validator1.nestedStructTest" => array( + "function" => "v1_nestedStruct", + "signature" => $v1_nestedStruct_sig, + "docstring" => $v1_nestedStruct_doc, + ), + "validator1.countTheEntities" => array( + "function" => "v1_countTheEntities", + "signature" => $v1_countTheEntities_sig, + "docstring" => $v1_countTheEntities_doc, + ), + "interopEchoTests.echoString" => array( + "function" => "i_echoString", + "signature" => $i_echoString_sig, + "docstring" => $i_echoString_doc, + ), + "interopEchoTests.echoStringArray" => array( + "function" => "i_echoStringArray", + "signature" => $i_echoStringArray_sig, + "docstring" => $i_echoStringArray_doc, + ), + "interopEchoTests.echoInteger" => array( + "function" => "i_echoInteger", + "signature" => $i_echoInteger_sig, + "docstring" => $i_echoInteger_doc, + ), + "interopEchoTests.echoIntegerArray" => array( + "function" => "i_echoIntegerArray", + "signature" => $i_echoIntegerArray_sig, + "docstring" => $i_echoIntegerArray_doc, + ), + "interopEchoTests.echoFloat" => array( + "function" => "i_echoFloat", + "signature" => $i_echoFloat_sig, + "docstring" => $i_echoFloat_doc, + ), + "interopEchoTests.echoFloatArray" => array( + "function" => "i_echoFloatArray", + "signature" => $i_echoFloatArray_sig, + "docstring" => $i_echoFloatArray_doc, + ), + "interopEchoTests.echoStruct" => array( + "function" => "i_echoStruct", + "signature" => $i_echoStruct_sig, + "docstring" => $i_echoStruct_doc, + ), + "interopEchoTests.echoStructArray" => array( + "function" => "i_echoStructArray", + "signature" => $i_echoStructArray_sig, + "docstring" => $i_echoStructArray_doc, + ), + "interopEchoTests.echoValue" => array( + "function" => "i_echoValue", + "signature" => $i_echoValue_sig, + "docstring" => $i_echoValue_doc, + ), + "interopEchoTests.echoBase64" => array( + "function" => "i_echoBase64", + "signature" => $i_echoBase64_sig, + "docstring" => $i_echoBase64_doc, + ), + "interopEchoTests.echoDate" => array( + "function" => "i_echoDate", + "signature" => $i_echoDate_sig, + "docstring" => $i_echoDate_doc, + ), + "interopEchoTests.whichToolkit" => array( + "function" => "i_whichToolkit", + "signature" => $i_whichToolkit_sig, + "docstring" => $i_whichToolkit_doc, + ), + + 'tests.getStateName.2' => $findstate2_sig, + 'tests.getStateName.3' => $findstate3_sig, + 'tests.getStateName.4' => $findstate4_sig, + 'tests.getStateName.5' => $findstate5_sig, + 'tests.getStateName.6' => $findstate6_sig, + 'tests.getStateName.7' => $findstate7_sig, + 'tests.getStateName.8' => $findstate8_sig, + 'tests.getStateName.9' => $findstate9_sig, + 'tests.getStateName.10' => $findstate10_sig, + 'tests.getStateName.11' => $findstate11_sig, + + 'tests.getStateName.12' => array( + "function" => "findStateWithNulls", + "signature" => $findstate12_sig, + "docstring" => $findstate_doc, + ), + + 'tests.returnPhpObject' => $returnObj_sig, +); + +$signatures = array_merge($signatures, $moreSignatures); + +// enable support for the NULL extension +PhpXmlRpc\PhpXmlRpc::$xmlrpc_null_extension = true; + +$s = new PhpXmlRpc\Server($signatures, false); +$s->setdebug(3); +$s->compress_response = true; + +// out-of-band information: let the client manipulate the server operations. +// we do this to help the testsuite script: do not reproduce in production! +if (isset($_GET['RESPONSE_ENCODING'])) { + $s->response_charset_encoding = $_GET['RESPONSE_ENCODING']; +} +if (isset($_GET['DETECT_ENCODINGS'])) { + PhpXmlRpc\PhpXmlRpc::$xmlrpc_detectencodings = $_GET['DETECT_ENCODINGS']; +} +if (isset($_GET['EXCEPTION_HANDLING'])) { + $s->exception_handling = $_GET['EXCEPTION_HANDLING']; +} +$s->service(); +// that should do all we need! + +// out-of-band information: let the client manipulate the server operations. +// we do this to help the testsuite script: do not reproduce in production! +if (isset($_COOKIE['PHPUNIT_SELENIUM_TEST_ID']) && extension_loaded('xdebug')) { + include_once __DIR__ . "/../../vendor/phpunit/phpunit-selenium/PHPUnit/Extensions/SeleniumCommon/append.php"; +} diff --git a/lib/phpxmlrpc/demo/vardemo.php b/lib/phpxmlrpc/demo/vardemo.php new file mode 100644 index 0000000..3c9812a --- /dev/null +++ b/lib/phpxmlrpc/demo/vardemo.php @@ -0,0 +1,95 @@ + +xmlrpc + +Testing value serialization\n"; + +$v = new PhpXmlRpc\Value(23, "int"); +print "
    " . htmlentities($v->serialize()) . "
    "; +$v = new PhpXmlRpc\Value("What are you saying? >> << &&"); +print "
    " . htmlentities($v->serialize()) . "
    "; + +$v = new PhpXmlRpc\Value( + array( + new PhpXmlRpc\Value("ABCDEFHIJ"), + new PhpXmlRpc\Value(1234, 'int'), + new PhpXmlRpc\Value(1, 'boolean'), + ), + "array" +); + +print "
    " . htmlentities($v->serialize()) . "
    "; + +$v = new PhpXmlRpc\Value( + array( + "thearray" => new PhpXmlRpc\Value( + array( + new PhpXmlRpc\Value("ABCDEFHIJ"), + new PhpXmlRpc\Value(1234, 'int'), + new PhpXmlRpc\Value(1, 'boolean'), + new PhpXmlRpc\Value(0, 'boolean'), + new PhpXmlRpc\Value(true, 'boolean'), + new PhpXmlRpc\Value(false, 'boolean'), + ), + "array" + ), + "theint" => new PhpXmlRpc\Value(23, 'int'), + "thestring" => new PhpXmlRpc\Value("foobarwhizz"), + "thestruct" => new PhpXmlRpc\Value( + array( + "one" => new PhpXmlRpc\Value(1, 'int'), + "two" => new PhpXmlRpc\Value(2, 'int'), + ), + "struct" + ), + ), + "struct" +); + +print "
    " . htmlentities($v->serialize()) . "
    "; + +$w = new PhpXmlRpc\Value(array($v, new PhpXmlRpc\Value("That was the struct!")), "array"); + +print "
    " . htmlentities($w->serialize()) . "
    "; + +$w = new PhpXmlRpc\Value("Mary had a little lamb, +Whose fleece was white as snow, +And everywhere that Mary went +the lamb was sure to go. + +Mary had a little lamb +She tied it to a pylon +Ten thousand volts went down its back +And turned it into nylon", "base64" +); +print "
    " . htmlentities($w->serialize()) . "
    "; +print "
    Value of base64 string is: '" . $w->scalarval() . "'
    "; + +$req->method(''); +$req->addParam(new PhpXmlRpc\Value("41", "int")); + +print "

    Testing request serialization

    \n"; +$op = $req->serialize(); +print "
    " . htmlentities($op) . "
    "; + +print "

    Testing ISO date format

    \n";
    +
    +$t = time();
    +$date = PhpXmlRpc\Helper\Date::iso8601Encode($t);
    +print "Now is $t --> $date\n";
    +print "Or in UTC, that is " . PhpXmlRpc\Helper\Date::iso8601Encode($t, 1) . "\n";
    +$tb = PhpXmlRpc\Helper\Date::iso8601Decode($date);
    +print "That is to say $date --> $tb\n";
    +print "Which comes out at " . PhpXmlRpc\Helper\Date::iso8601Encode($tb) . "\n";
    +print "Which was the time in UTC at " . PhpXmlRpc\Helper\Date::iso8601Encode($date, 1) . "\n";
    +
    +print "
    \n"; + +?> + + diff --git a/lib/phpxmlrpc/doc/api_changes_v4.md b/lib/phpxmlrpc/doc/api_changes_v4.md new file mode 100644 index 0000000..57b4eb3 --- /dev/null +++ b/lib/phpxmlrpc/doc/api_changes_v4.md @@ -0,0 +1,237 @@ +API Changes between library versions 3 and 4 +============================================ + +Class loading +------------- + +It is not necessary any more to include the files xmlrpc.inc, xmlrpcs.inc and xmlrpc_wrappers.inc to have the +library classes available. + +Instead, it is recommended to rely on class autoloading. + +* If you are using Composer, just install the library by declaring it as dependency for your project in composer.json + + "require": { + ..., + "phpxmlrpc/phpxmlrpc": "~4.0" + }, + +* If you do not use Composer, an autoloader for the library can be found in src/Atuloader.php. + The php example files in the demo/client folder do make use of it. + Example code to set up the autoloader: + + include_once . "/src/Autoloader.php"; + PhpXmlRpc\Autoloader::register(); + + +* If you still include manually xmlrpc.inc, xmlrpcs.inc or xmlrpc_wrappers.inc, you will not need to set up + class autoloading, as those files do include all the source files for the library classes + + +New class naming +---------------- + +All classes have ben renamed, are now properly namespaced and follow the CamelCase naming convention. +Existing class methods and members have been preserved; all new method names follow camelCase. + +Conversion table: + +| Old class | New class | Notes | +| ------------- | ------------------ | ------------------------------------- | +| xmlrpc_client | PhpXmlRpc\Client | | +| xmlrpc_server | PhpXmlRpc\Server | Removed method: echoInput | +| xmlrpcmsg | PhpXmlRpc\Request | | +| xmlrpcresp | PhpXmlRpc\Response | | +| xmlrpcval | PhpXmlRpc\Value | Removed methods: serializeval, getval | + + +New class methods +----------------- + +In case you had extended the classes of the library and added methods to the subclasses, you might find that your +implementation clashes with the new one if you implemented: + + +| Class | Method | Notes | +| --------- | ------------ | --------------------------------------- | +| xmlrpcval | count | implements interface: Countable | +| xmlrpcval | getIterator | implements interface: IteratorAggregate | +| xmlrpcval | offsetExists | implements interface: ArrayAccess | +| xmlrpcval | offsetGet | implements interface: ArrayAccess | +| xmlrpcval | offsetSet | implements interface: ArrayAccess | +| xmlrpcval | offsetUnset | implements interface: ArrayAccess | + + +Global variables cleanup +------------------------ + +All variables in the global scope have been moved into classes. + +Conversion table: + +| Old variable | New variable | Notes | +| ------------------------ | ------------------------------------------- | --------- | +| _xmlrpc_debuginfo | PhpXmlRpc\Server::$_xmlrpc_debuginfo | protected | +| _xmlrpcs_capabilities | NOT AVAILABLE YET | | +| _xmlrpcs_dmap | NOT AVAILABLE YET | | +| _xmlrpcs_occurred_errors | PhpXmlRpc\Server::$_xmlrpcs_occurred_errors | protected | +| _xmlrpcs_prev_ehandler | PhpXmlRpc\Server::$_xmlrpcs_prev_ehandler | protected | +| xmlrpcWPFObjHolder | PhpXmlRpc\Wrapper::$objHolder | | +| ... | | | + + +Global functions cleanup +------------------------ + +Most functions in the global scope have been moved into classes. +Some have been slightly changed. + +| Old function | New function | Notes | +| -------------------------------- | ------------------------------------------- | ------------------------------------------------------ | +| build_client_wrapper_code | none | | +| build_remote_method_wrapper_code | PhpXmlRpc\Wrapper->buildWrapMethodSource | signature changed | +| decode_chunked | PhpXmlRpc\Helper\Http::decodeChunked | | +| guess_encoding | PhpXmlRpc\Helper\XMLParser::guessEncoding | | +| has_encoding | PhpXmlRpc\Helper\XMLParser::hasEncoding | | +| is_valid_charset | PhpXmlRpc\Helper\Charset->isValidCharset | this method is not static, you need a Charset obj | +| iso8601_decode | PhpXmlRpc\Helper\Date::iso8601Decode | | +| iso8601_encode | PhpXmlRpc\Helper\Date::iso8601Encode | | +| php_2_xmlrpc_type | PhpXmlRpc\Wrapper->php2XmlrpcType | this method is not static, you need a Wrapper obj | +| php_xmlrpc_decode | PhpXmlRpc\Encoder->decode | this method is not static, you need an Encoder obj | +| php_xmlrpc_decode_xml | PhpXmlRpc\Encoder->decodeXml | this method is not static, you need an Encoder obj | +| php_xmlrpc_encode | PhpXmlRpc\Encoder->encode | this method is not static, you need an Encoder obj | +| wrap_php_class | PhpXmlRpc\Wrapper->wrapPhpClass | returns closures instead of function names by default | +| wrap_php_function | PhpXmlRpc\Wrapper->wrapPhpFunction | returns closures instead of function names by default | +| wrap_xmlrpc_method | PhpXmlRpc\Wrapper->wrapXmrlpcMethod | returns closures instead of function names by default | +| wrap_xmlrpc_server | PhpXmlRpc\Wrapper->wrapXmrlpcServer | returns closures instead of function names by default; | +| | | returns an array ready for usage in dispatch map | +| xmlrpc_2_php_type | PhpXmlRpc\Wrapper->Xmlrpc2phpType | this method is not static, you need a Wrapper obj | +| xmlrpc_debugmsg | PhpXmlRpc\Server->xmlrpc_debugmsg | | +| xmlrpc_encode_entitites | PhpXmlRpc\Helper\Charset->encodeEntitities | this method is not static, you need a Charset obj | + + +Character sets and encoding +--------------------------- + +The default character set used by the library to deliver data to your app is now UTF8. +It is also the character set that the library expects data from your app to be in (including method names). +The value can be changed (to either US-ASCII or ISO-8859-1) by setting the desired value to + PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding + +Usage of closures for wrapping +------------------------------ + +... + + +Differences in server behaviour +------------------------------- + +The results for calls to system.listMethods and system.getCapabilities can not be set anymore via changes to +global variables. + + +Other +----- + +* when serialize() is invoked on a response and its payload can not be serialized, an exception is thrown instead of + ending all execution + +* all error messages now mention the class and method which generated them + +* all library source code has been moved to the src/ directory + +* all source code has been reformatted according to modern PSR standards + + +Enabling compatibility with legacy code +--------------------------------------- + +If you have code which relies on version 3 of the phpxmlrpc API, you *should* be able to use version 4 as a drop-in +replacement, regardless of all of the changes mentioned above. + +The magic happens via the xmlrpc.inc, xmlrpcs.inc and xmlrpc_wrappers.inc files, which have been kept solely for +the purpose of backwards compatibility (you might notice that they are still in the 'lib' directory, whereas all of +the refactored code now sits in the 'src' directory). + +Of course, some minor changes where inevitable, and backwards compatibility can not be guaranteed at 100%. +Below is the list of all known changes and possible pitfalls when enabling 'compatibility mode'. + +### Default character set used for application data + +* when including the xmlrpc.inc file, the defalt character set used by the lib to give data to your app gets switched + back to ISO-8859-1, as it was in previous versions + +* if yor app used to change that value, you will need to add one line to your code, to make sure it is properly used + + // code as was before + include('xmlrpc.inc'); + $GLOBALS['xmlrpc_internalencoding'] = 'UTF-8'; + // new line needed now + PhpXmlRpc\PhpXmlRpc::importGlobals(); + +### Usage of global variables + +* ALL global variables which existed after including xmlrpc.inc in version 3 still do exist after including it in v. 4 + +* Code which relies on using (as in 'reading') their value will keep working unchanged + +* Changing the value of some of those variables does not have any effect anymore on library operation. + This is true for: + + $GLOBALS['xmlrpcI4'] + $GLOBALS['xmlrpcInt'] + $GLOBALS['xmlrpcBoolean'] + $GLOBALS['xmlrpcDouble'] + $GLOBALS['xmlrpcString'] + $GLOBALS['xmlrpcDatetTme'] + $GLOBALS['xmlrpcBase64'] + $GLOBALS['xmlrpcArray'] + $GLOBALS['xmlrpcStruct'] + $GLOBALS['xmlrpcValue'] + $GLOBALS['xmlrpcNull'] + $GLOBALS['xmlrpcTypes'] + $GLOBALS['xmlrpc_valid_parents'] + $GLOBALS['xml_iso88591_Entities'] + +* Changing the value of the other global variables will still have an effect on operation of the library, but only after + a call to PhpXmlRpc::importGlobals() + + Example: + + // code as was before + include('xmlrpc.inc'); + $GLOBALS['xmlrpc_null_apache_encoding'] = true; + // new line needed now + PhpXmlRpc\PhpXmlRpc::importGlobals(); + + Alternative solution: + + include('xmlrpc.inc'); + PhpXmlRpc\PhpXmlRpc::$xmlrpc_null_apache_encoding = true; + +* Not all variables which existed after including xmlrpcs.inc in version 3 are available + + - $GLOBALS['_xmlrpcs_prev_ehandler'] has been replaced with protected static var PhpXmlRpc\Server::$_xmlrpcs_prev_ehandler + and is thus not available any more + + - same for $GLOBALS['_xmlrpcs_occurred_errors'] + + - same for $GLOBALS['_xmlrpc_debuginfo'] + + - $GLOBALS['_xmlrpcs_capabilities'] and $GLOBALS['_xmlrpcs_dmap'] have been removed + +### Using typeof/class-name checks in your code + +* if you are checking the types of returned objects, your checks will most likely fail. + This is due to the fact that 'old' classes extend the 'new' versions, but library code that creates object + instances will return the new classes. + + Example: + + is_a(php_xmlrpc_encode('hello world'), 'xmlrpcval') => false + is_a(php_xmlrpc_encode('hello world'), 'PhpXmlRpc\Value') => true + +### server behaviour can not be changed by setting global variables (the ones starting with _xmlrpcs_ ) + +might be fixed later? diff --git a/lib/phpxmlrpc/doc/build/custom.fo.xsl b/lib/phpxmlrpc/doc/build/custom.fo.xsl new file mode 100644 index 0000000..b1964c0 --- /dev/null +++ b/lib/phpxmlrpc/doc/build/custom.fo.xsl @@ -0,0 +1,103 @@ + + + + + + + + + + +1 +no +ansi +0 +1 +php +A4 +1 + + + 80% + + + + + + + + + + + + + + + + + + + + + + + + + + + ( void ) + + + ( ) + + + + + + ( ... ) + + + + + + + ( + + + + + + + + + + + , + + + ) + + + + + + + + + + + + = + + + + + \ No newline at end of file diff --git a/lib/phpxmlrpc/doc/build/custom.xsl b/lib/phpxmlrpc/doc/build/custom.xsl new file mode 100644 index 0000000..c96cf55 --- /dev/null +++ b/lib/phpxmlrpc/doc/build/custom.xsl @@ -0,0 +1,91 @@ + + + + + + + + + + +no +ansi +xmlrpc.css +0 + + + + + + + + + + ( + + + + + + + + + + + + void ) + + + + ... + ) + + + + + + + , + + + ) + + + + + + + + + + + + + + + + + + + + + + + + = + + + + + \ No newline at end of file diff --git a/lib/phpxmlrpc/doc/manual/images/debugger.gif b/lib/phpxmlrpc/doc/manual/images/debugger.gif new file mode 100644 index 0000000..492c2ca Binary files /dev/null and b/lib/phpxmlrpc/doc/manual/images/debugger.gif differ diff --git a/lib/phpxmlrpc/doc/manual/images/progxmlrpc.s.gif b/lib/phpxmlrpc/doc/manual/images/progxmlrpc.s.gif new file mode 100644 index 0000000..d1dcea5 Binary files /dev/null and b/lib/phpxmlrpc/doc/manual/images/progxmlrpc.s.gif differ diff --git a/lib/phpxmlrpc/doc/manual/phpxmlrpc_manual.adoc b/lib/phpxmlrpc/doc/manual/phpxmlrpc_manual.adoc new file mode 100644 index 0000000..63ac427 --- /dev/null +++ b/lib/phpxmlrpc/doc/manual/phpxmlrpc_manual.adoc @@ -0,0 +1,2333 @@ += XML-RPC for PHP +:revision: 4.0.0 +:keywords: xmlrpc, xml, rpc, webservices, http +:toc: left +:imagesdir: images +:source-highlighter: highlightjs + + +[preface] +== Introduction + +WARNING: THIS MANUAL HAS NOT YET BEEN UPDATED TO REFLECT ALL THE CHANGES WHICH HAVE MADE IN VERSION 4. *DO NOT USE* FOR NOW. You can find the API documentation at link:$$http://gggeek.github.io/phpxmlrpc/doc-4/api/index.html$$[http://gggeek.github.io/phpxmlrpc/doc-4/api/index.html] + +This collection of PHP classes provides a framework for writing XML-RPC clients and servers in PHP. + +Main goals of the project are ease of use, flexibility and completeness. + +The original author is Edd Dumbill of link:$$http://usefulinc.com/$$[Useful Information Company]. As of the 1.0 stable + release, the project was opened to wider involvement and moved to + link:$$http://phpxmlrpc.sourceforge.net/$$[SourceForge]; later, to link:$$https://github.com/gggeek/phpxmlrpc$$[Github] + +XML-RPC is a format devised by link:$$http://www.userland.com/$$[Userland Software] for achieving remote procedure call + via XML using HTTP as the transport. XML-RPC has its own web site, link:$$http://www.xmlrpc.com/$$[www.xmlrpc.com] + +A list of XML-RPC implementations for other languages such as Perl and Python can be found on the + link:$$http://www.xmlrpc.com/$$[www.xmlrpc.com] site. + +=== Acknowledgements + +Daniel E. Baumann + +James Bercegay + +Leon Blackwell + +Stephane Bortzmeyer + +Daniel Convissor + +Geoffrey T. Dairiki + +Stefan Esser + +James Flemer + +Ernst de Haan + +Tom Knight + +Axel Kollmorgen + +Peter Kocks + +Daniel Krippner + +{empty}S. Kuip + +{empty}A. Lambert + +Frederic Lecointre + +Dan Libby + +Arnaud Limbourg + +Ernest MacDougal Campbell III + +Lukasz Mach + +Kjartan Mannes + +Ben Margolin + +Nicolay Mausz + +Justin Miller + +Jan Pfeifer + +Giancarlo Pinerolo + +Peter Russel + +Jean-Jacques Sarton + +Viliam Simko + +Idan Sofer + +Douglas Squirrel + +Heiko Stübner + +Anatoly Techtonik + +Tommaso Trani + +Eric van der Vlist + +Christian Wenz + +Jim Winstead + +Przemyslaw Wroblewski + +Bruno Zanetti Melotti + + +[[requirements]] +== System Requirements + +The library has been designed with goals of flexibility and backward compatibility. As such, it supports a wide range of + PHP installs. Note that not all features of the lib are available in every configuration. + +The __minimum supported__ PHP version is 5.3. + +If you wish to use HTTPS or HTTP 1.1 to communicate with remote servers, or to use NTLM authentication, you need the + *curl* extension compiled into your PHP installation. + +If you wish to receive XML-RPC requests or responses in any other character set than US-ASCII, ISO-8859-1 or UTF-8, you + will need the *mbstring* extension compiled into your PHP installation. + +The *xmlrpc* native extension is not required to be compiled into your PHP installation, but if it is, there will be no + interference with the operation of this library. + + +[[manifest]] +== Files in the distribution + +debugger/*:: a graphical debugger which can be used to test calls to xmlrpc servers + +demo/*:: example code for implementing both xmlrpc client and server functionality + +doc/*:: the documentation/ this manual, and the list of API changes between versions 3 and 4 + +extras/rsakey.pem:: A test certificate key for the SSL support, which can be used to generate dummy certificates. It has + the passphrase "test." + +extras/test.pl, extras/test.py:: Perl and Python programs to exercise server.php to test that some of the methods work. + +extras/workspace.testPhpServer.fttb:: Frontier scripts to exercise the demo server. Thanks to Dave Winer for permission + to include these. See link:$$http://www.xmlrpc.com/discuss/msgReader$853$$[Dave's announcement of these.] + +lib/*:: a compatibility layer for applications which still rely on version 3 of the API + +src/*:: the XML-RPC library classes. You can autoload these via Composer, or via a dedicated Autoloader class + +tests/*:: the test suite for the library, written using PhpUnit, and the configuration to run it on Travis + + +[[bugs]] + +== Known Bugs + +Known bugs are tracked using the link:$$https://github.com/gggeek/phpxmlrpc/issues$$[GitHub issue tracker] + +== Known limitations + +This started out as a bare framework. Many "nice" bits have been put in over time, but backwards compatibility has + always taken precedence over API cleanups. As such, you might find some API choices questionable. + +Specifically, very little type validation or coercion has been put in. PHP being a loosely-typed language, this is + going to have to be done explicitly (in other words: you can call a lot of library functions passing them arguments + of the wrong type and receive an error message only much further down the code, where it will be difficult to + understand). + +dateTime.iso8601 is supported opaquely. It can't be done natively as the XML-RPC specification explicitly forbids + passing of timezone specifiers in ISO8601 format dates. You can, however, use the PhpXmlRpc\Helper\Date class to do + the encoding and decoding for you. + +Very little HTTP response checking is performed (e.g. HTTP redirects are not followed and the Content-Length HTTP + header, mandated by the xml-rpc spec, is not validated); cookie support still involves quite a bit of coding on the + part of the user. + +Support for receiving from servers version 1 cookies (i.e. conforming to RFC 2965) is quite incomplete, and might cause + unforeseen errors. + + +[[support]] + +== Support + + +=== Online Support + +XML-RPC for PHP is offered "as-is" without any warranty or commitment to support. However, informal advice and help is + available via the XML-RPC for PHP website and mailing list. + +* The __XML-RPC for PHP__ development is hosted on + link:$$https://github.com/gggeek/phpxmlrpc$$[github.com/gggeek/phpxmlrpc]. Bugs, feature requests and patches can be + posted to the link:$$https://github.com/gggeek/phpxmlrpc/issues$$[project's website]. + +* The __PHP XML-RPC interest mailing list__ is run by the original author. More details + link:$$http://lists.gnomehack.com/mailman/listinfo/phpxmlrpc$$[can be found here]. + + +[[jellyfish]] + +=== The Jellyfish Book + +image::progxmlrpc.s.gif[The Jellyfish Book] +Together with Simon St.Laurent and Joe Johnston, Edd Dumbill wrote a book on XML-RPC for O'Reilly and Associates on + XML-RPC. It features a rather fetching jellyfish on the cover. + +Complete details of the book are link:$$http://www.oreilly.com/catalog/progxmlrpc/$$[available from O'Reilly's web site.] + +Edd is responsible for the chapter on PHP, which includes a worked example of creating a forum server, and hooking it up + the O'Reilly's link:$$http://meerkat.oreillynet.com/$$[Meerkat] service in order to allow commenting on news stories + from around the Web. + +If you've benefited from the effort that has been put into writing this software, then please consider buying the book! + + +[[apidocs]] + +== Class documentation + + +==== Notes on types + +===== int + +The type i4 is accepted as a synonym + for int when creating xmlrpcval objects. The + xml parsing code will always convert i4 to + int: int is regarded + by this implementation as the canonical name for this type. + +The type i8 on the other hand is considered as a separate type. + Note that the library will never output integers as 'i8' on its own, + even when php is compiled in 64-bit mode. + +===== base64 + +Base 64 encoding is performed transparently to the caller when + using this type. Decoding is also transparent. Therefore you ought + to consider it as a "binary" data type, for use when you want to + pass data that is not 7-bit clean. + +===== boolean + +The php values ++true++ and + ++1++ map to ++true++. All other + values (including the empty string) are converted to + ++false++. + +===== string + +Characters <, >;, ', ", &, are encoded using their + entity reference as < > ' " and + & All other characters outside of the ASCII range are + encoded using their character reference representation (e.g. + È for é). The XML-RPC spec recommends only encoding + ++< >++ but this implementation goes further, + for reasons explained by link:$$http://www.w3.org/TR/REC-xml#syntax$$[the XML 1.0 recommendation]. In particular, using character reference + representation has the advantage of producing XML that is valid + independently of the charset encoding assumed. + +===== null + +There is no support for encoding ++null++ + values in the XML-RPC spec, but at least a couple of extensions (and + many toolkits) do support it. Before using ++null++ + values in your messages, make sure that the responding party accepts + them, and uses the same encoding convention (see ...). + +[[xmlrpcval-creation]] + +==== Xmlrpcval creation + +The constructor is the normal way to create an + xmlrpcval. The constructor can take these + forms: + +xmlrpcvalnew + xmlrpcval xmlrpcvalnew + xmlrpcval string $stringVal xmlrpcvalnew + xmlrpcval mixed $scalarVal string$scalartyp xmlrpcvalnew + xmlrpcval array $arrayVal string $arraytyp The first constructor creates an empty value, which must be + altered using the methods addScalar, + addArray or addStruct before + it can be used. + +The second constructor creates a simple string value. + +The third constructor is used to create a scalar value. The + second parameter must be a name of an XML-RPC type. Valid types are: + "++int++", "++boolean++", + "++string++", "++double++", + "++dateTime.iso8601++", "++base64++" or + "null". + +Examples: + +[source, php] +---- + +$myInt = new xmlrpcval(1267, "int"); +$myString = new xmlrpcval("Hello, World!", "string"); +$myBool = new xmlrpcval(1, "boolean"); +$myString2 = new xmlrpcval(1.24, "string"); // note: this will serialize a php float value as xmlrpc string + +---- + +The fourth constructor form can be used to compose complex + XML-RPC values. The first argument is either a simple array in the + case of an XML-RPC array or an associative + array in the case of a struct. The elements of + the array __must be xmlrpcval objects themselves__. + +The second parameter must be either "++array++" + or "++struct++". + +Examples: + +[source, php] +---- + +$myArray = new xmlrpcval( + array( + new xmlrpcval("Tom"), + new xmlrpcval("Dick"), + new xmlrpcval("Harry") + ), + "array"); + +// recursive struct +$myStruct = new xmlrpcval( + array( + "name" => new xmlrpcval("Tom", "string"), + "age" => new xmlrpcval(34, "int"), + "address" => new xmlrpcval( + array( + "street" => new xmlrpcval("Fifht Ave", "string"), + "city" => new xmlrpcval("NY", "string") + ), + "struct") + ), + "struct"); + +---- + +See the file ++vardemo.php++ in this distribution + for more examples. + +[[xmlrpc-client]] + +==== Xmlrpc-client creation + +The constructor accepts one of two possible syntaxes: + +xmlrpc_clientnew + xmlrpc_clientstring$server_urlxmlrpc_clientnew + xmlrpc_clientstring$server_pathstring$server_hostnameint$server_port80string$transport'http'Here are a couple of usage examples of the first form: + + +[source, php] +---- + +$client = new xmlrpc_client("http://phpxmlrpc.sourceforge.net/server.php"); +$another_client = new xmlrpc_client("https://james:bond@secret.service.com:443/xmlrpcserver?agent=007"); + +---- + +The second syntax does not allow to express a username and + password to be used for basic HTTP authorization as in the second + example above, but instead it allows to choose whether xmlrpc calls + will be made using the HTTP 1.0 or 1.1 protocol. + +Here's another example client set up to query Userland's XML-RPC + server at __betty.userland.com__: + +[source, php] +---- + +$client = new xmlrpc_client("/RPC2", "betty.userland.com", 80); + +---- + +The server_port parameter is optional, + and if omitted will default to 80 when using HTTP and 443 when using + HTTPS (see the <> method + below). + +The transport parameter is optional, and + if omitted will default to 'http'. Allowed values are either + 'http', 'https' or + 'http11'. Its value can be overridden with every call + to the send method. See the + send method below for more details about the + meaning of the different values. + + +[[xmlrpc-server]] + +=== xmlrpc_server + +The implementation of this class has been kept as simple to use as + possible. The constructor for the server basically does all the work. + Here's a minimal example: + + +[source, php] +---- + + function foo ($xmlrpcmsg) { + ... + return new xmlrpcresp($some_xmlrpc_val); + } + + class bar { + function foobar($xmlrpcmsg) { + ... + return new xmlrpcresp($some_xmlrpc_val); + } + } + + $s = new xmlrpc_server( + array( + "examples.myFunc1" => array("function" => "foo"), + "examples.myFunc2" => array("function" => "bar::foobar"), + )); + +---- + +This performs everything you need to do with a server. The single + constructor argument is an associative array from xmlrpc method names to + php function names. The incoming request is parsed and dispatched to the + relevant php function, which is responsible for returning a + xmlrpcresp object, that will be serialized back + to the caller. + + +==== Method handler functions + +Both php functions and class methods can be registered as xmlrpc + method handlers. + +The synopsis of a method handler function is: + +xmlrpcresp $resp = function (xmlrpcmsg $msg) + +No text should be echoed 'to screen' by the handler function, or + it will break the xml response sent back to the client. This applies + also to error and warning messages that PHP prints to screen unless + the appropriate parameters have been set in the php.in file. Another + way to prevent echoing of errors inside the response and facilitate + debugging is to use the server SetDebug method with debug level 3 (see + ...). Exceptions thrown duting execution of handler functions are + caught by default and a XML-RPC error reponse is generated instead. + This behaviour can be finetuned by usage of the + exception_handling member variable (see + ...). + +Note that if you implement a method with a name prefixed by + ++system.++ the handler function will be invoked by the + server with two parameters, the first being the server itself and the + second being the xmlrpcmsg object. + +The same php function can be registered as handler of multiple + xmlrpc methods. + +Here is a more detailed example of what the handler function + foo may do: + + +[source, php] +---- + + function foo ($xmlrpcmsg) { + global $xmlrpcerruser; // import user errcode base value + + $meth = $xmlrpcmsg->method(); // retrieve method name + $par = $xmlrpcmsg->getParam(0); // retrieve value of first parameter - assumes at least one param received + $val = $par->scalarval(); // decode value of first parameter - assumes it is a scalar value + + ... + + if ($err) { + // this is an error condition + return new xmlrpcresp(0, $xmlrpcerruser+1, // user error 1 + "There's a problem, Captain"); + } else { + // this is a successful value being returned + return new xmlrpcresp(new xmlrpcval("All's fine!", "string")); + } + } + +---- + +See __server.php__ in this distribution for + more examples of how to do this. + +Since release 2.0RC3 there is a new, even simpler way of + registering php functions with the server. See section 5.7 + below + + +==== The dispatch map + +The first argument to the xmlrpc_server + constructor is an array, called the __dispatch map__. + In this array is the information the server needs to service the + XML-RPC methods you define. + +The dispatch map takes the form of an associative array of + associative arrays: the outer array has one entry for each method, the + key being the method name. The corresponding value is another + associative array, which can have the following members: + + +* ++function++ - this + entry is mandatory. It must be either a name of a function in the + global scope which services the XML-RPC method, or an array + containing an instance of an object and a static method name (for + static class methods the 'class::method' syntax is also + supported). + + +* ++signature++ - this + entry is an array containing the possible signatures (see <>) for the method. If this entry is present + then the server will check that the correct number and type of + parameters have been sent for this method before dispatching + it. + + +* ++docstring++ - this + entry is a string containing documentation for the method. The + documentation may contain HTML markup. + + +* ++$$signature_docs$$++ - this entry can be used + to provide documentation for the single parameters. It must match + in structure the 'signature' member. By default, only the + documenting_xmlrpc_server class in the + extras package will take advantage of this, since the + "system.methodHelp" protocol does not support documenting method + parameters individually. + + +* ++$$parameters_type$$++ - this entry can be used + when the server is working in 'xmlrpcvals' mode (see ...) to + define one or more entries in the dispatch map as being functions + that follow the 'phpvals' calling convention. The only useful + value is currently the string ++phpvals++. + +Look at the __server.php__ example in the + distribution to see what a dispatch map looks like. + +[[signatures]] + +==== Method signatures + +A signature is a description of a method's return type and its + parameter types. A method may have more than one signature. + +Within a server's dispatch map, each method has an array of + possible signatures. Each signature is an array of types. The first + entry is the return type. For instance, the method +[source, php] +---- +string examples.getStateName(int) + +---- + + has the signature +[source, php] +---- +array($xmlrpcString, $xmlrpcInt) + +---- + + and, assuming that it is the only possible signature for the + method, it might be used like this in server creation: +[source, php] +---- + +$findstate_sig = array(array($xmlrpcString, $xmlrpcInt)); + +$findstate_doc = 'When passed an integer between 1 and 51 returns the +name of a US state, where the integer is the index of that state name +in an alphabetic order.'; + +$s = new xmlrpc_server( array( + "examples.getStateName" => array( + "function" => "findstate", + "signature" => $findstate_sig, + "docstring" => $findstate_doc + ))); + +---- + + + +Note that method signatures do not allow to check nested + parameters, e.g. the number, names and types of the members of a + struct param cannot be validated. + +If a method that you want to expose has a definite number of + parameters, but each of those parameters could reasonably be of + multiple types, the array of acceptable signatures will easily grow + into a combinatorial explosion. To avoid such a situation, the lib + defines the global var $xmlrpcValue, which can be + used in method signatures as a placeholder for 'any xmlrpc + type': + + +[source, php] +---- + +$echoback_sig = array(array($xmlrpcValue, $xmlrpcValue)); + +$findstate_doc = 'Echoes back to the client the received value, regardless of its type'; + +$s = new xmlrpc_server( array( + "echoBack" => array( + "function" => "echoback", + "signature" => $echoback_sig, // this sig guarantees that the method handler will be called with one and only one parameter + "docstring" => $echoback_doc + ))); + +---- + +Methods system.listMethods, + system.methodHelp, + system.methodSignature and + system.multicall are already defined by the + server, and should not be reimplemented (see Reserved Methods + below). + + +==== Delaying the server response + +You may want to construct the server, but for some reason not + fulfill the request immediately (security verification, for instance). + If you omit to pass to the constructor the dispatch map or pass it a + second argument of ++0++ this will have the desired + effect. You can then use the service() method of + the server class to service the request. For example: + + +[source, php] +---- + +$s = new xmlrpc_server($myDispMap, 0); // second parameter = 0 prevents automatic servicing of request + +// ... some code that does other stuff here + +$s->service(); + +---- + +Note that the service method will print + the complete result payload to screen and send appropriate HTTP + headers back to the client, but also return the response object. This + permits further manipulation of the response, possibly in combination + with output buffering. + +To prevent the server from sending HTTP headers back to the + client, you can pass a second parameter with a value of + ++TRUE++ to the service + method. In this case, the response payload will be returned instead of + the response object. + +Xmlrpc requests retrieved by other means than HTTP POST bodies + can also be processed. For example: + + +[source, php] +---- + +$s = new xmlrpc_server(); // not passing a dispatch map prevents automatic servicing of request + +// ... some code that does other stuff here, including setting dispatch map into server object + +$resp = $s->service($xmlrpc_request_body, true); // parse a variable instead of POST body, retrieve response payload + +// ... some code that does other stuff with xml response $resp here + +---- + + +==== Modifying the server behaviour + +A couple of methods / class variables are available to modify + the behaviour of the server. The only way to take advantage of their + existence is by usage of a delayed server response (see above) + + +===== setDebug() + +This function controls weather the server is going to echo + debugging messages back to the client as comments in response body. + Valid values: 0,1,2,3, with 1 being the default. At level 0, no + debug info is returned to the client. At level 2, the complete + client request is added to the response, as part of the xml + comments. At level 3, a new PHP error handler is set when executing + user functions exposed as server methods, and all non-fatal errors + are trapped and added as comments into the response. + + +===== allow_system_funcs + +Default_value: TRUE. When set to FALSE, disables support for + System.xxx functions in the server. It + might be useful e.g. if you do not wish the server to respond to + requests to System.ListMethods. + + +===== compress_response + +When set to TRUE, enables the server to take advantage of HTTP + compression, otherwise disables it. Responses will be transparently + compressed, but only when an xmlrpc-client declares its support for + compression in the HTTP headers of the request. + +Note that the ZLIB php extension must be installed for this to + work. If it is, compress_response will default to + TRUE. + + +===== exception_handling + +This variable controls the behaviour of the server when an + exception is thrown by a method handler php function. Valid values: + 0,1,2, with 0 being the default. At level 0, the server catches the + exception and return an 'internal error' xmlrpc response; at 1 it + catches the exceptions and return an xmlrpc response with the error + code and error message corresponding to the exception that was + thron; at 2 = the exception is floated to the upper layers in the + code + + +===== response_charset_encoding + +Charset encoding to be used for response (only affects string + values). + +If it can, the server will convert the generated response from + internal_encoding to the intended one. + +Valid values are: a supported xml encoding (only UTF-8 and + ISO-8859-1 at present, unless mbstring is enabled), null (leave + charset unspecified in response and convert output stream to + US_ASCII), 'default' (use xmlrpc library default as specified in + xmlrpc.inc, convert output stream if needed), or 'auto' (use + client-specified charset encoding or same as request if request + headers do not specify it (unless request is US-ASCII: then use + library default anyway). + + +==== Fault reporting + +Fault codes for your servers should start at the value indicated + by the global ++$xmlrpcerruser++ + 1. + +Standard errors returned by the server include: + +++1++ Unknown method:: Returned if the server was asked to dispatch a method it + didn't know about + +++2++ Invalid return payload:: This error is actually generated by the client, not + server, code, but signifies that a server returned something it + couldn't understand. A more detailed error report is sometimes + added onto the end of the phrase above. + +++3++ Incorrect parameters:: This error is generated when the server has signature(s) + defined for a method, and the parameters passed by the client do + not match any of signatures. + +++4++ Can't introspect: method unknown:: This error is generated by the builtin + system.* methods when any kind of + introspection is attempted on a method undefined by the + server. + +++5++ Didn't receive 200 OK from remote server:: This error is generated by the client when a remote server + doesn't return HTTP/1.1 200 OK in response to a request. A more + detailed error report is added onto the end of the phrase + above. + +++6++ No data received from server:: This error is generated by the client when a remote server + returns HTTP/1.1 200 OK in response to a request, but no + response body follows the HTTP headers. + +++7++ No SSL support compiled in:: This error is generated by the client when trying to send + a request with HTTPS and the CURL extension is not available to + PHP. + +++8++ CURL error:: This error is generated by the client when trying to send + a request with HTTPS and the HTTPS communication fails. + +++9-14++ multicall errors:: These errors are generated by the server when something + fails inside a system.multicall request. + +++100-++ XML parse errors:: Returns 100 plus the XML parser error code for the fault + that occurred. The faultString returned + explains where the parse error was in the incoming XML + stream. + + +==== 'New style' servers + +In the same spirit of simplification that inspired the + xmlrpc_client::return_type class variable, a new + class variable has been added to the server class: + functions_parameters_type. When set to 'phpvals', + the functions registered in the server dispatch map will be called + with plain php values as parameters, instead of a single xmlrpcmsg + instance parameter. The return value of those functions is expected to + be a plain php value, too. An example is worth a thousand + words: +[source, php] +---- + + function foo($usr_id, $out_lang='en') { + global $xmlrpcerruser; + + ... + + if ($someErrorCondition) + return new xmlrpcresp(0, $xmlrpcerruser+1, 'DOH!'); + else + return array( + 'name' => 'Joe', + 'age' => 27, + 'picture' => new xmlrpcval(file_get_contents($picOfTheGuy), 'base64') + ); + } + + $s = new xmlrpc_server( + array( + "examples.myFunc" => array( + "function" => "bar::foobar", + "signature" => array( + array($xmlrpcString, $xmlrpcInt), + array($xmlrpcString, $xmlrpcInt, $xmlrpcString) + ) + ) + ), false); + $s->functions_parameters_type = 'phpvals'; + $s->service(); + +---- + +There are a few things to keep in mind when using this + simplified syntax: + +to return an xmlrpc error, the method handler function must + return an instance of xmlrpcresp. The only + other way for the server to know when an error response should be + served to the client is to throw an exception and set the server's + exception_handling memeber var to 1; + +to return a base64 value, the method handler function must + encode it on its own, creating an instance of an xmlrpcval + object; + +the method handler function cannot determine the name of the + xmlrpc method it is serving, unlike standard handler functions that + can retrieve it from the message object; + +when receiving nested parameters, the method handler function + has no way to distinguish a php string that was sent as base64 value + from one that was sent as a string value; + +this has a direct consequence on the support of + system.multicall: a method whose signature contains datetime or base64 + values will not be available to multicall calls; + +last but not least, the direct parsing of xml to php values is + much faster than using xmlrpcvals, and allows the library to handle + much bigger messages without allocating all available server memory or + smashing PHP recursive call stack. + + +[[globalvars]] + +== Global variables + +Many global variables are defined in the xmlrpc.inc file. Some of + those are meant to be used as constants (and modifying their value might + cause unpredictable behaviour), while some others can be modified in your + php scripts to alter the behaviour of the xml-rpc client and + server. + + +=== "Constant" variables + + +==== $xmlrpcerruser + +$xmlrpcerruser800The minimum value for errors reported by user + implemented XML-RPC servers. Error numbers lower than that are + reserved for library usage. + + +==== $xmlrpcI4, $xmlrpcI8 $xmlrpcInt, $xmlrpcBoolean, $xmlrpcDouble, $xmlrpcString, $xmlrpcDateTime, $xmlrpcBase64, $xmlrpcArray, $xmlrpcStruct, $xmlrpcValue, $xmlrpcNull + +For convenience the strings representing the XML-RPC types have + been encoded as global variables: +[source, php] +---- + +$xmlrpcI4="i4"; +$xmlrpcI8="i8"; +$xmlrpcInt="int"; +$xmlrpcBoolean="boolean"; +$xmlrpcDouble="double"; +$xmlrpcString="string"; +$xmlrpcDateTime="dateTime.iso8601"; +$xmlrpcBase64="base64"; +$xmlrpcArray="array"; +$xmlrpcStruct="struct"; +$xmlrpcValue="undefined"; +$xmlrpcNull="null"; + +---- + +==== $xmlrpcTypes, $xmlrpc_valid_parents, $xmlrpcerr, $xmlrpcstr, $xmlrpcerrxml, $xmlrpc_backslash, $_xh, $xml_iso88591_Entities, $xmlEntities, $xmlrpcs_capabilities + +Reserved for internal usage. + + +=== Variables whose value can be modified + +[[xmlrpc-defencoding]] + +==== xmlrpc_defencoding + +$xmlrpc_defencoding"UTF8"This variable defines the character set encoding that will be + used by the xml-rpc client and server to decode the received messages, + when a specific charset declaration is not found (in the messages sent + non-ascii chars are always encoded using character references, so that + the produced xml is valid regardless of the charset encoding + assumed). + +Allowed values: ++"UTF8"++, + ++"ISO-8859-1"++, ++"ASCII".++ + +Note that the appropriate RFC actually mandates that XML + received over HTTP without indication of charset encoding be treated + as US-ASCII, but many servers and clients 'in the wild' violate the + standard, and assume the default encoding is UTF-8. + + +==== xmlrpc_internalencoding + +$xmlrpc_internalencoding"ISO-8859-1"This variable defines the character set encoding + that the library uses to transparently encode into valid XML the + xml-rpc values created by the user and to re-encode the received + xml-rpc values when it passes them to the PHP application. It only + affects xml-rpc values of string type. It is a separate value from + xmlrpc_defencoding, allowing e.g. to send/receive xml messages encoded + on-the-wire in US-ASCII and process them as UTF-8. It defaults to the + character set used internally by PHP (unless you are running an + MBString-enabled installation), so you should change it only in + special situations, if e.g. the string values exchanged in the xml-rpc + messages are directly inserted into / fetched from a database + configured to return UTF8 encoded strings to PHP. Example + usage: + +[source, php] +---- + + (and ) xmlrpc value, as + per the extension to the standard proposed here. This means that + and tags received will be parsed as valid + xmlrpc, and the corresponding xmlrpcvals will return "null" for + scalarTyp(). + + +==== xmlrpc_null_apache_encoding + +When set to ++TRUE++, php NULL values encoded + into xmlrpcval objects get serialized using the + ++++ tag instead of + ++++. Please note that both forms are + always accepted as input regardless of the value of this + variable. + + +[[helpers]] + +== Helper functions + +XML-RPC for PHP contains some helper functions which you can use to + make processing of XML-RPC requests easier. + + +=== Date functions + +The XML-RPC specification has this to say on dates: + +[quote] +____ +[[wrap_xmlrpc_method]] +Don't assume a timezone. It should be + specified by the server in its documentation what assumptions it makes + about timezones. +____ + + +Unfortunately, this means that date processing isn't + straightforward. Although XML-RPC uses ISO 8601 format dates, it doesn't + use the timezone specifier. + +We strongly recommend that in every case where you pass dates in + XML-RPC calls, you use UTC (GMT) as your timezone. Most computer + languages include routines for handling GMT times natively, and you + won't have to translate between timezones. + +For more information about dates, see link:$$http://www.uic.edu/year2000/datefmt.html$$[ISO 8601: The Right Format for Dates], which has a handy link to a PDF of the ISO + 8601 specification. Note that XML-RPC uses exactly one of the available + representations: CCYYMMDDTHH:MM:SS. + +[[iso8601encode]] + +==== iso8601_encode + +stringiso8601_encodestring$time_tint$utc0Returns an ISO 8601 formatted date generated from the UNIX + timestamp $time_t, as returned by the PHP + function time(). + +The argument $utc can be omitted, in + which case it defaults to ++0++. If it is set to + ++1++, then the function corrects the time passed in + for UTC. Example: if you're in the GMT-6:00 timezone and set + $utc, you will receive a date representation + six hours ahead of your local time. + +The included demo program __vardemo.php__ + includes a demonstration of this function. + +[[iso8601decode]] + +==== iso8601_decode + +intiso8601_decodestring$isoStringint$utc0Returns a UNIX timestamp from an ISO 8601 encoded time and date + string passed in. If $utc is + ++1++ then $isoString is assumed + to be in the UTC timezone, and thus the result is also UTC: otherwise, + the timezone is assumed to be your local timezone and you receive a + local timestamp. + +[[arrayuse]] + +=== Easy use with nested PHP values + +Dan Libby was kind enough to contribute two helper functions that + make it easier to translate to and from PHP values. This makes it easier + to deal with complex structures. At the moment support is limited to + int, double, string, + array, datetime and struct + datatypes; note also that all PHP arrays are encoded as structs, except + arrays whose keys are integer numbers starting with 0 and incremented by + 1. + +These functions reside in __xmlrpc.inc__. + +[[phpxmlrpcdecode]] + +==== php_xmlrpc_decode + +mixedphp_xmlrpc_decodexmlrpcval$xmlrpc_valarray$optionsarrayphp_xmlrpc_decodexmlrpcmsg$xmlrpcmsg_valstring$optionsReturns a native PHP value corresponding to the values found in + the xmlrpcval $xmlrpc_val, + translated into PHP types. Base-64 and datetime values are + automatically decoded to strings. + +In the second form, returns an array containing the parameters + of the given + xmlrpcmsg_val, decoded + to php types. + +The options parameter is optional. If + specified, it must consist of an array of options to be enabled in the + decoding process. At the moment the only valid option are + decode_php_objs and + ++$$dates_as_objects$$++. When the first is set, php + objects that have been converted to xml-rpc structs using the + php_xmlrpc_encode function and a corresponding + encoding option will be converted back into object values instead of + arrays (provided that the class definition is available at + reconstruction time). When the second is set, XML-RPC datetime values + will be converted into native dateTime objects + instead of strings. + +____WARNING__:__ please take + extreme care before enabling the decode_php_objs + option: when php objects are rebuilt from the received xml, their + constructor function will be silently invoked. This means that you are + allowing the remote end to trigger execution of uncontrolled PHP code + on your server, opening the door to code injection exploits. Only + enable this option when you have complete trust of the remote + server/client. + +Example: +[source, php] +---- + +// wrapper to expose an existing php function as xmlrpc method handler +function foo_wrapper($m) +{ + $params = php_xmlrpc_decode($m); + $retval = call_user_func_array('foo', $params); + return new xmlrpcresp(new xmlrpcval($retval)); // foo return value will be serialized as string +} + +$s = new xmlrpc_server(array( + "examples.myFunc1" => array( + "function" => "foo_wrapper", + "signatures" => ... + ))); + +---- + +[[phpxmlrpcencode]] + +==== php_xmlrpc_encode + +xmlrpcvalphp_xmlrpc_encodemixed$phpvalarray$optionsReturns an xmlrpcval object populated with the PHP + values in $phpval. Works recursively on arrays + and objects, encoding numerically indexed php arrays into array-type + xmlrpcval objects and non numerically indexed php arrays into + struct-type xmlrpcval objects. Php objects are encoded into + struct-type xmlrpcvals, excepted for php values that are already + instances of the xmlrpcval class or descendants thereof, which will + not be further encoded. Note that there's no support for encoding php + values into base-64 values. Encoding of date-times is optionally + carried on on php strings with the correct format. + +The options parameter is optional. If + specified, it must consist of an array of options to be enabled in the + encoding process. At the moment the only valid options are + encode_php_objs, ++$$null_extension$$++ + and auto_dates. + +The first will enable the creation of 'particular' xmlrpcval + objects out of php objects, that add a "php_class" xml attribute to + their serialized representation. This attribute allows the function + php_xmlrpc_decode to rebuild the native php objects (provided that the + same class definition exists on both sides of the communication). The + second allows to encode php ++NULL++ values to the + ++++ (or + ++++, see ...) tag. The last encodes any + string that matches the ISO8601 format into an XML-RPC + datetime. + +Example: +[source, php] +---- + +// the easy way to build a complex xml-rpc struct, showing nested base64 value and datetime values +$val = php_xmlrpc_encode(array( + 'first struct_element: an int' => 666, + 'second: an array' => array ('apple', 'orange', 'banana'), + 'third: a base64 element' => new xmlrpcval('hello world', 'base64'), + 'fourth: a datetime' => '20060107T01:53:00' + ), array('auto_dates')); + +---- + +==== php_xmlrpc_decode_xml + +xmlrpcval | xmlrpcresp | + xmlrpcmsgphp_xmlrpc_decode_xmlstring$xmlarray$optionsDecodes the xml representation of either an xmlrpc request, + response or single value, returning the corresponding php-xmlrpc + object, or ++FALSE++ in case of an error. + +The options parameter is optional. If + specified, it must consist of an array of options to be enabled in the + decoding process. At the moment, no option is supported. + +Example: +[source, php] +---- + +$text = 'Hello world'; +$val = php_xmlrpc_decode_xml($text); +if ($val) echo 'Found a value of type '.$val->kindOf(); else echo 'Found invalid xml'; + +---- + +=== Automatic conversion of php functions into xmlrpc methods (and vice versa) + +For the extremely lazy coder, helper functions have been added + that allow to convert a php function into an xmlrpc method, and a + remotely exposed xmlrpc method into a local php function - or a set of + methods into a php class. Note that these comes with many caveat. + + +==== wrap_xmlrpc_method + +stringwrap_xmlrpc_method$client$methodname$extra_optionsstringwrap_xmlrpc_method$client$methodname$signum$timeout$protocol$funcnameGiven an xmlrpc server and a method name, creates a php wrapper + function that will call the remote method and return results using + native php types for both params and results. The generated php + function will return an xmlrpcresp object for failed xmlrpc + calls. + +The second syntax is deprecated, and is listed here only for + backward compatibility. + +The server must support the + system.methodSignature xmlrpc method call for + this function to work. + +The client param must be a valid + xmlrpc_client object, previously created with the address of the + target xmlrpc server, and to which the preferred communication options + have been set. + +The optional parameters can be passed as array key,value pairs + in the extra_options param. + +The signum optional param has the purpose + of indicating which method signature to use, if the given server + method has multiple signatures (defaults to 0). + +The timeout and + protocol optional params are the same as in the + xmlrpc_client::send() method. + +If set, the optional new_function_name + parameter indicates which name should be used for the generated + function. In case it is not set the function name will be + auto-generated. + +If the ++$$return_source$$++ optional parameter is + set, the function will return the php source code to build the wrapper + function, instead of evaluating it (useful to save the code and use it + later as stand-alone xmlrpc client). + +If the ++$$encode_php_objs$$++ optional parameter is + set, instances of php objects later passed as parameters to the newly + created function will receive a 'special' treatment that allows the + server to rebuild them as php objects instead of simple arrays. Note + that this entails using a "slightly augmented" version of the xmlrpc + protocol (ie. using element attributes), which might not be understood + by xmlrpc servers implemented using other libraries. + +If the ++$$decode_php_objs$$++ optional parameter is + set, instances of php objects that have been appropriately encoded by + the server using a coordinate option will be deserialized as php + objects instead of simple arrays (the same class definition should be + present server side and client side). + +__Note that this might pose a security risk__, + since in order to rebuild the object instances their constructor + method has to be invoked, and this means that the remote server can + trigger execution of unforeseen php code on the client: not really a + code injection, but almost. Please enable this option only when you + trust the remote server. + +In case of an error during generation of the wrapper function, + FALSE is returned, otherwise the name (or source code) of the new + function. + +Known limitations: server must support + system.methodsignature for the wanted xmlrpc + method; for methods that expose multiple signatures, only one can be + picked; for remote calls with nested xmlrpc params, the caller of the + generated php function has to encode on its own the params passed to + the php function if these are structs or arrays whose (sub)members + include values of type base64. + +Note: calling the generated php function 'might' be slow: a new + xmlrpc client is created on every invocation and an xmlrpc-connection + opened+closed. An extra 'debug' param is appended to the parameter + list of the generated php function, useful for debugging + purposes. + +Example usage: + + +[source, php] +---- + +$c = new xmlrpc_client('http://phpxmlrpc.sourceforge.net/server.php'); + +$function = wrap_xmlrpc_method($client, 'examples.getStateName'); + +if (!$function) + die('Cannot introspect remote method'); +else { + $stateno = 15; + $statename = $function($a); + if (is_a($statename, 'xmlrpcresp')) // call failed + { + echo 'Call failed: '.$statename->faultCode().'. Calling again with debug on'; + $function($a, true); + } + else + echo "OK, state nr. $stateno is $statename"; +} + +---- + +[[wrap_php_function]] + +==== wrap_php_function + +arraywrap_php_functionstring$funcnamestring$wrapper_function_namearray$extra_optionsGiven a user-defined PHP function, create a PHP 'wrapper' + function that can be exposed as xmlrpc method from an xmlrpc_server + object and called from remote clients, and return the appropriate + definition to be added to a server's dispatch map. + +The optional $wrapper_function_name + specifies the name that will be used for the auto-generated + function. + +Since php is a typeless language, to infer types of input and + output parameters, it relies on parsing the javadoc-style comment + block associated with the given function. Usage of xmlrpc native types + (such as datetime.dateTime.iso8601 and base64) in the docblock @param + tag is also allowed, if you need the php function to receive/send data + in that particular format (note that base64 encoding/decoding is + transparently carried out by the lib, while datetime vals are passed + around as strings). + +Known limitations: only works for + user-defined functions, not for PHP internal functions (reflection + does not support retrieving number/type of params for those); the + wrapped php function will not be able to programmatically return an + xmlrpc error response. + +If the ++$$return_source$$++ optional parameter is + set, the function will return the php source code to build the wrapper + function, instead of evaluating it (useful to save the code and use it + later in a stand-alone xmlrpc server). It will be in the stored in the + ++source++ member of the returned array. + +If the ++$$suppress_warnings$$++ optional parameter + is set, any runtime warning generated while processing the + user-defined php function will be catched and not be printed in the + generated xml response. + +If the extra_options array contains the + ++$$encode_php_objs$$++ value, wrapped functions returning + php objects will generate "special" xmlrpc responses: when the xmlrpc + decoding of those responses is carried out by this same lib, using the + appropriate param in php_xmlrpc_decode(), the objects will be + rebuilt. + +In short: php objects can be serialized, too (except for their + resource members), using this function. Other libs might choke on the + very same xml that will be generated in this case (i.e. it has a + nonstandard attribute on struct element tags) + +If the ++$$decode_php_objs$$++ optional parameter is + set, instances of php objects that have been appropriately encoded by + the client using a coordinate option will be deserialized and passed + to the user function as php objects instead of simple arrays (the same + class definition should be present server side and client + side). + +__Note that this might pose a security risk__, + since in order to rebuild the object instances their constructor + method has to be invoked, and this means that the remote client can + trigger execution of unforeseen php code on the server: not really a + code injection, but almost. Please enable this option only when you + trust the remote clients. + +Example usage: + + +[source, php] +---- +/** +* State name from state number decoder. NB: do NOT remove this comment block. +* @param integer $stateno the state number +* @return string the name of the state (or error description) +*/ +function findstate($stateno) +{ + global $stateNames; + if (isset($stateNames[$stateno-1])) + { + return $stateNames[$stateno-1]; + } + else + { + return "I don't have a state for the index '" . $stateno . "'"; + } +} + +// wrap php function, build xmlrpc server +$methods = array(); +$findstate_sig = wrap_php_function('findstate'); +if ($findstate_sig) + $methods['examples.getStateName'] = $findstate_sig; +$srv = new xmlrpc_server($methods); + +---- + +[[deprecated]] + +=== Functions removed from the library + +The following two functions have been deprecated in version 1.1 of + the library, and removed in version 2, in order to avoid conflicts with + the EPI xml-rpc library, which also defines two functions with the same + names. + +To ease the transition to the new naming scheme and avoid breaking + existing implementations, the following scheme has been adopted: + +* If EPI-XMLRPC is not active in the current PHP installation, + the constant `XMLRPC_EPI_ENABLED` will be set to + '0' + + +* If EPI-XMLRPC is active in the current PHP installation, the + constant `XMLRPC_EPI_ENABLED` will be set to + '1' + + + +The following documentation is kept for historical + reference: + +[[xmlrpcdecode]] + +==== xmlrpc_decode + +mixedx mlrpc_decode xmlrpcval $xmlrpc_val Alias for php_xmlrpc_decode. + +[[xmlrpcencode]] + +==== xmlrpc_encode + +xmlrpcval xmlrpc_encode mixed $phpvalAlias for php_xmlrpc_encode. + +[[debugging]] + +=== Debugging aids + +==== xmlrpc_debugmsg + +void xmlrpc_debugmsgstring$debugstringSends the contents of $debugstring in XML + comments in the server return payload. If a PHP client has debugging + turned on, the user will be able to see server debug + information. + +Use this function in your methods so you can pass back + diagnostic information. It is only available from + __xmlrpcs.inc__. + + +[[reserved]] + +== Reserved methods + +In order to extend the functionality offered by XML-RPC servers + without impacting on the protocol, reserved methods are supported in this + release. + +All methods starting with system. are + considered reserved by the server. PHP for XML-RPC itself provides four + special methods, detailed in this chapter. + +Note that all server objects will automatically respond to clients + querying these methods, unless the property + allow_system_funcs has been set to + false before calling the + service() method. This might pose a security risk + if the server is exposed to public access, e.g. on the internet. + + +=== system.getCapabilities + + +=== system.listMethods + +This method may be used to enumerate the methods implemented by + the XML-RPC server. + +The system.listMethods method requires no + parameters. It returns an array of strings, each of which is the name of + a method implemented by the server. + +[[sysmethodsig]] + +=== system.methodSignature + +This method takes one parameter, the name of a method implemented + by the XML-RPC server. + +It returns an array of possible signatures for this method. A + signature is an array of types. The first of these types is the return + type of the method, the rest are parameters. + +Multiple signatures (i.e. overloading) are permitted: this is the + reason that an array of signatures are returned by this method. + +Signatures themselves are restricted to the top level parameters + expected by a method. For instance if a method expects one array of + structs as a parameter, and it returns a string, its signature is simply + "string, array". If it expects three integers, its signature is "string, + int, int, int". + +For parameters that can be of more than one type, the "undefined" + string is supported. + +If no signature is defined for the method, a not-array value is + returned. Therefore this is the way to test for a non-signature, if + $resp below is the response object from a method + call to system.methodSignature: + +[source, php] +---- + +$v = $resp->value(); +if ($v->kindOf() != "array") { + // then the method did not have a signature defined +} + +---- + +See the __introspect.php__ demo included in this + distribution for an example of using this method. + +[[sysmethhelp]] + +=== system.methodHelp + +This method takes one parameter, the name of a method implemented + by the XML-RPC server. + +It returns a documentation string describing the use of that + method. If no such string is available, an empty string is + returned. + +The documentation string may contain HTML markup. + +=== system.multicall + +This method takes one parameter, an array of 'request' struct + types. Each request struct must contain a + methodName member of type string and a + params member of type array, and corresponds to + the invocation of the corresponding method. + +It returns a response of type array, with each value of the array + being either an error struct (containing the faultCode and faultString + members) or the successful response value of the corresponding single + method call. + + +[[examples]] + +== Examples + +The best examples are to be found in the sample files included with + the distribution. Some are included here. + +[[statename]] + +=== XML-RPC client: state name query + +Code to get the corresponding state name from a number (1-50) from + the demo server available on SourceForge + +[source, php] +---- + + $m = new xmlrpcmsg('examples.getStateName', + array(new xmlrpcval($HTTP_POST_VARS["stateno"], "int"))); + $c = new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80); + $r = $c->send($m); + if (!$r->faultCode()) { + $v = $r->value(); + print "State number " . htmlentities($HTTP_POST_VARS["stateno"]) . " is " . + htmlentities($v->scalarval()) . "
    "; + print "
    I got this value back
    " .
    +        htmlentities($r->serialize()) . "

    \n"; + } else { + print "Fault
    "; + print "Code: " . htmlentities($r->faultCode()) . "
    " . + "Reason: '" . htmlentities($r->faultString()) . "'
    "; + } + +---- + +=== Executing a multicall call + +To be documented... + + +[[faq]] + +[qanda] +== Frequently Asked Questions + +==== How to send custom XML as payload of a method call:: + +Unfortunately, at the time the XML-RPC spec was designed, support + for namespaces in XML was not as ubiquitous as it is now. As a + consequence, no support was provided in the protocol for embedding XML + elements from other namespaces into an xmlrpc request. + +To send an XML "chunk" as payload of a method call or response, + two options are available: either send the complete XML block as a + string xmlrpc value, or as a base64 value. Since the '<' character in + string values is encoded as '<' in the xml payload of the method + call, the XML string will not break the surrounding xmlrpc, unless + characters outside of the assumed character set are used. The second + method has the added benefits of working independently of the charset + encoding used for the xml to be transmitted, and preserving exactly + whitespace, whilst incurring in some extra message length and cpu load + (for carrying out the base64 encoding/decoding). + + +==== Is there any limitation on the size of the requests / responses that can be successfully sent?:: + +Yes. But I have no hard figure to give; it most likely will depend + on the version of PHP in usage and its configuration. + +Keep in mind that this library is not optimized for speed nor for + memory usage. Better alternatives exist when there are strict + requirements on throughput or resource usage, such as the php native + xmlrpc extension (see the PHP manual for more information). + +Keep in mind also that HTTP is probably not the best choice in + such a situation, and XML is a deadly enemy. CSV formatted data over + socket would be much more efficient. + +If you really need to move a massive amount of data around, and + you are crazy enough to do it using phpxmlrpc, your best bet is to + bypass usage of the xmlrpcval objects, at least in the decoding phase, + and have the server (or client) object return to the calling function + directly php values (see xmlrpc_client::return_type + and xmlrpc_server::functions_parameters_type for more + details). + + +==== My server (client) returns an error whenever the client (server) returns accented characters + +To be documented... + + +==== How to enable long-lasting method calls + +To be documented... + + +==== My client returns "XML-RPC Fault #2: Invalid return payload: enable debugging to examine incoming payload": what should I do? + +The response you are seeing is a default error response that the + client object returns to the php application when the server did not + respond to the call with a valid xmlrpc response. + +The most likely cause is that you are not using the correct URL + when creating the client object, or you do not have appropriate access + rights to the web page you are requesting, or some other common http + misconfiguration. + +To find out what the server is really returning to your client, + you have to enable the debug mode of the client, using + $client->setdebug(1); + + +==== How can I save to a file the xml of the xmlrpc responses received from servers? + +If what you need is to save the responses received from the server + as xml, you have two options: + +1- use the serialize() method on the response object. + + +[source, php] +---- + +$resp = $client->send($msg); +if (!$resp->faultCode()) + $data_to_be_saved = $resp->serialize(); + +---- + +Note that this will not be 100% accurate, since the xml generated + by the response object can be different from the xml received, + especially if there is some character set conversion involved, or such + (eg. if you receive an empty string tag as , serialize() + will output ), or if the server sent back + as response something invalid (in which case the xml generated client + side using serialize() will correspond to the error response generated + internally by the lib). + +2 - set the client object to return the raw xml received instead + of the decoded objects: + + +[source, php] +---- + +$client = new xmlrpc_client($url); +$client->return_type = 'xml'; +$resp = $client->send($msg); +if (!$resp->faultCode()) + $data_to_be_saved = $resp->value(); + +---- + +Note that using this method the xml response response will not be + parsed at all by the library, only the http communication protocol will + be checked. This means that xmlrpc responses sent by the server that + would have generated an error response on the client (eg. malformed xml, + responses that have faultcode set, etc...) now will not be flagged as + invalid, and you might end up saving not valid xml but random + junk... + + +==== Can I use the ms windows character set? + +If the data your application is using comes from a Microsoft + application, there are some chances that the character set used to + encode it is CP1252 (the same might apply to data received from an + external xmlrpc server/client, but it is quite rare to find xmlrpc + toolkits that encode to CP1252 instead of UTF8). It is a character set + which is "almost" compatible with ISO 8859-1, but for a few extra + characters. + +PHP-XMLRPC only supports the ISO 8859-1 and UTF8 character sets. + The net result of this situation is that those extra characters will not + be properly encoded, and will be received at the other end of the + XML-RPC transmission as "garbled data". Unfortunately the library cannot + provide real support for CP1252 because of limitations in the PHP 4 xml + parser. Luckily, we tried our best to support this character set anyway, + and, since version 2.2.1, there is some form of support, left commented + in the code. + +To properly encode outgoing data that is natively in CP1252, you + will have to uncomment all relative code in the file + __xmlrpc.inc__ (you can search for the string "1252"), + then set ++$$$GLOBALS['xmlrpc_internalencoding']='CP1252';$$++ + Please note that all incoming data will then be fed to your application + as UTF-8 to avoid any potential data loss. + + +==== Does the library support using cookies / http sessions? + +In short: yes, but a little coding is needed to make it + happen. + +The code below uses sessions to e.g. let the client store a value + on the server and retrieve it later. + +[source, php] +---- + +$resp = $client->send(new xmlrpcmsg('registervalue', array(new xmlrpcval('foo'), new xmlrpcval('bar')))); +if (!$resp->faultCode()) +{ + $cookies = $resp->cookies(); + if (array_key_exists('PHPSESSID', $cookies)) // nb: make sure to use the correct session cookie name + { + $session_id = $cookies['PHPSESSID']['value']; + + // do some other stuff here... + + $client->setcookie('PHPSESSID', $session_id); + $val = $client->send(new xmlrpcmsg('getvalue', array(new xmlrpcval('foo'))); + } +} + +---- + +Server-side sessions are handled normally like in any other + php application. Please see the php manual for more information about + sessions. + +NB: unlike web browsers, not all xmlrpc clients support usage of + http cookies. If you have troubles with sessions and control only the + server side of the communication, please check with the makers of the + xmlrpc client in use. + + +[[integration]] + +[appendix] +== Integration with the PHP xmlrpc extension + +To be documented more... + +In short: for the fastest execution possible, you can enable the php + native xmlrpc extension, and use it in conjunction with phpxmlrpc. The + following code snippet gives an example of such integration + + +[source, php] +---- + +/*** client side ***/ +$c = new xmlrpc_client('http://phpxmlrpc.sourceforge.net/server.php'); + +// tell the client to return raw xml as response value +$c->return_type = 'xml'; + +// let the native xmlrpc extension take care of encoding request parameters +$r = $c->send(xmlrpc_encode_request('examples.getStateName', $_POST['stateno'])); + +if ($r->faultCode()) + // HTTP transport error + echo 'Got error '.$r->faultCode(); +else +{ + // HTTP request OK, but XML returned from server not parsed yet + $v = xmlrpc_decode($r->value()); + // check if we got a valid xmlrpc response from server + if ($v === NULL) + echo 'Got invalid response'; + else + // check if server sent a fault response + if (xmlrpc_is_fault($v)) + echo 'Got xmlrpc fault '.$v['faultCode']; + else + echo'Got response: '.htmlentities($v); +} + +---- + + +[[substitution]] + +[appendix] +== Substitution of the PHP xmlrpc extension + +Yet another interesting situation is when you are using a ready-made + php application, that provides support for the XMLRPC protocol via the + native php xmlrpc extension, but the extension is not available on your + php install (e.g. because of shared hosting constraints). + +Since version 2.1, the PHP-XMLRPC library provides a compatibility + layer that aims to be 100% compliant with the xmlrpc extension API. This + means that any code written to run on the extension should obtain the + exact same results, albeit using more resources and a longer processing + time, using the PHP-XMLRPC library and the extension compatibility module. + The module is part of the EXTRAS package, available as a separate download + from the sourceforge.net website, since version 0.2 + + +[[enough]] + +[appendix] +== 'Enough of xmlrpcvals!': new style library usage + +To be documented... + +In the meantime, see docs about xmlrpc_client::return_type and + xmlrpc_server::functions_parameters_types, as well as php_xmlrpc_encode, + php_xmlrpc_decode and php_xmlrpc_decode_xml + + +[[debugger]] + +[appendix] +== Usage of the debugger + +A webservice debugger is included in the library to help during + development and testing. + +The interface should be self-explicative enough to need little + documentation. + +image::debugger.gif[,,,,align="center"] + +The most useful feature of the debugger is without doubt the "Show + debug info" option. It allows to have a screen dump of the complete http + communication between client and server, including the http headers as + well as the request and response payloads, and is invaluable when + troubleshooting problems with charset encoding, authentication or http + compression. + +The debugger can take advantage of the JSONRPC library extension, to + allow debugging of JSON-RPC webservices, and of the JS-XMLRPC library + visual editor to allow easy mouse-driven construction of the payload for + remote methods. Both components have to be downloaded separately from the + sourceforge.net web pages and copied to the debugger directory to enable + the extra functionality: + + +* to enable jsonrpc functionality, download the PHP-XMLRPC + EXTRAS package, and copy the file __jsonrpc.inc__ + either to the same directory as the debugger or somewhere in your + php include path + + +* to enable the visual value editing dialog, download the + JS-XMLRPC library, and copy somewhere in the web root files + __visualeditor.php__, + __visualeditor.css__ and the folders + __yui__ and __img__. Then edit the + debugger file __controller.php__ and set + appropriately the variable $editorpath. + + +[[news]] + +[appendix] + +== Whats's new + +CAUTION: not all items the following list have (yet) been fully documented, and some might not be present in any other + chapter in the manual. To find a more detailed description of new functions and methods please take a look at the + source code of the library, which is quite thoroughly commented in phpdoc form. + +=== 4.0.0 + +* new: introduction of namespaces and full OOP. ++ +All php classes have been renamed and moved to separate files. ++ +Class autoloading can now be done in accord with the PSR-4 standard. ++ +All global variables and global functions have been removed. ++ +Iterating over xmlrpc value objects is now easier thank to support for ArrayAccess and Traversable interfaces. ++ +Backward compatibility is maintained via _lib/xmlrpc.inc_, _lib/xmlrpcs.inc_ and _lib/xmlrpc_wrappers.inc_. + For more details, head on to doc/api_changes_v4.md + +* changed: the default character encoding delivered from the library to your code is now utf8. + It can be changed at any time setting a value to `PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding` + +* improved: the library now accepts requests/responses sent using other character sets than UTF-8/ISO-8859-1/ASCII. + This only works when the mbstring php extension is enabled. + +* improved: no need to call anymore `$client->setSSLVerifyHost(2)` to silence a curl warning when using https + with recent curl builds + +* improved: the xmlrpcval class now supports the interfaces `Countable` and `IteratorAggregate` + +* improved: a specific option allows users to decide the version of SSL to use for https calls. + This is useful f.e. for the testing suite, when the server target of calls has no proper ssl certificate, + and the cURL extension has been compiled with GnuTLS (such as on Travis VMs) + +* improved: the function `wrap_php_function()` now can be used to wrap closures (it is now a method btw) + +* improved: all _wrap_something()_ functions now return a closure by default instead of a function name + +* improved: debug messages are not html-escaped any more when executing from the command line + +* improved: the library is now tested using Travis ( https://travis-ci.org/ ). + Tests are executed using all php versions from 5.3 to 7.0 nightly, plus HHVM; code-coverage information + is generated using php 5.6 and uploaded to both Code Coverage and Scrutinizer online services + +* improved: phpunit is now installed via composer, not bundled anymore + +* improved: when phpunit is used to generate code-coverage data, the code executed server-side is accounted for + +* improved: the test suite has basic checks for the debugger and demo files + +* improved: more tests in the test suite + +* fixed: the server would not reset the user-set debug messages between subsequent `service()` calls + +* fixed: the server would not reset previous php error handlers when an exception was thrown by user code and + exception_handling set to 2 + +* fixed: the server would fail to decode a request with ISO-8859-1 payload and character set declaration in the xml + prolog only + +* fixed: the client would fail to decode a response with ISO-8859-1 payload and character set declaration in the xml + prolog only + +* fixed: the function `decode_xml()` would not decode an xml with character set declaration in the xml prolog + +* fixed: the client can now successfully call methods using ISO-8859-1 or UTF-8 characters in their name + +* fixed: the debugger would fail sending a request with ISO-8859-1 payload (it missed the character set declaration). + It would have a hard time coping with ISO-8859-1 in other fields, such as e.g. the remote method name + +* fixed: the debugger would generate a bad payload via the 'load method synopsis' button for signatures containing NULL + or undefined parameters + +* fixed: the debugger would generate a bad payload via the 'load method synopsis' button for methods with multiple + signatures + +* improved: the debugger is displayed using UTF-8, making it more useful to debug any kind of service + +* improved: echo all debug messages even when there are characters in them which php deems to be in a wrong encoding; + previously those messages would just disappear (this is visible e.g. in the debugger) + +* changed: debug info handling + - at debug level 1, the rebuilt php objects are not dumped to screen (server-side already did that) + - at debug level 1, curl communication info are not dumped to screen + - at debug level 1, the tests echo payloads of failures; at debug level 2 all payloads + +* improved: makefiles have been replaced with a php_based pakefile + +* improved: the source for the manual is stored in asciidoc format, which can be displayed natively by GitHub + with nice html formatting. Also the HTML version generated by hand and bundled in tarballs is much nicer + to look at than previous versions + +* improved: all php code is now formatted according to the PSR-2 standard + +=== 3.0.0 + +__Note:__ this is the last release of the library that will support PHP 5.1 and up. Future releases will target php 5.3 + as minimum supported version. + +* when using curl and keepalive, reset curl handle if we did not get back an http 200 response (eg a 302) + +* omit port on http 'Host' header if it is 80 + +* test suite allows interrogating https servers ignoring their certs + +* method `setAcceptedCompression` was failing to disable reception of compressed responses if the client supported them + +=== 3.0.0 beta + +This is the first release of the library to only support PHP 5. Some legacy code has been removed, and support for + features such as exceptions and dateTime objects introduced. + +The "beta" tag is meant to indicate the fact that the refactoring has been more widespread than in precedent releases + and that more changes are likely to be introduced with time - the library is still considered to be production + quality. + +* improved: removed all usage of php functions deprecated in php 5.3, usage of assign-by-ref when creating new objects + etc... + +* improved: add support for the `` tag used by the apache library, both in input and output + +* improved: add support for dateTime objects in both in php_xmlrpc_encode and as parameter for constructor of xmlrpcval + +* improved: add support for timestamps as parameter for constructor of xmlrpcval + +* improved: add option `dates_as_objects` to `php_xmlrpc_decode` to return dateTime objects for xmlrpc datetimes + +* improved: add new method `SetCurlOptions` to xmrlpc_client to allow extra flexibility in tweaking http config, such as + explicitly binding to an ip address + +* improved: add new method `SetUserAgent` to xmrlpc_client to to allow having different user-agent http headers + +* improved: add a new member variable in server class to allow fine-tuning of the encoding of returned values when the + server is in 'phpvals' mode + +* improved: allow servers in 'xmlrpcvals' mode to also register plain php functions by defining them in the dispatch map + with an added option + +* improved: catch exceptions thrown during execution of php functions exposed as methods by the server + +* fixed: bad encoding if same object is encoded twice using `php_xmlrpc_encode` + +=== 2.2.2 + +__Note:__ this is the last release of the library that will support PHP 4. Future releases (if any) should target + php 5.0 as minimum supported version. + +* fixed: encoding of utf-8 characters outside of the BMP plane + +* fixed: character set declarations surrounded by double quotes were not recognized in http headers + +* fixed: be more tolerant in detection of charset in http headers + +* fixed: fix detection of zlib.output_compression + +* fixed: use `feof()` to test if socket connections are to be closed instead of the number of bytes read (rare bug when + communicating with some servers) + +* fixed: format floating point values using the correct decimal separator even when php locale is set to one that uses + comma + +* fixed: improve robustness of the debugger when parsing weird results from non-compliant servers + +* php warning when receiving `false` in a bool value + +* improved: allow the add_to_map server method to add docs for single params too + +* improved: added the possibility to wrap for exposure as xmlrpc methods plain php class methods, object methods and even + whole classes + +=== 2.2.1 + +* fixed: work aroung bug in php 5.2.2 which broke support of `HTTP_RAW_POST_DATA` + +* fixed: is_dir parameter of `setCaCertificate()` method is reversed + +* fixed: a php warning in xmlrpc_client creator method + +* fixed: parsing of `1e+1` as valid float + +* fixed: allow errorlevel 3 to work when prev. error handler was a static method + +* fixed: usage of `client::setcookie()` for multiple cookies in non-ssl mode + +* improved: support for CP1252 charset is not part or the library but almost possible + +* improved: more info when curl is enabled and debug mode is on + +=== 2.2 + +* fixed: debugger errors on php installs with `magic_quotes_gpc` on + +* fixed: support for https connections via proxy + +* fixed: `wrap_xmlrpc_method()` generated code failed to properly encode php objects + +* improved: slightly faster encoding of data which is internally UTF-8 + +* improved: debugger always generates a `null` id for jsonrpc if user omits it + +* new: debugger can take advantage of a graphical value builder (it has to be downloaded separately, as part of jsxmlrpc + package. See Appendix D for more details) + +* new: support for the `` xmlrpc extension. see below for more details + +* new: server support for the `system.getCapabilities` xmlrpc extension + +* new: `wrap_xmlrpc_method`, `wrap_xmlrpc_method()` accepts two new options: debug and return_on_fault + +=== 2.1 + +* The wrap_php_function and wrap_xmlrpc_method functions have been moved out of the base library file _xmlrpc.inc_ + into a file of their own: _xmlrpc_wrappers.php_. You will have to include() / require() it in your scripts if + you have been using those functions. + For increased security, the automatic rebuilding of php object instances out ofreceived xmlrpc structs in + `wrap_xmlrpc_method()` has been disabled (but it can be optionally re-enabled). + Both `wrap_php_function()` and `wrap_xmlrpc_method()` functions accept many more options to fine tune their behaviour, + including one to return the php code to be saved and later used as standalone php script + +* The constructor of xmlrpcval() values has seen some internal changes, and it will not throw a php warning anymore when + invoked using an unknown xmlrpc type: the error will only be written to php error log. Also + `new xmlrpcval('true', 'boolean')` is not supported anymore + +* The new function `php_xmlrpc_decode_xml()` will take the xml representation of either an xmlrpc request, response or + single value and return the corresponding php-xmlrpc object instance + +* A new function `wrap_xmlrpc_server()` has been added, to wrap all (or some) of the methods exposed by a remote xmlrpc + server into a php class + +* A new file has been added: _verify_compat.php_, to help users diagnose the level of compliance of their php + installation with the library + +* Restored compatibility with php 4.0.5 (for those poor souls still stuck on it) + +* Method `xmlrpc_server->service()` now returns a value: either the response payload or xmlrpcresp object instance + +* Method `xmlrpc_server->add_to_map()` now accepts xmlrpc methods with no param definitions + +* Documentation for single parameters of exposed methods can be added to the dispatch map (and turned into html docs in + conjunction with a future release of the 'extras' package) + +* Full response payload is saved into xmlrpcresp object for further debugging + +* The debugger can now generate code that wraps a remote method into a php function (works for jsonrpc, too); it also + has better support for being activated via a single GET call (e.g. for integration into other tools) + +* Stricter parsing of incoming xmlrpc messages: two more invalid cases are now detected (double `data` element inside + `array` and `struct`/`array` after scalar inside `value` element) + +* More logging of errors in a lot of situations + +* Javadoc documentation of lib files (almost) complete + +* Many performance tweaks and code cleanups, plus the usual crop of bugs fixed (see NEWS file for complete list of bugs) + +* Lib internals have been modified to provide better support for grafting extra functionality on top of it. Stay tuned + for future releases of the EXTRAS package (or go read Appendix B)... + +=== 2.0 final + +* Added to the client class the possibility to use Digest and NTLM authentication methods (when using the CURL library) + for connecting to servers and NTLM for connecting to proxies + +* Added to the client class the possibility to specify alternate certificate files/directories for authenticating the + peer with when using HTTPS communication + +* Reviewed all examples and added a new demo file, containing a proxy to forward xmlrpc requests to other servers + (useful e.g. for ajax coding) + +* The debugger has been upgraded to reflect the new client capabilities + +* All known bugs have been squashed, and the lib is more tolerant than ever of commonly-found mistakes + +=== 2.0 Release candidate 3 + +* Added to server class the property functions_parameters_type, that allows the server to register plain php functions + as xmlrpc methods (i.e. functions that do not take an xmlrpcmsg object as unique param) + +* let server and client objects serialize calls using a specified character set encoding for the produced xml instead of + US-ASCII (ISO-8859-1 and UTF-8 supported) + +* let `php_xmlrpc_decode` accept xmlrpcmsg objects as valid input + +* 'class::method' syntax is now accepted in the server dispatch map + +* `xmlrpc_clent::SetDebug()` accepts integer values instead of a boolean value, with debugging level 2 adding to the + information printed to screen the complete client request + +=== 2.0 Release candidate 2 + +* Added a new property of the client object: `xmlrpc_client->return_type`, indicating whether calls to the + send() method will return xmlrpcresp objects whose value() is an xmlrpcval object, a php value (automatically + decoded) or the raw xml received from the server. + +* Added in the extras dir. two new library files: _jsonrpc.inc_ and _jsonrpcs.inc_ containing new classes that + implement support for the json-rpc protocol (alpha quality code) + +* Added a new client method: `setKey($key, $keypass)` to be used in HTTPS connections + +* Added a new file containing some benchmarks in the testsuite directory + +=== 2.0 Release candidate 1 + +* Support for HTTP proxies (new method: `xmlrpc_client::setProxy()`) + +* Support HTTP compression of both requests and responses. + Clients can specify what kind of compression they accept for responses between deflate/gzip/any, and whether to + compress the requests. + Servers by default compress responses to clients that explicitly declare support for compression (new methods: + `xmlrpc_client::setAcceptedCompression()`, `xmlrpc_client::setRequestCompression()`). + Note that the ZLIB php extension needs to be enabled in PHP to support compression. + +* Implement HTTP 1.1 connections, but only if CURL is enabled (added an extra parameter to + `xmlrpc_client::xmlrpc_client` to set the desired HTTP protocol at creation time and a new supported value for + the last parameter of `xmlrpc_client::send`, which now can be safely omitted if it has been specified at + creation time). ++ +With PHP versions greater than 4.3.8 keep-alives are enabled by default for HTTP 1.1 connections. This should yield + faster execution times when making multiple calls in sequence to the same xml-rpc server from a single client. + +* Introduce support for cookies. + Cookies to be sent to the server with a request can be set using `xmlrpc_client::setCookie()`, while cookies + received from the server are found in ++xmlrpcresp::cookies()++. It is left to the user to check for validity of + received cookies and decide whether they apply to successive calls or not. + +* Better support for detecting different character set encodings of xml-rpc requests and responses: both client and + server objects will correctly detect the charset encoding of received xml, and use an appropriate xml parser. ++ +Supported encodings are US-ASCII, UTF-8 and ISO-8859-1. + +* Added one new xmlrpcmsg constructor syntax, allowing usage of a single string with the complete URL of the target + server + +* Convert xml-rpc boolean values into native php values instead of 0 and 1 + +* Force the `php_xmlrpc_encode` function to properly encode numerically indexed php arrays into xml-rpc arrays + (numerically indexed php arrays always start with a key of 0 and increment keys by values of 1) + +* Prevent the `php_xmlrpc_encode` function from further re-encoding any objects of class ++xmlrpcval++ that + are passed to it. This allows to call the function with arguments consisting of mixed php values / xmlrpcval objects + +* Allow a server to NOT respond to system.* method calls (setting the `$server->allow_system_funcs` property). + +* Implement a new xmlrpcval method to determine if a value of type struct has a member of a given name without having to + loop trough all members: `xmlrpcval::structMemExists()` + +* Expand methods `xmlrpcval::addArray`, `addScalar` and `addStruct` allowing extra php values to be added to + xmlrpcval objects already formed. + +* Let the `xmlrpc_client::send` method accept an XML string for sending instead of an xmlrpcmsg object, to + facilitate debugging and integration with the php native xmlrpc extension + +* Extend the `php_xmlrpc_encode` and `php_xmlrpc_decode` functions to allow serialization and rebuilding of + PHP objects. To successfully rebuild a serialized object, the object class must be defined in the deserializing end + of the transfer. Note that object members of type resource will be deserialized as NULL values. ++ +Note that his has been implemented adding a "php_class" attribute to xml representation of xmlrpcval of STRUCT type, + which, strictly speaking, breaks the xml-rpc spec. Other xmlrpc implementations are supposed to ignore such an + attribute (unless they implement a brain-dead custom xml parser...), so it should be safe enabling it in + heterogeneous environments. The activation of this feature is done by usage of an option passed as second parameter + to both `php_xmlrpc_encode` and `php_xmlrpc_decode`. + +* Extend the `php_xmlrpc_encode` function to allow automatic serialization of iso8601-conforming php strings as + datetime.iso8601 xmlrpcvals, by usage of an optional parameter + +* Added an automatic stub code generator for converting xmlrpc methods to php functions and vice-versa. ++ +This is done via two new functions: `wrap_php_function` and `wrap_xmlrpc_method`, and has many caveats, + with php being a typeless language and all... + +* Allow object methods to be used in server dispatch map + +* Added a complete debugger solution, in the __debugger__ folder + +* Added configurable server-side debug messages, controlled by the new method `xmlrpc_server::SetDebug()`. + At level 0, no debug messages are sent to the client; level 1 is the same as the old behaviour; at level 2 a lot + more info is echoed back to the client, regarding the received call; at level 3 all warnings raised during server + processing are trapped (this prevents breaking the xml to be echoed back to the client) and added to the debug info + sent back to the client + +* New XML parsing code, yields smaller memory footprint and faster execution times, not to mention complete elimination + of the dreaded __eval()__ construct, so prone to code injection exploits + +* Rewritten most of the error messages, making text more explicative + +++++++++++++++++++++++++++++++++++++++ + +++++++++++++++++++++++++++++++++++++++ diff --git a/lib/phpxmlrpc/extras/rsakey.pem b/lib/phpxmlrpc/extras/rsakey.pem new file mode 100644 index 0000000..473f652 --- /dev/null +++ b/lib/phpxmlrpc/extras/rsakey.pem @@ -0,0 +1,9 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIBOgIBAAJBAM12w6/J20HMj0V9VC24xPFQG9RKSDt8vmviM+tnc1BgCrzPyF1v +3/rWGoWDjkJrE9WFOeqIjJHeEWWT4uKq2ZkCAwEAAQJAZZYJ7Nld+et9DvuHak/H +uBRGnjDYA+mKcObXitWMUzk2ZodL8UoCP1J9kKqV8Zp/l2cBZkLo0aWTN94sWkHy +rQIhAOhxWxRXSZ4kArIQqZnDG9JgtOAeaaFso/zpxIHpN6OrAiEA4klzl+rUc32/ +7SDcJYa9j5vehp1jCTnkN+n0rujTM8sCIAGwMRUovSQk5tAcRt8TB7SzdxzZm7LM +czR3DjJTW1AZAiEAlYN+svPgJ+cAdwdtLgZXHZoZb8xx8Vik6CTXHPKNCf0CIBQL +zF4Qp8/C+gjsXtEZJvhxY7i1luHn6iNwNnE932r3 +-----END RSA PRIVATE KEY----- diff --git a/lib/phpxmlrpc/extras/test.pl b/lib/phpxmlrpc/extras/test.pl new file mode 100644 index 0000000..6c7df55 --- /dev/null +++ b/lib/phpxmlrpc/extras/test.pl @@ -0,0 +1,52 @@ +#!/usr/local/bin/perl + +use Frontier::Client; + +my $serverURL='http://phpxmlrpc.sourceforge.net/server.php'; + +# try the simplest example + +my $client = Frontier::Client->new( 'url' => $serverURL, + 'debug' => 0, 'encoding' => 'iso-8859-1' ); +my $resp = $client->call("examples.getStateName", 32); + +print "Got '${resp}'\n"; + +# now send a mail to nobody in particular + +$resp = $client->call("mail.send", ("edd", "Test", + "Bonjour. Je m'appelle Grard. Maana. ", "freddy", "", "", + 'text/plain; charset="iso-8859-1"')); + +if ($resp->value()) { + print "Mail sent OK.\n"; +} else { + print "Error sending mail.\n"; +} + +# test echoing of characters works fine + +$resp = $client->call("examples.echo", 'Three "blind" mice - ' . + "See 'how' they run"); +print $resp . "\n"; + +# test name and age example. this exercises structs and arrays + +$resp = $client->call("examples.sortByAge", + [ { 'name' => 'Dave', 'age' => 35}, + { 'name' => 'Edd', 'age' => 45 }, + { 'name' => 'Fred', 'age' => 23 }, + { 'name' => 'Barney', 'age' => 36 } ] ); + +my $e; +foreach $e (@$resp) { + print $$e{'name'} . ", " . $$e{'age'} . "\n"; +} + +# test base64 + +$resp = $client->call("examples.decode64", + $client->base64("TWFyeSBoYWQgYSBsaXR0bGUgbGFtYiBTaGUgd" . + "GllZCBpdCB0byBhIHB5bG9u")); + +print $resp . "\n"; diff --git a/lib/phpxmlrpc/extras/test.py b/lib/phpxmlrpc/extras/test.py new file mode 100644 index 0000000..f554b89 --- /dev/null +++ b/lib/phpxmlrpc/extras/test.py @@ -0,0 +1,37 @@ +#!/usr/local/bin/python + +from xmlrpclib import * +import sys + +server = Server("http://phpxmlrpc.sourceforge.net/server.php") + +try: + print "Got '" + server.examples.getStateName(32) + "'" + + r = server.mail.send("edd", "Test", + "Bonjour. Je m'appelle Grard. Maana. ", "freddy", "", "", + 'text/plain; charset="iso-8859-1"') + if r: + print "Mail sent OK" + else: + print "Error sending mail" + + + r = server.examples.echo('Three "blind" mice - ' + "See 'how' they run") + print r + + # name/age example. this exercises structs and arrays + + a = [ {'name': 'Dave', 'age': 35}, {'name': 'Edd', 'age': 45 }, + {'name': 'Fred', 'age': 23}, {'name': 'Barney', 'age': 36 }] + r = server.examples.sortByAge(a) + print r + + # test base 64 + b = Binary("Mary had a little lamb She tied it to a pylon") + b.encode(sys.stdout) + r = server.examples.decode64(b) + print r + +except Error, v: + print "XML-RPC Error:",v diff --git a/lib/phpxmlrpc/extras/workspace.testPhpServer.fttb b/lib/phpxmlrpc/extras/workspace.testPhpServer.fttb new file mode 100644 index 0000000..8d50758 --- /dev/null +++ b/lib/phpxmlrpc/extras/workspace.testPhpServer.fttb @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/lib/phpxmlrpc/lib/xmlrpc.inc b/lib/phpxmlrpc/lib/xmlrpc.inc new file mode 100644 index 0000000..28b47d3 --- /dev/null +++ b/lib/phpxmlrpc/lib/xmlrpc.inc @@ -0,0 +1,217 @@ + + +// Copyright (c) 1999,2000,2002 Edd Dumbill. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// +// * Neither the name of the "XML-RPC for PHP" nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +// OF THE POSSIBILITY OF SUCH DAMAGE. + +/****************************************************************************** + * + * *** DEPRECATED *** + * + * This file is only used to insure backwards compatibility + * with the API of the library <= rev. 3 + * + * If it is included, the library will work without any further autoloading + *****************************************************************************/ + +include_once(__DIR__.'/../src/PhpXmlRpc.php'); +include_once(__DIR__.'/../src/Value.php'); +include_once(__DIR__.'/../src/Request.php'); +include_once(__DIR__.'/../src/Response.php'); +include_once(__DIR__.'/../src/Client.php'); +include_once(__DIR__.'/../src/Encoder.php'); +include_once(__DIR__.'/../src/Helper/Charset.php'); +include_once(__DIR__.'/../src/Helper/Date.php'); +include_once(__DIR__.'/../src/Helper/Http.php'); +include_once(__DIR__.'/../src/Helper/Logger.php'); +include_once(__DIR__.'/../src/Helper/XMLParser.php'); + + +/* Expose the global variables which used to be defined */ +PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'ISO-8859-1'; // old default +PhpXmlRpc\PhpXmlRpc::exportGlobals(); + +/* some stuff deprecated enough that we do not want to put it in the new lib version */ + +/// @deprecated +$GLOBALS['xmlEntities'] = array( + 'amp' => '&', + 'quot' => '"', + 'lt' => '<', + 'gt' => '>', + 'apos' => "'" +); + +// formulate backslashes for escaping regexp +// Not in use anymore since 2.0. Shall we remove it? +/// @deprecated +$GLOBALS['xmlrpc_backslash'] = chr(92).chr(92); + +/* Expose with the old names the classes which have been namespaced */ + +class xmlrpcval extends PhpXmlRpc\Value +{ + /** + * @deprecated + * @param xmlrpcval $o + * @return string + */ + public function serializeval($o) + { + // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals... + //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval'))) + //{ + $ar = $o->me; + reset($ar); + list($typ, $val) = each($ar); + + return '' . $this->serializedata($typ, $val) . "\n"; + //} + } + + /** + * @deprecated this code looks like it is very fragile and has not been fixed + * for a long long time. Shall we remove it for 2.0? + */ + public function getval() + { + // UNSTABLE + reset($this->me); + list($a, $b) = each($this->me); + // contributed by I Sofer, 2001-03-24 + // add support for nested arrays to scalarval + // i've created a new method here, so as to + // preserve back compatibility + + if (is_array($b)) { + @reset($b); + while (list($id, $cont) = @each($b)) { + $b[$id] = $cont->scalarval(); + } + } + + // add support for structures directly encoding php objects + if (is_object($b)) { + $t = get_object_vars($b); + @reset($t); + while (list($id, $cont) = @each($t)) { + $t[$id] = $cont->scalarval(); + } + @reset($t); + while (list($id, $cont) = @each($t)) { + @$b->$id = $cont; + } + } + // end contrib + return $b; + } + + /// reset functionality added by parent class: same as it would happen if no interface was declared + public function count() + { + return 1; + } + + /// reset functionality added by parent class: same as it would happen if no interface was declared + public function getIterator() { + return new ArrayIterator($this); + } +} + +class xmlrpcmsg extends PhpXmlRpc\Request +{ +} + +class xmlrpcresp extends PhpXmlRpc\Response +{ +} + +class xmlrpc_client extends PhpXmlRpc\Client +{ +} + +/* Expose as global functions the ones which are now class methods */ + +/// Wrong speling, but we are adamant on backwards compatibility! +function xmlrpc_encode_entitites($data, $srcEncoding='', $destEncoding='') +{ + return PhpXmlRpc\Helper\Charset::instance()->encodeEntitites($data, $srcEncoding, $destEncoding); +} + +function iso8601_encode($timeT, $utc=0) +{ + return PhpXmlRpc\Helper\Date::iso8601Encode($timeT, $utc); +} + +function iso8601_decode($iDate, $utc=0) +{ + return PhpXmlRpc\Helper\Date::iso8601Decode($iDate, $utc); +} + +function decode_chunked($buffer) +{ + return PhpXmlRpc\Helper\Http::decodeChunked($buffer); +} + +function php_xmlrpc_decode($xmlrpcVal, $options=array()) +{ + $encoder = new PhpXmlRpc\Encoder(); + return $encoder->decode($xmlrpcVal, $options); +} + +function php_xmlrpc_encode($phpVal, $options=array()) +{ + $encoder = new PhpXmlRpc\Encoder(); + return $encoder->encode($phpVal, $options); +} + +function php_xmlrpc_decode_xml($xmlVal, $options=array()) +{ + $encoder = new PhpXmlRpc\Encoder(); + return $encoder->decodeXml($xmlVal, $options); +} + +function guess_encoding($httpHeader='', $xmlChunk='', $encodingPrefs=null) +{ + return PhpXmlRpc\Helper\XMLParser::guessEncoding($httpHeader, $xmlChunk, $encodingPrefs); +} + +function has_encoding($xmlChunk) +{ + return PhpXmlRpc\Helper\XMLParser::hasEncoding($xmlChunk); +} + +function is_valid_charset($encoding, $validList) +{ + return PhpXmlRpc\Helper\Charset::instance()->isValidCharset($encoding, $validList); +} diff --git a/lib/phpxmlrpc/lib/xmlrpc_wrappers.inc b/lib/phpxmlrpc/lib/xmlrpc_wrappers.inc new file mode 100644 index 0000000..cec3374 --- /dev/null +++ b/lib/phpxmlrpc/lib/xmlrpc_wrappers.inc @@ -0,0 +1,243 @@ +php2XmlrpcType($phpType); +} + +/** + * @see PhpXmlRpc\Wrapper::xmlrpc_2_php_type + * @param string $xmlrpcType + * @return string + */ +function xmlrpc_2_php_type($xmlrpcType) +{ + $wrapper = new PhpXmlRpc\Wrapper(); + return $wrapper->xmlrpc2PhpType($xmlrpcType); +} + +/** + * @see PhpXmlRpc\Wrapper::wrap_php_function + * @param callable $funcName + * @param string $newFuncName + * @param array $extraOptions + * @return array|false + */ +function wrap_php_function($funcName, $newFuncName='', $extraOptions=array()) +{ + $wrapper = new PhpXmlRpc\Wrapper(); + if (!isset($extraOptions['return_source']) || $extraOptions['return_source'] == false) { + // backwards compat: return string instead of callable + $extraOptions['return_source'] = true; + $wrapped = $wrapper->wrapPhpFunction($funcName, $newFuncName, $extraOptions); + eval($wrapped['source']); + } else { + $wrapped = $wrapper->wrapPhpFunction($funcName, $newFuncName, $extraOptions); + } + return $wrapped; +} + +/** + * NB: this function returns an array in a format which is unsuitable for direct use in the server dispatch map, unlike + * PhpXmlRpc\Wrapper::wrapPhpClass. This behaviour might seem like a bug, but has been kept for backwards compatibility. + * + * @see PhpXmlRpc\Wrapper::wrap_php_class + * @param string|object $className + * @param array $extraOptions + * @return array|false + */ +function wrap_php_class($className, $extraOptions=array()) +{ + $wrapper = new PhpXmlRpc\Wrapper(); + $fix = false; + if (!isset($extraOptions['return_source']) || $extraOptions['return_source'] == false) { + // backwards compat: return string instead of callable + $extraOptions['return_source'] = true; + $fix = true; + } + $wrapped = $wrapper->wrapPhpClass($className, $extraOptions); + foreach($wrapped as $name => $value) { + if ($fix) { + eval($value['source']); + } + $wrapped[$name] = $value['function']; + } + return $wrapped; +} + +/** + * @see PhpXmlRpc\Wrapper::wrapXmlrpcMethod + * @param xmlrpc_client $client + * @param string $methodName + * @param int|array $extraOptions the usage of an int as signature number is deprecated, use an option in $extraOptions + * @param int $timeout deprecated, use an option in $extraOptions + * @param string $protocol deprecated, use an option in $extraOptions + * @param string $newFuncName deprecated, use an option in $extraOptions + * @return array|callable|false + */ +function wrap_xmlrpc_method($client, $methodName, $extraOptions=0, $timeout=0, $protocol='', $newFuncName='') +{ + if (!is_array($extraOptions)) + { + $sigNum = $extraOptions; + $extraOptions = array( + 'signum' => $sigNum, + 'timeout' => $timeout, + 'protocol' => $protocol, + 'new_function_name' => $newFuncName + ); + } + + $wrapper = new PhpXmlRpc\Wrapper(); + + if (!isset($extraOptions['return_source']) || $extraOptions['return_source'] == false) { + // backwards compat: return string instead of callable + $extraOptions['return_source'] = true; + $wrapped = $wrapper->wrapXmlrpcMethod($client, $methodName, $extraOptions); + eval($wrapped['source']); + $wrapped = $wrapped['function']; + } else { + $wrapped = $wrapper->wrapXmlrpcMethod($client, $methodName, $extraOptions); + } + return $wrapped; +} + +/** + * @see PhpXmlRpc\Wrapper::wrap_xmlrpc_server + * @param xmlrpc_client $client + * @param array $extraOptions + * @return mixed + */ +function wrap_xmlrpc_server($client, $extraOptions=array()) +{ + $wrapper = new PhpXmlRpc\Wrapper(); + return $wrapper->wrapXmlrpcServer($client, $extraOptions); +} + +/** + * Given the necessary info, build php code that creates a new function to invoke a remote xmlrpc method. + * Take care that no full checking of input parameters is done to ensure that valid php code is emitted. + * Only kept for backwards compatibility + * Note: real spaghetti code follows... + * + * @deprecated + */ +function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFuncName, + $mSig, $mDesc = '', $timeout = 0, $protocol = '', $clientCopyMode = 0, $prefix = 'xmlrpc', + $decodePhpObjects = false, $encodePhpObjects = false, $decodeFault = false, + $faultResponse = '', $namespace = '\\PhpXmlRpc\\') +{ + $code = "function $xmlrpcFuncName ("; + if ($clientCopyMode < 2) { + // client copy mode 0 or 1 == partial / full client copy in emitted code + $innerCode = build_client_wrapper_code($client, $clientCopyMode, $prefix, $namespace); + $innerCode .= "\$client->setDebug(\$debug);\n"; + $this_ = ''; + } else { + // client copy mode 2 == no client copy in emitted code + $innerCode = ''; + $this_ = 'this->'; + } + $innerCode .= "\$req = new {$namespace}Request('$methodName');\n"; + + if ($mDesc != '') { + // take care that PHP comment is not terminated unwillingly by method description + $mDesc = "/**\n* " . str_replace('*/', '* /', $mDesc) . "\n"; + } else { + $mDesc = "/**\nFunction $xmlrpcFuncName\n"; + } + + // param parsing + $innerCode .= "\$encoder = new {$namespace}Encoder();\n"; + $plist = array(); + $pCount = count($mSig); + for ($i = 1; $i < $pCount; $i++) { + $plist[] = "\$p$i"; + $pType = $mSig[$i]; + if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' || + $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null' + ) { + // only build directly xmlrpc values when type is known and scalar + $innerCode .= "\$p$i = new {$namespace}Value(\$p$i, '$pType');\n"; + } else { + if ($encodePhpObjects) { + $innerCode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n"; + } else { + $innerCode .= "\$p$i = \$encoder->encode(\$p$i);\n"; + } + } + $innerCode .= "\$req->addparam(\$p$i);\n"; + $mDesc .= '* @param ' . xmlrpc_2_php_type($pType) . " \$p$i\n"; + } + if ($clientCopyMode < 2) { + $plist[] = '$debug=0'; + $mDesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n"; + } + $plist = implode(', ', $plist); + $mDesc .= '* @return ' . xmlrpc_2_php_type($mSig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n"; + + $innerCode .= "\$res = \${$this_}client->send(\$req, $timeout, '$protocol');\n"; + if ($decodeFault) { + if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) || (strpos($faultResponse, '%faultString%') !== false))) { + $respCode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $faultResponse) . "')"; + } else { + $respCode = var_export($faultResponse, true); + } + } else { + $respCode = '$res'; + } + if ($decodePhpObjects) { + $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));"; + } else { + $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value());"; + } + + $code = $code . $plist . ") {\n" . $innerCode . "\n}\n"; + + return array('source' => $code, 'docstring' => $mDesc); +} + +/** + * @deprecated + */ +function build_client_wrapper_code($client, $verbatim_client_copy, $prefix='xmlrpc') +{ + $code = "\$client = new {$prefix}_client('".str_replace("'", "\'", $client->path). + "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n"; + + // copy all client fields to the client that will be generated runtime + // (this provides for future expansion or subclassing of client obj) + if ($verbatim_client_copy) + { + foreach($client as $fld => $val) + { + if($fld != 'debug' && $fld != 'return_type') + { + $val = var_export($val, true); + $code .= "\$client->$fld = $val;\n"; + } + } + } + // only make sure that client always returns the correct data type + $code .= "\$client->return_type = '{$prefix}vals';\n"; + //$code .= "\$client->setDebug(\$debug);\n"; + return $code; +} diff --git a/lib/phpxmlrpc/lib/xmlrpcs.inc b/lib/phpxmlrpc/lib/xmlrpcs.inc new file mode 100644 index 0000000..71cde1f --- /dev/null +++ b/lib/phpxmlrpc/lib/xmlrpcs.inc @@ -0,0 +1,121 @@ + + +// Copyright (c) 1999,2000,2002 Edd Dumbill. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// +// * Neither the name of the "XML-RPC for PHP" nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +// OF THE POSSIBILITY OF SUCH DAMAGE. + +/****************************************************************************** + * + * *** DEPRECATED *** + * + * This file is only used to insure backwards compatibility + * with the API of the library <= rev. 3 + *****************************************************************************/ + +include_once(__DIR__.'/../src/Server.php'); + +class xmlrpc_server extends PhpXmlRpc\Server +{ + /** + * A debugging routine: just echoes back the input packet as a string value + * @deprecated + */ + public function echoInput() + { + $r = new Response(new PhpXmlRpc\Value("'Aha said I: '" . file_get_contents('php://input'), 'string')); + print $r->serialize(); + } +} + +/* Expose as global functions the ones which are now class methods */ + +/** + * @see PhpXmlRpc\Server::xmlrpc_debugmsg + * @param string $m + */ +function xmlrpc_debugmsg($m) +{ + PhpXmlRpc\Server::xmlrpc_debugmsg($m); +} + +function _xmlrpcs_getCapabilities($server, $m=null) +{ + return PhpXmlRpc\Server::_xmlrpcs_getCapabilities($server, $m); +} + +$_xmlrpcs_listMethods_sig=array(array($GLOBALS['xmlrpcArray'])); +$_xmlrpcs_listMethods_doc='This method lists all the methods that the XML-RPC server knows how to dispatch'; +$_xmlrpcs_listMethods_sdoc=array(array('list of method names')); +function _xmlrpcs_listMethods($server, $m=null) // if called in plain php values mode, second param is missing +{ + return PhpXmlRpc\Server::_xmlrpcs_listMethods($server, $m); +} + +$_xmlrpcs_methodSignature_sig=array(array($GLOBALS['xmlrpcArray'], $GLOBALS['xmlrpcString'])); +$_xmlrpcs_methodSignature_doc='Returns an array of known signatures (an array of arrays) for the method name passed. If no signatures are known, returns a none-array (test for type != array to detect missing signature)'; +$_xmlrpcs_methodSignature_sdoc=array(array('list of known signatures, each sig being an array of xmlrpc type names', 'name of method to be described')); +function _xmlrpcs_methodSignature($server, $m) +{ + return PhpXmlRpc\Server::_xmlrpcs_methodSignature($server, $m); +} + +$_xmlrpcs_methodHelp_sig=array(array($GLOBALS['xmlrpcString'], $GLOBALS['xmlrpcString'])); +$_xmlrpcs_methodHelp_doc='Returns help text if defined for the method passed, otherwise returns an empty string'; +$_xmlrpcs_methodHelp_sdoc=array(array('method description', 'name of the method to be described')); +function _xmlrpcs_methodHelp($server, $m) +{ + return PhpXmlRpc\Server::_xmlrpcs_methodHelp($server, $m); +} + +function _xmlrpcs_multicall_error($err) +{ + return PhpXmlRpc\Server::_xmlrpcs_multicall_error($err); +} + +function _xmlrpcs_multicall_do_call($server, $call) +{ + return PhpXmlRpc\Server::_xmlrpcs_multicall_do_call($server, $call); +} + +function _xmlrpcs_multicall_do_call_phpvals($server, $call) +{ + return PhpXmlRpc\Server::_xmlrpcs_multicall_do_call_phpvals($server, $call); +} + +$_xmlrpcs_multicall_sig = array(array($GLOBALS['xmlrpcArray'], $GLOBALS['xmlrpcArray'])); +$_xmlrpcs_multicall_doc = 'Boxcar multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details'; +$_xmlrpcs_multicall_sdoc = array(array('list of response structs, where each struct has the usual members', 'list of calls, with each call being represented as a struct, with members "methodname" and "params"')); +function _xmlrpcs_multicall($server, $m) +{ + return PhpXmlRpc\Server::_xmlrpcs_multicall($server, $m); +} diff --git a/lib/phpxmlrpc/license.txt b/lib/phpxmlrpc/license.txt new file mode 100644 index 0000000..37313ac --- /dev/null +++ b/lib/phpxmlrpc/license.txt @@ -0,0 +1,29 @@ +Software License Agreement (BSD License) + +Copyright (c) 1999,2000,2001 Edd Dumbill, Useful Information Company +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name of the "XML-RPC for PHP" nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/lib/phpxmlrpc/pakefile.php b/lib/phpxmlrpc/pakefile.php new file mode 100644 index 0000000..4bca828 --- /dev/null +++ b/lib/phpxmlrpc/pakefile.php @@ -0,0 +1,400 @@ + 'asciidoctor', + 'fop' => 'fop', + 'php' => 'php', + 'zip' => 'zip', + ); + protected static $options = array( + 'repo' => 'https://github.com/gggeek/phpxmlrpc', + 'branch' => 'master' + ); + + public static function libVersion() + { + if (self::$libVersion == null) + throw new \Exception('Missing library version argument'); + return self::$libVersion; + } + + public static function buildDir() + { + return self::$buildDir; + } + + public static function workspaceDir() + { + return self::buildDir().'/workspace'; + } + + /// most likely things will break if this one is moved outside of BuildDir + public static function distDir() + { + return self::buildDir().'/xmlrpc-'.self::libVersion(); + } + + /// these will be generated in BuildDir + public static function distFiles() + { + return array( + 'xmlrpc-'.self::libVersion().'.tar.gz', + 'xmlrpc-'.self::libVersion().'.zip', + ); + } + + public static function getOpts($args=array(), $cliOpts=array()) + { + if (count($args) > 0) + // throw new \Exception('Missing library version argument'); + self::$libVersion = $args[0]; + + foreach (self::$tools as $name => $binary) { + if (isset($cliOpts[$name])) { + self::$tools[$name] = $cliOpts[$name]; + } + } + + foreach (self::$options as $name => $value) { + if (isset($cliOpts[$name])) { + self::$options[$name] = $cliOpts[$name]; + } + } + + //pake_echo('---'.self::$libVersion.'---'); + } + + /** + * @param string $name + * @return string + */ + public static function tool($name) + { + return self::$tools[$name]; + } + + /** + * @param string $name + * @return string + */ + public static function option($name) + { + return self::$options[$name]; + } + + /** + * @param string $inFile + * @param string $xssFile + * @param string $outFileOrDir + * @throws \Exception + */ + public static function applyXslt($inFile, $xssFile, $outFileOrDir) + { + + if (!file_exists($inFile)) { + throw new \Exception("File $inFile cannot be found"); + } + if (!file_exists($xssFile)) { + throw new \Exception("File $xssFile cannot be found"); + } + + // Load the XML source + $xml = new \DOMDocument(); + $xml->load($inFile); + $xsl = new \DOMDocument(); + $xsl->load($xssFile); + + // Configure the transformer + $processor = new \XSLTProcessor(); + if (version_compare(PHP_VERSION, '5.4', "<")) { + if (defined('XSL_SECPREF_WRITE_FILE')) { + ini_set("xsl.security_prefs", XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE); + } + } else { + // the php online docs only mention setSecurityPrefs, but somehow some installs have setSecurityPreferences... + if (method_exists('XSLTProcessor', 'setSecurityPrefs')) { + $processor->setSecurityPrefs(XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE); + } else { + $processor->setSecurityPreferences(XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE); + } + } + $processor->importStyleSheet($xsl); // attach the xsl rules + + if (is_dir($outFileOrDir)) { + if (!$processor->setParameter('', 'base.dir', realpath($outFileOrDir))) { + echo "setting param base.dir KO\n"; + } + } + + $out = $processor->transformToXML($xml); + + if (!is_dir($outFileOrDir)) { + file_put_contents($outFileOrDir, $out); + } + } + + public static function highlightPhpInHtml($content) + { + $startTag = '
    ';
    +        $endTag = '
    '; + + //$content = file_get_contents($inFile); + $last = 0; + $out = ''; + while (($start = strpos($content, $startTag, $last)) !== false) { + $end = strpos($content, $endTag, $start); + $code = substr($content, $start + strlen($startTag), $end - $start - strlen($startTag)); + if ($code[strlen($code) - 1] == "\n") { + $code = substr($code, 0, -1); + } + + $code = str_replace(array('>', '<'), array('>', '<'), $code); + $code = highlight_string('<?php 
    ', '', $code); + + $out = $out . substr($content, $last, $start + strlen($startTag) - $last) . $code . $endTag; + $last = $end + strlen($endTag); + } + $out .= substr($content, $last, strlen($content)); + + return $out; + } +} + +} + +namespace { + +use PhpXmlRpc\Builder; + +function run_default($task=null, $args=array(), $cliOpts=array()) +{ + echo "Syntax: pake {\$pake-options} \$task \$lib-version [\$git-tag] {\$task-options}\n"; + echo "\n"; + echo " Run 'pake help' to list all pake options\n"; + echo " Run 'pake -T' to list available tasks\n"; + echo " Run 'pake -P' to list all available tasks (including hidden ones) and their dependencies\n"; + echo "\n"; + echo " Task options:\n"; + echo " --repo=REPO URL of the source repository to clone. Defaults to the github repo.\n"; + echo " --branch=BRANCH The git branch to build from.\n"; + echo " --asciidoctor=ASCIIDOCTOR Location of the asciidoctor command-line tool\n"; + echo " --fop=FOP Location of the apache fop command-line tool\n"; + echo " --php=PHP Location of the php command-line interpreter\n"; + echo " --zip=ZIP Location of the zip tool\n"; +} + +function run_getopts($task=null, $args=array(), $cliOpts=array()) +{ + Builder::getOpts($args, $cliOpts); +} + +/** + * Downloads source code in the build workspace directory, optionally checking out the given branch/tag + */ +function run_init($task=null, $args=array(), $cliOpts=array()) +{ + // download the current version into the workspace + $targetDir = Builder::workspaceDir(); + + // check if workspace exists and is not already set to the correct repo + if (is_dir($targetDir) && pakeGit::isRepository($targetDir)) { + $repo = new pakeGit($targetDir); + $remotes = $repo->remotes(); + if (trim($remotes['origin']['fetch']) != Builder::option('repo')) { + throw new Exception("Directory '$targetDir' exists and is not linked to correct git repo"); + } + + /// @todo should we not just fetch instead? + $repo->pull(); + } else { + pake_mkdirs(dirname($targetDir)); + $repo = pakeGit::clone_repository(Builder::option('repo'), Builder::workspaceDir()); + } + + $repo->checkout(Builder::option('branch')); +} + +/** + * Runs all the build steps. + * + * (does nothing by itself, as all the steps are managed via task dependencies) + */ +function run_build($task=null, $args=array(), $cliOpts=array()) +{ +} + +function run_clean_doc() +{ + pake_remove_dir(Builder::workspaceDir().'/doc/api'); + $finder = pakeFinder::type('file')->name('*.html'); + pake_remove($finder, Builder::workspaceDir().'/doc/manual'); + $finder = pakeFinder::type('file')->name('*.xml'); + pake_remove($finder, Builder::workspaceDir().'/doc/manual'); +} + +/** + * Generates documentation in all formats + */ +function run_doc($task=null, $args=array(), $cliOpts=array()) +{ + $docDir = Builder::workspaceDir().'/doc'; + + // API docs + + // from phpdoc comments using phpdocumentor + //$cmd = Builder::tool('php'); + //pake_sh("$cmd vendor/phpdocumentor/phpdocumentor/bin/phpdoc run -d ".Builder::workspaceDir().'/src'." -t ".Builder::workspaceDir().'/doc/api --title PHP-XMLRPC'); + + // from phpdoc comments using Sami + $samiConfig = <<files() + ->exclude('debugger') + ->exclude('demo') + ->exclude('doc') + ->exclude('tests') + ->in('./build/workspace'); + return new Sami\Sami(\$iterator, array( + 'title' => 'PHP-XMLRPC', + 'build_dir' => 'build/workspace/doc/api', + 'cache_dir' => 'build/cache', + )); +EOT; + file_put_contents('build/sami_config.php', $samiConfig); + $cmd = Builder::tool('php'); + pake_sh("$cmd vendor/sami/sami/sami.php update -vvv build/sami_config.php"); + + // User Manual + + // html (single file) from asciidoc + $cmd = Builder::tool('asciidoctor'); + pake_sh("$cmd -d book $docDir/manual/phpxmlrpc_manual.adoc"); + + // then docbook from asciidoc + /// @todo create phpxmlrpc_manual.xml with the good version number + /// @todo create phpxmlrpc_manual.xml with the date set to the one of last commit (or today?) + pake_sh("$cmd -d book -b docbook $docDir/manual/phpxmlrpc_manual.adoc"); + + # Other tools for docbook... + # + # jade cmd yet to be rebuilt, starting from xml file and putting output in ./out dir, e.g. + # jade -t xml -d custom.dsl xmlrpc_php.xml + # + # convertdoc command for xmlmind xxe editor + # convertdoc docb.toHTML xmlrpc_php.xml -u out + # + # saxon + xerces xml parser + saxon extensions + xslthl: adds a little syntax highligting + # (bold and italics only, no color) for php source examples... + # java \ + # -classpath c:\programmi\saxon\saxon.jar\;c:\programmi\saxon\xslthl.jar\;c:\programmi\xerces\xercesImpl.jar\;C:\htdocs\xmlrpc_cvs\docbook-xsl\extensions\saxon65.jar \ + # -Djavax.xml.parsers.DocumentBuilderFactory=org.apache.xerces.jaxp.DocumentBuilderFactoryImpl \ + # -Djavax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl \ + # -Dxslthl.config=file:///c:/htdocs/xmlrpc_cvs/docbook-xsl/highlighting/xslthl-config.xml \ + # com.icl.saxon.StyleSheet -o xmlrpc_php.fo.xml xmlrpc_php.xml custom.fo.xsl use.extensions=1 + + // HTML (multiple files) from docbook - discontinued, as we use the nicer-looking html gotten from asciidoc + /*Builder::applyXslt($docDir.'/manual/phpxmlrpc_manual.xml', $docDir.'/build/custom.xsl', $docDir.'/manual'); + // post process html files to highlight php code samples + foreach(pakeFinder::type('file')->name('*.html')->in($docDir.'/manual') as $file) + { + file_put_contents($file, Builder::highlightPhpInHtml(file_get_contents($file))); + }*/ + + // PDF file from docbook + + // convert to fo and then to pdf using apache fop + Builder::applyXslt($docDir.'/manual/phpxmlrpc_manual.xml', $docDir.'/build/custom.fo.xsl', $docDir.'/manual/phpxmlrpc_manual.fo.xml'); + $cmd = Builder::tool('fop'); + pake_sh("$cmd $docDir/manual/phpxmlrpc_manual.fo.xml $docDir/manual/phpxmlrpc_manual.pdf"); + + // cleanup + unlink($docDir.'/manual/phpxmlrpc_manual.xml'); + unlink($docDir.'/manual/phpxmlrpc_manual.fo.xml'); +} + +function run_clean_dist() +{ + pake_remove_dir(Builder::distDir()); + $finder = pakeFinder::type('file')->name(Builder::distFiles()); + pake_remove($finder, Builder::buildDir()); +} + +/** + * Creates the tarballs for a release + */ +function run_dist($task=null, $args=array(), $cliOpts=array()) +{ + // copy workspace dir into dist dir, without git + pake_mkdirs(Builder::distDir()); + $finder = pakeFinder::type('any')->ignore_version_control(); + pake_mirror($finder, realpath(Builder::workspaceDir()), realpath(Builder::distDir())); + + // remove unwanted files from dist dir + + // also: do we still need to run dos2unix? + + // create tarballs + $cwd = getcwd(); + chdir(dirname(Builder::distDir())); + foreach(Builder::distFiles() as $distFile) { + // php can not really create good zip files via phar: they are not compressed! + if (substr($distFile, -4) == '.zip') { + $cmd = Builder::tool('zip'); + $extra = '-9 -r'; + pake_sh("$cmd $distFile $extra ".basename(Builder::distDir())); + } + else { + $finder = pakeFinder::type('any')->pattern(basename(Builder::distDir()).'/**'); + // see https://bugs.php.net/bug.php?id=58852 + $pharFile = str_replace(Builder::libVersion(), '_LIBVERSION_', $distFile); + pakeArchive::createArchive($finder, '.', $pharFile); + rename($pharFile, $distFile); + } + } + chdir($cwd); +} + +function run_clean_workspace($task=null, $args=array(), $cliOpts=array()) +{ + pake_remove_dir(Builder::workspaceDir()); +} + +/** + * Cleans up the whole build directory + * @todo 'make clean' usually just removes the results of the build, distclean removes all but sources + */ +function run_clean($task=null, $args=array(), $cliOpts=array()) +{ + pake_remove_dir(Builder::buildDir()); +} + +// helper task: display help text +pake_task( 'default' ); +// internal task: parse cli options +pake_task('getopts'); +pake_task('init', 'getopts'); +pake_task('doc', 'getopts', 'init', 'clean-doc'); +pake_task('build', 'getopts', 'init', 'doc'); +pake_task('dist', 'getopts', 'init', 'build', 'clean-dist'); +pake_task('clean-doc', 'getopts'); +pake_task('clean-dist', 'getopts'); +pake_task('clean-workspace', 'getopts'); +pake_task('clean', 'getopts'); + +} diff --git a/lib/phpxmlrpc/src/Autoloader.php b/lib/phpxmlrpc/src/Autoloader.php new file mode 100644 index 0000000..40ec219 --- /dev/null +++ b/lib/phpxmlrpc/src/Autoloader.php @@ -0,0 +1,36 @@ +send(). + */ + public function __construct($path, $server = '', $port = '', $method = '') + { + // allow user to specify all params in $path + if ($server == '' and $port == '' and $method == '') { + $parts = parse_url($path); + $server = $parts['host']; + $path = isset($parts['path']) ? $parts['path'] : ''; + if (isset($parts['query'])) { + $path .= '?' . $parts['query']; + } + if (isset($parts['fragment'])) { + $path .= '#' . $parts['fragment']; + } + if (isset($parts['port'])) { + $port = $parts['port']; + } + if (isset($parts['scheme'])) { + $method = $parts['scheme']; + } + if (isset($parts['user'])) { + $this->username = $parts['user']; + } + if (isset($parts['pass'])) { + $this->password = $parts['pass']; + } + } + if ($path == '' || $path[0] != '/') { + $this->path = '/' . $path; + } else { + $this->path = $path; + } + $this->server = $server; + if ($port != '') { + $this->port = $port; + } + if ($method != '') { + $this->method = $method; + } + + // if ZLIB is enabled, let the client by default accept compressed responses + if (function_exists('gzinflate') || ( + function_exists('curl_init') && (($info = curl_version()) && + ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version']))) + ) + ) { + $this->accepted_compression = array('gzip', 'deflate'); + } + + // keepalives: enabled by default + $this->keepalive = true; + + // by default the xml parser can support these 3 charset encodings + $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII'); + + // Add all charsets which mbstring can handle, but remove junk not found in IANA registry at + // in http://www.iana.org/assignments/character-sets/character-sets.xhtml + // NB: this is disabled to avoid making all the requests sent huge... mbstring supports more than 80 charsets! + /*if (function_exists('mb_list_encodings')) { + + $encodings = array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'BASE64', 'UUENCODE', 'ASCII', + 'HTML-ENTITIES', 'Quoted-Printable', '7bit','8bit', 'byte2be', 'byte2le', 'byte4be', 'byte4le')); + $this->accepted_charset_encodings = array_unique(array_merge($this->accepted_charset_encodings, $encodings)); + }*/ + + // initialize user_agent string + $this->user_agent = PhpXmlRpc::$xmlrpcName . ' ' . PhpXmlRpc::$xmlrpcVersion; + } + + /** + * Enable/disable the echoing to screen of the xmlrpc responses received. The default is not no output anything. + * + * The debugging information at level 1 includes the raw data returned from the XML-RPC server it was querying + * (including bot HTTP headers and the full XML payload), and the PHP value the client attempts to create to + * represent the value returned by the server + * At level2, the complete payload of the xmlrpc request is also printed, before being sent t the server. + * + * This option can be very useful when debugging servers as it allows you to see exactly what the client sends and + * the server returns. + * + * @param integer $in values 0, 1 and 2 are supported (2 = echo sent msg too, before received response) + */ + public function setDebug($level) + { + $this->debug = $level; + } + + /** + * Sets the username and password for authorizing the client to the server. + * + * With the default (HTTP) transport, this information is used for HTTP Basic authorization. + * Note that username and password can also be set using the class constructor. + * With HTTP 1.1 and HTTPS transport, NTLM and Digest authentication protocols are also supported. To enable them use + * the constants CURLAUTH_DIGEST and CURLAUTH_NTLM as values for the auth type parameter. + * + * @param string $user username + * @param string $password password + * @param integer $authType auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC + * (basic auth). Note that auth types NTLM and Digest will only work if the Curl php + * extension is enabled. + */ + public function setCredentials($user, $password, $authType = 1) + { + $this->username = $user; + $this->password = $password; + $this->authtype = $authType; + } + + /** + * Set the optional certificate and passphrase used in SSL-enabled communication with a remote server. + * + * Note: to retrieve information about the client certificate on the server side, you will need to look into the + * environment variables which are set up by the webserver. Different webservers will typically set up different + * variables. + * + * @param string $cert the name of a file containing a PEM formatted certificate + * @param string $certPass the password required to use it + */ + public function setCertificate($cert, $certPass = '') + { + $this->cert = $cert; + $this->certpass = $certPass; + } + + /** + * Add a CA certificate to verify server with in SSL-enabled communication when SetSSLVerifypeer has been set to TRUE. + * + * See the php manual page about CURLOPT_CAINFO for more details. + * + * @param string $caCert certificate file name (or dir holding certificates) + * @param bool $isDir set to true to indicate cacert is a dir. defaults to false + */ + public function setCaCertificate($caCert, $isDir = false) + { + if ($isDir) { + $this->cacertdir = $caCert; + } else { + $this->cacert = $caCert; + } + } + + /** + * Set attributes for SSL communication: private SSL key. + * + * NB: does not work in older php/curl installs. + * Thanks to Daniel Convissor. + * + * @param string $key The name of a file containing a private SSL key + * @param string $keyPass The secret password needed to use the private SSL key + */ + public function setKey($key, $keyPass) + { + $this->key = $key; + $this->keypass = $keyPass; + } + + /** + * Set attributes for SSL communication: verify the remote host's SSL certificate, and cause the connection to fail + * if the cert verification fails. + * + * By default, verification is enabled. + * To specify custom SSL certificates to validate the server with, use the setCaCertificate method. + * + * @param bool $i enable/disable verification of peer certificate + */ + public function setSSLVerifyPeer($i) + { + $this->verifypeer = $i; + } + + /** + * Set attributes for SSL communication: verify the remote host's SSL certificate's common name (CN). + * + * Note that support for value 1 has been removed in cURL 7.28.1 + * + * @param int $i Set to 1 to only the existence of a CN, not that it matches + */ + public function setSSLVerifyHost($i) + { + $this->verifyhost = $i; + } + + /** + * Set attributes for SSL communication: SSL version to use. Best left at 0 (default value ): let cURL decide + * + * @param int $i + */ + public function setSSLVersion($i) + { + $this->sslversion = $i; + } + + /** + * Set proxy info. + * + * NB: CURL versions before 7.11.10 cannot use a proxy to communicate with https servers. + * + * @param string $proxyHost + * @param string $proxyPort Defaults to 8080 for HTTP and 443 for HTTPS + * @param string $proxyUsername Leave blank if proxy has public access + * @param string $proxyPassword Leave blank if proxy has public access + * @param int $proxyAuthType defaults to CURLAUTH_BASIC (Basic authentication protocol); set to constant CURLAUTH_NTLM + * to use NTLM auth with proxy (has effect only when the client uses the HTTP 1.1 protocol) + */ + public function setProxy($proxyHost, $proxyPort, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1) + { + $this->proxy = $proxyHost; + $this->proxyport = $proxyPort; + $this->proxy_user = $proxyUsername; + $this->proxy_pass = $proxyPassword; + $this->proxy_authtype = $proxyAuthType; + } + + /** + * Enables/disables reception of compressed xmlrpc responses. + * + * This requires the "zlib" extension to be enabled in your php install. If it is, by default xmlrpc_client + * instances will enable reception of compressed content. + * Note that enabling reception of compressed responses merely adds some standard http headers to xmlrpc requests. + * It is up to the xmlrpc server to return compressed responses when receiving such requests. + * + * @param string $compMethod either 'gzip', 'deflate', 'any' or '' + */ + public function setAcceptedCompression($compMethod) + { + if ($compMethod == 'any') { + $this->accepted_compression = array('gzip', 'deflate'); + } elseif ($compMethod == false) { + $this->accepted_compression = array(); + } else { + $this->accepted_compression = array($compMethod); + } + } + + /** + * Enables/disables http compression of xmlrpc request. + * + * This requires the "zlib" extension to be enabled in your php install. + * Take care when sending compressed requests: servers might not support them (and automatic fallback to + * uncompressed requests is not yet implemented). + * + * @param string $compMethod either 'gzip', 'deflate' or '' + */ + public function setRequestCompression($compMethod) + { + $this->request_compression = $compMethod; + } + + /** + * Adds a cookie to list of cookies that will be sent to server with every further request (useful e.g. for keeping + * session info outside of the xml-rpc payload). + * + * NB: By default cookies are sent using the 'original/netscape' format, which is also the same as the RFC 2965; + * setting any param but name and value will turn the cookie into a 'version 1' cookie (i.e. RFC 2109 cookie) that + * might not be fully supported by the server. Note that RFC 2109 has currently 'historic' status... + * + * @param string $name nb: will not be escaped in the request's http headers. Take care not to use CTL chars or + * separators! + * @param string $value + * @param string $path leave this empty unless the xml-rpc server only accepts RFC 2109 cookies + * @param string $domain leave this empty unless the xml-rpc server only accepts RFC 2109 cookies + * @param int $port leave this empty unless the xml-rpc server only accepts RFC 2109 cookies + * + * @todo check correctness of urlencoding cookie value (copied from php way of doing it, but php is generally sending + * response not requests. We do the opposite...) + * @todo strip invalid chars from cookie name? As per RFC6265, we should follow RFC2616, Section 2.2 + */ + public function setCookie($name, $value = '', $path = '', $domain = '', $port = null) + { + $this->cookies[$name]['value'] = urlencode($value); + if ($path || $domain || $port) { + $this->cookies[$name]['path'] = $path; + $this->cookies[$name]['domain'] = $domain; + $this->cookies[$name]['port'] = $port; + $this->cookies[$name]['version'] = 1; + } else { + $this->cookies[$name]['version'] = 0; + } + } + + /** + * Directly set cURL options, for extra flexibility (when in cURL mode). + * + * It allows eg. to bind client to a specific IP interface / address. + * + * @param array $options + */ + public function setCurlOptions($options) + { + $this->extracurlopts = $options; + } + + /** + * Set user-agent string that will be used by this client instance in http headers sent to the server. + * + * The default user agent string includes the name of this library and the version number. + * + * @param string $agentString + */ + public function setUserAgent($agentString) + { + $this->user_agent = $agentString; + } + + /** + * Send an xmlrpc request to the server. + * + * @param Request|Request[]|string $req The Request object, or an array of requests for using multicall, or the + * complete xml representation of a request. + * When sending an array of Request objects, the client will try to make use of + * a single 'system.multicall' xml-rpc method call to forward to the server all + * the requests in a single HTTP round trip, unless $this->no_multicall has + * been previously set to TRUE (see the multicall method below), in which case + * many consecutive xmlrpc requests will be sent. The method will return an + * array of Response objects in both cases. + * The third variant allows to build by hand (or any other means) a complete + * xmlrpc request message, and send it to the server. $req should be a string + * containing the complete xml representation of the request. It is e.g. useful + * when, for maximal speed of execution, the request is serialized into a + * string using the native php xmlrpc functions (see http://www.php.net/xmlrpc) + * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply. + * This timeout value is passed to fsockopen(). It is also used for detecting server + * timeouts during communication (i.e. if the server does not send anything to the client + * for $timeout seconds, the connection will be closed). + * @param string $method valid values are 'http', 'http11' and 'https'. If left unspecified, the http protocol + * chosen during creation of the object will be used. + * + * + * @return Response|Response[] Note that the client will always return a Response object, even if the call fails + */ + public function send($req, $timeout = 0, $method = '') + { + // if user does not specify http protocol, use native method of this client + // (i.e. method set during call to constructor) + if ($method == '') { + $method = $this->method; + } + + if (is_array($req)) { + // $req is an array of Requests + $r = $this->multicall($req, $timeout, $method); + + return $r; + } elseif (is_string($req)) { + $n = new Request(''); + $n->payload = $req; + $req = $n; + } + + // where req is a Request + $req->setDebug($this->debug); + + if ($method == 'https') { + $r = $this->sendPayloadHTTPS( + $req, + $this->server, + $this->port, + $timeout, + $this->username, + $this->password, + $this->authtype, + $this->cert, + $this->certpass, + $this->cacert, + $this->cacertdir, + $this->proxy, + $this->proxyport, + $this->proxy_user, + $this->proxy_pass, + $this->proxy_authtype, + $this->keepalive, + $this->key, + $this->keypass, + $this->sslversion + ); + } elseif ($method == 'http11') { + $r = $this->sendPayloadCURL( + $req, + $this->server, + $this->port, + $timeout, + $this->username, + $this->password, + $this->authtype, + null, + null, + null, + null, + $this->proxy, + $this->proxyport, + $this->proxy_user, + $this->proxy_pass, + $this->proxy_authtype, + 'http', + $this->keepalive + ); + } else { + $r = $this->sendPayloadHTTP10( + $req, + $this->server, + $this->port, + $timeout, + $this->username, + $this->password, + $this->authtype, + $this->proxy, + $this->proxyport, + $this->proxy_user, + $this->proxy_pass, + $this->proxy_authtype, + $method + ); + } + + return $r; + } + + /** + * @param Request $req + * @param string $server + * @param int $port + * @param int $timeout + * @param string $username + * @param string $password + * @param int $authType + * @param string $proxyHost + * @param int $proxyPort + * @param string $proxyUsername + * @param string $proxyPassword + * @param int $proxyAuthType + * @param string $method + * @return Response + */ + protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0, $username = '', $password = '', + $authType = 1, $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, + $method='http') + { + if ($port == 0) { + $port = ( $method === "https" ) ? 443 : 80; + } + + // Only create the payload if it was not created previously + if (empty($req->payload)) { + $req->createPayload($this->request_charset_encoding); + } + + $payload = $req->payload; + // Deflate request body and set appropriate request headers + if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) { + if ($this->request_compression == 'gzip') { + $a = @gzencode($payload); + if ($a) { + $payload = $a; + $encodingHdr = "Content-Encoding: gzip\r\n"; + } + } else { + $a = @gzcompress($payload); + if ($a) { + $payload = $a; + $encodingHdr = "Content-Encoding: deflate\r\n"; + } + } + } else { + $encodingHdr = ''; + } + + // thanks to Grant Rauscher for this + $credentials = ''; + if ($username != '') { + $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n"; + if ($authType != 1) { + error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0'); + } + } + + $acceptedEncoding = ''; + if (is_array($this->accepted_compression) && count($this->accepted_compression)) { + $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n"; + } + + $proxyCredentials = ''; + if ($proxyHost) { + if ($proxyPort == 0) { + $proxyPort = 8080; + } + $connectServer = $proxyHost; + $connectPort = $proxyPort; + $transport = "tcp"; + $uri = 'http://' . $server . ':' . $port . $this->path; + if ($proxyUsername != '') { + if ($proxyAuthType != 1) { + error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0'); + } + $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n"; + } + } else { + $connectServer = $server; + $connectPort = $port; + /// @todo if supporting https, we should support all its current options as well: peer name verification etc... + $transport = ( $method === "https" ) ? "tls" : "tcp"; + $uri = $this->path; + } + + // Cookie generation, as per rfc2965 (version 1 cookies) or + // netscape's rules (version 0 cookies) + $cookieHeader = ''; + if (count($this->cookies)) { + $version = ''; + foreach ($this->cookies as $name => $cookie) { + if ($cookie['version']) { + $version = ' $Version="' . $cookie['version'] . '";'; + $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";'; + if ($cookie['path']) { + $cookieHeader .= ' $Path="' . $cookie['path'] . '";'; + } + if ($cookie['domain']) { + $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";'; + } + if ($cookie['port']) { + $cookieHeader .= ' $Port="' . $cookie['port'] . '";'; + } + } else { + $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";"; + } + } + $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n"; + } + + // omit port if 80 + $port = ($port == 80) ? '' : (':' . $port); + + $op = 'POST ' . $uri . " HTTP/1.0\r\n" . + 'User-Agent: ' . $this->user_agent . "\r\n" . + 'Host: ' . $server . $port . "\r\n" . + $credentials . + $proxyCredentials . + $acceptedEncoding . + $encodingHdr . + 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" . + $cookieHeader . + 'Content-Type: ' . $req->content_type . "\r\nContent-Length: " . + strlen($payload) . "\r\n\r\n" . + $payload; + + if ($this->debug > 1) { + Logger::instance()->debugMessage("---SENDING---\n$op\n---END---"); + } + + if ($timeout > 0) { + $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $timeout); + } else { + $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr); + } + if ($fp) { + if ($timeout > 0) { + stream_set_timeout($fp, $timeout); + } + } else { + $this->errstr = 'Connect error: ' . $this->errstr; + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')'); + + return $r; + } + + if (!fputs($fp, $op, strlen($op))) { + fclose($fp); + $this->errstr = 'Write error'; + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr); + + return $r; + } else { + // reset errno and errstr on successful socket connection + $this->errstr = ''; + } + // G. Giunta 2005/10/24: close socket before parsing. + // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects) + $ipd = ''; + do { + // shall we check for $data === FALSE? + // as per the manual, it signals an error + $ipd .= fread($fp, 32768); + } while (!feof($fp)); + fclose($fp); + $r = $req->parseResponse($ipd, false, $this->return_type); + + return $r; + } + + /** + * @param Request $req + * @param string $server + * @param int $port + * @param int $timeout + * @param string $username + * @param string $password + * @param int $authType + * @param string $cert + * @param string $certPass + * @param string $caCert + * @param string $caCertDir + * @param string $proxyHost + * @param int $proxyPort + * @param string $proxyUsername + * @param string $proxyPassword + * @param int $proxyAuthType + * @param bool $keepAlive + * @param string $key + * @param string $keyPass + * @param int $sslVersion + * @return Response + */ + protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '', $password = '', + $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0, + $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $keepAlive = false, $key = '', $keyPass = '', + $sslVersion = 0) + { + return $this->sendPayloadCURL($req, $server, $port, $timeout, $username, + $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort, + $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion); + } + + /** + * Contributed by Justin Miller + * Requires curl to be built into PHP + * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers! + * + * @param Request $req + * @param string $server + * @param int $port + * @param int $timeout + * @param string $username + * @param string $password + * @param int $authType + * @param string $cert + * @param string $certPass + * @param string $caCert + * @param string $caCertDir + * @param string $proxyHost + * @param int $proxyPort + * @param string $proxyUsername + * @param string $proxyPassword + * @param int $proxyAuthType + * @param string $method + * @param bool $keepAlive + * @param string $key + * @param string $keyPass + * @param int $sslVersion + * @return Response + */ + protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '', $password = '', + $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0, + $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', $keepAlive = false, $key = '', + $keyPass = '', $sslVersion = 0) + { + if (!function_exists('curl_init')) { + $this->errstr = 'CURL unavailable on this install'; + return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']); + } + if ($method == 'https') { + if (($info = curl_version()) && + ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version']))) + ) { + $this->errstr = 'SSL unavailable on this install'; + return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']); + } + } + + if ($port == 0) { + if ($method == 'http') { + $port = 80; + } else { + $port = 443; + } + } + + // Only create the payload if it was not created previously + if (empty($req->payload)) { + $req->createPayload($this->request_charset_encoding); + } + + // Deflate request body and set appropriate request headers + $payload = $req->payload; + if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) { + if ($this->request_compression == 'gzip') { + $a = @gzencode($payload); + if ($a) { + $payload = $a; + $encodingHdr = 'Content-Encoding: gzip'; + } + } else { + $a = @gzcompress($payload); + if ($a) { + $payload = $a; + $encodingHdr = 'Content-Encoding: deflate'; + } + } + } else { + $encodingHdr = ''; + } + + if ($this->debug > 1) { + Logger::instance()->debugMessage("---SENDING---\n$payload\n---END---"); + } + + if (!$keepAlive || !$this->xmlrpc_curl_handle) { + $curl = curl_init($method . '://' . $server . ':' . $port . $this->path); + if ($keepAlive) { + $this->xmlrpc_curl_handle = $curl; + } + } else { + $curl = $this->xmlrpc_curl_handle; + } + + // results into variable + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + + if ($this->debug > 1) { + curl_setopt($curl, CURLOPT_VERBOSE, true); + /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered + } + curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); + // required for XMLRPC: post the data + curl_setopt($curl, CURLOPT_POST, 1); + // the data + curl_setopt($curl, CURLOPT_POSTFIELDS, $payload); + + // return the header too + curl_setopt($curl, CURLOPT_HEADER, 1); + + // NB: if we set an empty string, CURL will add http header indicating + // ALL methods it is supporting. This is possibly a better option than + // letting the user tell what curl can / cannot do... + if (is_array($this->accepted_compression) && count($this->accepted_compression)) { + //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression)); + // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?) + if (count($this->accepted_compression) == 1) { + curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]); + } else { + curl_setopt($curl, CURLOPT_ENCODING, ''); + } + } + // extra headers + $headers = array('Content-Type: ' . $req->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings)); + // if no keepalive is wanted, let the server know it in advance + if (!$keepAlive) { + $headers[] = 'Connection: close'; + } + // request compression header + if ($encodingHdr) { + $headers[] = $encodingHdr; + } + + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); + // timeout is borked + if ($timeout) { + curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1); + } + + if ($username && $password) { + curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password); + if (defined('CURLOPT_HTTPAUTH')) { + curl_setopt($curl, CURLOPT_HTTPAUTH, $authType); + } elseif ($authType != 1) { + error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install'); + } + } + + if ($method == 'https') { + // set cert file + if ($cert) { + curl_setopt($curl, CURLOPT_SSLCERT, $cert); + } + // set cert password + if ($certPass) { + curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certPass); + } + // whether to verify remote host's cert + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer); + // set ca certificates file/dir + if ($caCert) { + curl_setopt($curl, CURLOPT_CAINFO, $caCert); + } + if ($caCertDir) { + curl_setopt($curl, CURLOPT_CAPATH, $caCertDir); + } + // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?) + if ($key) { + curl_setopt($curl, CURLOPT_SSLKEY, $key); + } + // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?) + if ($keyPass) { + curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keyPass); + } + // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost); + // allow usage of different SSL versions + curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion); + } + + // proxy info + if ($proxyHost) { + if ($proxyPort == 0) { + $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080 + } + curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort); + if ($proxyUsername) { + curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword); + if (defined('CURLOPT_PROXYAUTH')) { + curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType); + } elseif ($proxyAuthType != 1) { + error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install'); + } + } + } + + // NB: should we build cookie http headers by hand rather than let CURL do it? + // the following code does not honour 'expires', 'path' and 'domain' cookie attributes + // set to client obj the the user... + if (count($this->cookies)) { + $cookieHeader = ''; + foreach ($this->cookies as $name => $cookie) { + $cookieHeader .= $name . '=' . $cookie['value'] . '; '; + } + curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2)); + } + + foreach ($this->extracurlopts as $opt => $val) { + curl_setopt($curl, $opt, $val); + } + + $result = curl_exec($curl); + + if ($this->debug > 1) { + $message = "---CURL INFO---\n"; + foreach (curl_getinfo($curl) as $name => $val) { + if (is_array($val)) { + $val = implode("\n", $val); + } + $message .= $name . ': ' . $val . "\n"; + } + $message .= "---END---"; + Logger::instance()->debugMessage($message); + } + + if (!$result) { + /// @todo we should use a better check here - what if we get back '' or '0'? + + $this->errstr = 'no response'; + $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl)); + curl_close($curl); + if ($keepAlive) { + $this->xmlrpc_curl_handle = null; + } + } else { + if (!$keepAlive) { + curl_close($curl); + } + $resp = $req->parseResponse($result, true, $this->return_type); + // if we got back a 302, we can not reuse the curl handle for later calls + if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) { + curl_close($curl); + $this->xmlrpc_curl_handle = null; + } + } + + return $resp; + } + + /** + * Send an array of requests and return an array of responses. + * + * Unless $this->no_multicall has been set to true, it will try first to use one single xmlrpc call to server method + * system.multicall, and revert to sending many successive calls in case of failure. + * This failure is also stored in $this->no_multicall for subsequent calls. + * Unfortunately, there is no server error code universally used to denote the fact that multicall is unsupported, + * so there is no way to reliably distinguish between that and a temporary failure. + * If you are sure that server supports multicall and do not want to fallback to using many single calls, set the + * fourth parameter to FALSE. + * + * NB: trying to shoehorn extra functionality into existing syntax has resulted + * in pretty much convoluted code... + * + * @param Request[] $reqs an array of Request objects + * @param integer $timeout connection timeout (in seconds). See the details in the docs for the send() method + * @param string $method the http protocol variant to be used. See the details in the docs for the send() method + * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be + * attempted + * + * @return Response[] + */ + public function multicall($reqs, $timeout = 0, $method = '', $fallback = true) + { + if ($method == '') { + $method = $this->method; + } + if (!$this->no_multicall) { + $results = $this->_try_multicall($reqs, $timeout, $method); + if (is_array($results)) { + // System.multicall succeeded + return $results; + } else { + // either system.multicall is unsupported by server, + // or call failed for some other reason. + if ($fallback) { + // Don't try it next time... + $this->no_multicall = true; + } else { + if (is_a($results, '\PhpXmlRpc\Response')) { + $result = $results; + } else { + $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']); + } + } + } + } else { + // override fallback, in case careless user tries to do two + // opposite things at the same time + $fallback = true; + } + + $results = array(); + if ($fallback) { + // system.multicall is (probably) unsupported by server: + // emulate multicall via multiple requests + foreach ($reqs as $req) { + $results[] = $this->send($req, $timeout, $method); + } + } else { + // user does NOT want to fallback on many single calls: + // since we should always return an array of responses, + // return an array with the same error repeated n times + foreach ($reqs as $req) { + $results[] = $result; + } + } + + return $results; + } + + /** + * Attempt to boxcar $reqs via system.multicall. + * + * Returns either an array of Response, a single error Response or false (when received response does not respect + * valid multicall syntax). + * + * @param Request[] $reqs + * @param int $timeout + * @param string $method + * @return Response[]|bool|mixed|Response + */ + private function _try_multicall($reqs, $timeout, $method) + { + // Construct multicall request + $calls = array(); + foreach ($reqs as $req) { + $call['methodName'] = new Value($req->method(), 'string'); + $numParams = $req->getNumParams(); + $params = array(); + for ($i = 0; $i < $numParams; $i++) { + $params[$i] = $req->getParam($i); + } + $call['params'] = new Value($params, 'array'); + $calls[] = new Value($call, 'struct'); + } + $multiCall = new Request('system.multicall'); + $multiCall->addParam(new Value($calls, 'array')); + + // Attempt RPC call + $result = $this->send($multiCall, $timeout, $method); + + if ($result->faultCode() != 0) { + // call to system.multicall failed + return $result; + } + + // Unpack responses. + $rets = $result->value(); + + if ($this->return_type == 'xml') { + return $rets; + } elseif ($this->return_type == 'phpvals') { + /// @todo test this code branch... + $rets = $result->value(); + if (!is_array($rets)) { + return false; // bad return type from system.multicall + } + $numRets = count($rets); + if ($numRets != count($reqs)) { + return false; // wrong number of return values. + } + + $response = array(); + for ($i = 0; $i < $numRets; $i++) { + $val = $rets[$i]; + if (!is_array($val)) { + return false; + } + switch (count($val)) { + case 1: + if (!isset($val[0])) { + return false; // Bad value + } + // Normal return value + $response[$i] = new Response($val[0], 0, '', 'phpvals'); + break; + case 2: + /// @todo remove usage of @: it is apparently quite slow + $code = @$val['faultCode']; + if (!is_int($code)) { + return false; + } + $str = @$val['faultString']; + if (!is_string($str)) { + return false; + } + $response[$i] = new Response(0, $code, $str); + break; + default: + return false; + } + } + + return $response; + } else { + // return type == 'xmlrpcvals' + + $rets = $result->value(); + if ($rets->kindOf() != 'array') { + return false; // bad return type from system.multicall + } + $numRets = $rets->count(); + if ($numRets != count($reqs)) { + return false; // wrong number of return values. + } + + $response = array(); + foreach($rets as $val) { + switch ($val->kindOf()) { + case 'array': + if ($val->count() != 1) { + return false; // Bad value + } + // Normal return value + $response[] = new Response($val[0]); + break; + case 'struct': + $code = $val['faultCode']; + if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') { + return false; + } + $str = $val['faultString']; + if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') { + return false; + } + $response[] = new Response(0, $code->scalarval(), $str->scalarval()); + break; + default: + return false; + } + } + + return $response; + } + } +} diff --git a/lib/phpxmlrpc/src/Encoder.php b/lib/phpxmlrpc/src/Encoder.php new file mode 100644 index 0000000..220ce88 --- /dev/null +++ b/lib/phpxmlrpc/src/Encoder.php @@ -0,0 +1,317 @@ +kindOf()) { + case 'scalar': + if (in_array('extension_api', $options)) { + reset($xmlrpcVal->me); + list($typ, $val) = each($xmlrpcVal->me); + switch ($typ) { + case 'dateTime.iso8601': + $xmlrpcVal->scalar = $val; + $xmlrpcVal->type = 'datetime'; + $xmlrpcVal->timestamp = \PhpXmlRpc\Helper\Date::iso8601Decode($val); + + return $xmlrpcVal; + case 'base64': + $xmlrpcVal->scalar = $val; + $xmlrpcVal->type = $typ; + + return $xmlrpcVal; + default: + return $xmlrpcVal->scalarval(); + } + } + if (in_array('dates_as_objects', $options) && $xmlrpcVal->scalartyp() == 'dateTime.iso8601') { + // we return a Datetime object instead of a string + // since now the constructor of xmlrpc value accepts safely strings, ints and datetimes, + // we cater to all 3 cases here + $out = $xmlrpcVal->scalarval(); + if (is_string($out)) { + $out = strtotime($out); + } + if (is_int($out)) { + $result = new \Datetime(); + $result->setTimestamp($out); + + return $result; + } elseif (is_a($out, 'Datetime')) { + return $out; + } + } + + return $xmlrpcVal->scalarval(); + case 'array': + $arr = array(); + foreach($xmlrpcVal as $value) { + $arr[] = $this->decode($value, $options); + } + + return $arr; + case 'struct': + // If user said so, try to rebuild php objects for specific struct vals. + /// @todo should we raise a warning for class not found? + // shall we check for proper subclass of xmlrpc value instead of + // presence of _php_class to detect what we can do? + if (in_array('decode_php_objs', $options) && $xmlrpcVal->_php_class != '' + && class_exists($xmlrpcVal->_php_class) + ) { + $obj = @new $xmlrpcVal->_php_class(); + foreach ($xmlrpcVal as $key => $value) { + $obj->$key = $this->decode($value, $options); + } + + return $obj; + } else { + $arr = array(); + foreach ($xmlrpcVal as $key => $value) { + $arr[$key] = $this->decode($value, $options); + } + + return $arr; + } + case 'msg': + $paramCount = $xmlrpcVal->getNumParams(); + $arr = array(); + for ($i = 0; $i < $paramCount; $i++) { + $arr[] = $this->decode($xmlrpcVal->getParam($i), $options); + } + + return $arr; + } + } + + /** + * Takes native php types and encodes them into xmlrpc PHP object format. + * It will not re-encode xmlrpc value objects. + * + * Feature creep -- could support more types via optional type argument + * (string => datetime support has been added, ??? => base64 not yet) + * + * If given a proper options parameter, php object instances will be encoded + * into 'special' xmlrpc values, that can later be decoded into php objects + * by calling php_xmlrpc_decode() with a corresponding option + * + * @author Dan Libby (dan@libby.com) + * + * @param mixed $phpVal the value to be converted into an xmlrpc value object + * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api' + * + * @return \PhpXmlrpc\Value + */ + public function encode($phpVal, $options = array()) + { + $type = gettype($phpVal); + switch ($type) { + case 'string': + if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $phpVal)) { + $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDateTime); + } else { + $xmlrpcVal = new Value($phpVal, Value::$xmlrpcString); + } + break; + case 'integer': + $xmlrpcVal = new Value($phpVal, Value::$xmlrpcInt); + break; + case 'double': + $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble); + break; + // + // Add support for encoding/decoding of booleans, since they are supported in PHP + case 'boolean': + $xmlrpcVal = new Value($phpVal, Value::$xmlrpcBoolean); + break; + // + case 'array': + // PHP arrays can be encoded to either xmlrpc structs or arrays, + // depending on wheter they are hashes or plain 0..n integer indexed + // A shorter one-liner would be + // $tmp = array_diff(array_keys($phpVal), range(0, count($phpVal)-1)); + // but execution time skyrockets! + $j = 0; + $arr = array(); + $ko = false; + foreach ($phpVal as $key => $val) { + $arr[$key] = $this->encode($val, $options); + if (!$ko && $key !== $j) { + $ko = true; + } + $j++; + } + if ($ko) { + $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct); + } else { + $xmlrpcVal = new Value($arr, Value::$xmlrpcArray); + } + break; + case 'object': + if (is_a($phpVal, 'PhpXmlRpc\Value')) { + $xmlrpcVal = $phpVal; + } elseif (is_a($phpVal, 'DateTime')) { + $xmlrpcVal = new Value($phpVal->format('Ymd\TH:i:s'), Value::$xmlrpcStruct); + } else { + $arr = array(); + reset($phpVal); + while (list($k, $v) = each($phpVal)) { + $arr[$k] = $this->encode($v, $options); + } + $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct); + if (in_array('encode_php_objs', $options)) { + // let's save original class name into xmlrpc value: + // might be useful later on... + $xmlrpcVal->_php_class = get_class($phpVal); + } + } + break; + case 'NULL': + if (in_array('extension_api', $options)) { + $xmlrpcVal = new Value('', Value::$xmlrpcString); + } elseif (in_array('null_extension', $options)) { + $xmlrpcVal = new Value('', Value::$xmlrpcNull); + } else { + $xmlrpcVal = new Value(); + } + break; + case 'resource': + if (in_array('extension_api', $options)) { + $xmlrpcVal = new Value((int)$phpVal, Value::$xmlrpcInt); + } else { + $xmlrpcVal = new Value(); + } + // catch "user function", "unknown type" + default: + // giancarlo pinerolo + // it has to return + // an empty object in case, not a boolean. + $xmlrpcVal = new Value(); + break; + } + + return $xmlrpcVal; + } + + /** + * Convert the xml representation of a method response, method request or single + * xmlrpc value into the appropriate object (a.k.a. deserialize). + * + * @param string $xmlVal + * @param array $options + * + * @return mixed false on error, or an instance of either Value, Request or Response + */ + public function decodeXml($xmlVal, $options = array()) + { + // 'guestimate' encoding + $valEncoding = XMLParser::guessEncoding('', $xmlVal); + if ($valEncoding != '') { + + // Since parsing will fail if charset is not specified in the xml prologue, + // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that... + // The following code might be better for mb_string enabled installs, but + // makes the lib about 200% slower... + //if (!is_valid_charset($valEncoding, array('UTF-8')) + if (!in_array($valEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($xmlVal)) { + if ($valEncoding == 'ISO-8859-1') { + $xmlVal = utf8_encode($xmlVal); + } else { + if (extension_loaded('mbstring')) { + $xmlVal = mb_convert_encoding($xmlVal, 'UTF-8', $valEncoding); + } else { + error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of xml text: ' . $valEncoding); + } + } + } + } + + $parser = xml_parser_create(); + xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true); + // What if internal encoding is not in one of the 3 allowed? + // we use the broadest one, ie. utf8! + if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) { + xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8'); + } else { + xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding); + } + + $xmlRpcParser = new XMLParser(); + xml_set_object($parser, $xmlRpcParser); + + xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee'); + xml_set_character_data_handler($parser, 'xmlrpc_cd'); + xml_set_default_handler($parser, 'xmlrpc_dh'); + if (!xml_parse($parser, $xmlVal, 1)) { + $errstr = sprintf('XML error: %s at line %d, column %d', + xml_error_string(xml_get_error_code($parser)), + xml_get_current_line_number($parser), xml_get_current_column_number($parser)); + error_log($errstr); + xml_parser_free($parser); + + return false; + } + xml_parser_free($parser); + if ($xmlRpcParser->_xh['isf'] > 1) { + // test that $xmlrpc->_xh['value'] is an obj, too??? + + error_log($xmlRpcParser->_xh['isf_reason']); + + return false; + } + switch ($xmlRpcParser->_xh['rt']) { + case 'methodresponse': + $v = &$xmlRpcParser->_xh['value']; + if ($xmlRpcParser->_xh['isf'] == 1) { + $vc = $v['faultCode']; + $vs = $v['faultString']; + $r = new Response(0, $vc->scalarval(), $vs->scalarval()); + } else { + $r = new Response($v); + } + + return $r; + case 'methodcall': + $req = new Request($xmlRpcParser->_xh['method']); + for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) { + $req->addParam($xmlRpcParser->_xh['params'][$i]); + } + + return $req; + case 'value': + return $xmlRpcParser->_xh['value']; + default: + return false; + } + } + +} diff --git a/lib/phpxmlrpc/src/Helper/Charset.php b/lib/phpxmlrpc/src/Helper/Charset.php new file mode 100644 index 0000000..4f1103b --- /dev/null +++ b/lib/phpxmlrpc/src/Helper/Charset.php @@ -0,0 +1,273 @@ + array(), "out" => array()); + protected $xml_iso88591_utf8 = array("in" => array(), "out" => array()); + + /// @todo add to iso table the characters from cp_1252 range, i.e. 128 to 159? + /// These will NOT be present in true ISO-8859-1, but will save the unwary + /// windows user from sending junk (though no luck when receiving them...) + /* + protected $xml_cp1252_Entities = array('in' => array(), out' => array( + '€', '?', '‚', 'ƒ', + '„', '…', '†', '‡', + 'ˆ', '‰', 'Š', '‹', + 'Œ', '?', 'Ž', '?', + '?', '‘', '’', '“', + '”', '•', '–', '—', + '˜', '™', 'š', '›', + 'œ', '?', 'ž', 'Ÿ' + )); + */ + + protected $charset_supersets = array( + 'US-ASCII' => array('ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4', + 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', + 'ISO-8859-9', 'ISO-8859-10', 'ISO-8859-11', 'ISO-8859-12', + 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'UTF-8', + 'EUC-JP', 'EUC-', 'EUC-KR', 'EUC-CN',), + ); + + protected static $instance = null; + + /** + * This class is singleton for performance reasons. + * + * @return Charset + */ + public static function instance() + { + if (self::$instance === null) { + self::$instance = new self(); + } + + return self::$instance; + } + + private function __construct() + { + for ($i = 0; $i < 32; $i++) { + $this->xml_iso88591_Entities["in"][] = chr($i); + $this->xml_iso88591_Entities["out"][] = "&#{$i};"; + } + + for ($i = 160; $i < 256; $i++) { + $this->xml_iso88591_Entities["in"][] = chr($i); + $this->xml_iso88591_Entities["out"][] = "&#{$i};"; + } + + /*for ($i = 128; $i < 160; $i++) + { + $this->xml_cp1252_Entities['in'][] = chr($i); + }*/ + } + + /** + * Convert a string to the correct XML representation in a target charset. + * + * To help correct communication of non-ascii chars inside strings, regardless of the charset used when sending + * requests, parsing them, sending responses and parsing responses, an option is to convert all non-ascii chars + * present in the message into their equivalent 'charset entity'. Charset entities enumerated this way are + * independent of the charset encoding used to transmit them, and all XML parsers are bound to understand them. + * Note that in the std case we are not sending a charset encoding mime type along with http headers, so we are + * bound by RFC 3023 to emit strict us-ascii. + * + * @todo do a bit of basic benchmarking (strtr vs. str_replace) + * @todo make usage of iconv() or recode_string() or mb_string() where available + * + * @param string $data + * @param string $srcEncoding + * @param string $destEncoding + * + * @return string + */ + public function encodeEntities($data, $srcEncoding = '', $destEncoding = '') + { + if ($srcEncoding == '') { + // lame, but we know no better... + $srcEncoding = PhpXmlRpc::$xmlrpc_internalencoding; + } + + $conversion = strtoupper($srcEncoding . '_' . $destEncoding); + switch ($conversion) { + case 'ISO-8859-1_': + case 'ISO-8859-1_US-ASCII': + $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escapedData = str_replace($this->xml_iso88591_Entities['in'], $this->xml_iso88591_Entities['out'], $escapedData); + break; + + case 'ISO-8859-1_UTF-8': + $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escapedData = utf8_encode($escapedData); + break; + + case 'ISO-8859-1_ISO-8859-1': + case 'US-ASCII_US-ASCII': + case 'US-ASCII_UTF-8': + case 'US-ASCII_': + case 'US-ASCII_ISO-8859-1': + case 'UTF-8_UTF-8': + //case 'CP1252_CP1252': + $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + break; + + case 'UTF-8_': + case 'UTF-8_US-ASCII': + case 'UTF-8_ISO-8859-1': + // NB: this will choke on invalid UTF-8, going most likely beyond EOF + $escapedData = ''; + // be kind to users creating string xmlrpc values out of different php types + $data = (string)$data; + $ns = strlen($data); + for ($nn = 0; $nn < $ns; $nn++) { + $ch = $data[$nn]; + $ii = ord($ch); + // 7 bits: 0bbbbbbb (127) + if ($ii < 128) { + /// @todo shall we replace this with a (supposedly) faster str_replace? + switch ($ii) { + case 34: + $escapedData .= '"'; + break; + case 38: + $escapedData .= '&'; + break; + case 39: + $escapedData .= '''; + break; + case 60: + $escapedData .= '<'; + break; + case 62: + $escapedData .= '>'; + break; + default: + $escapedData .= $ch; + } // switch + } // 11 bits: 110bbbbb 10bbbbbb (2047) + elseif ($ii >> 5 == 6) { + $b1 = ($ii & 31); + $ii = ord($data[$nn + 1]); + $b2 = ($ii & 63); + $ii = ($b1 * 64) + $b2; + $ent = sprintf('&#%d;', $ii); + $escapedData .= $ent; + $nn += 1; + } // 16 bits: 1110bbbb 10bbbbbb 10bbbbbb + elseif ($ii >> 4 == 14) { + $b1 = ($ii & 15); + $ii = ord($data[$nn + 1]); + $b2 = ($ii & 63); + $ii = ord($data[$nn + 2]); + $b3 = ($ii & 63); + $ii = ((($b1 * 64) + $b2) * 64) + $b3; + $ent = sprintf('&#%d;', $ii); + $escapedData .= $ent; + $nn += 2; + } // 21 bits: 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb + elseif ($ii >> 3 == 30) { + $b1 = ($ii & 7); + $ii = ord($data[$nn + 1]); + $b2 = ($ii & 63); + $ii = ord($data[$nn + 2]); + $b3 = ($ii & 63); + $ii = ord($data[$nn + 3]); + $b4 = ($ii & 63); + $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4; + $ent = sprintf('&#%d;', $ii); + $escapedData .= $ent; + $nn += 3; + } + } + + // when converting to latin-1, do not be so eager with using entities for characters 160-255 + if ($conversion == 'UTF-8_ISO-8859-1') { + $escapedData = str_replace(array_slice($this->xml_iso88591_Entities['out'], 32), array_slice($this->xml_iso88591_Entities['in'], 32), $escapedData); + } + break; + + /* + case 'CP1252_': + case 'CP1252_US-ASCII': + $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escapedData = str_replace($this->xml_iso88591_Entities']['in'], $this->xml_iso88591_Entities['out'], $escapedData); + $escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData); + break; + case 'CP1252_UTF-8': + $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + /// @todo we could use real UTF8 chars here instead of xml entities... (note that utf_8 encode all allone will NOT convert them) + $escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData); + $escapedData = utf8_encode($escapedData); + break; + case 'CP1252_ISO-8859-1': + $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + // we might as well replace all funky chars with a '?' here, but we are kind and leave it to the receiving application layer to decide what to do with these weird entities... + $escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData); + break; + */ + + default: + $escapedData = ''; + error_log('XML-RPC: ' . __METHOD__ . ": Converting from $srcEncoding to $destEncoding: not supported..."); + } + + return $escapedData; + } + + /** + * Checks if a given charset encoding is present in a list of encodings or + * if it is a valid subset of any encoding in the list. + * + * @param string $encoding charset to be tested + * @param string|array $validList comma separated list of valid charsets (or array of charsets) + * + * @return bool + */ + public function isValidCharset($encoding, $validList) + { + if (is_string($validList)) { + $validList = explode(',', $validList); + } + if (@in_array(strtoupper($encoding), $validList)) { + return true; + } else { + if (array_key_exists($encoding, $this->charset_supersets)) { + foreach ($validList as $allowed) { + if (in_array($allowed, $this->charset_supersets[$encoding])) { + return true; + } + } + } + + return false; + } + } + + /** + * Used only for backwards compatibility + * @deprecated + * + * @param string $charset + * + * @return array + * + * @throws \Exception for unknown/unsupported charsets + */ + public function getEntities($charset) + { + switch ($charset) + { + case 'iso88591': + return $this->xml_iso88591_Entities; + default: + throw new \Exception('Unsupported charset: ' . $charset); + } + } + +} diff --git a/lib/phpxmlrpc/src/Helper/Date.php b/lib/phpxmlrpc/src/Helper/Date.php new file mode 100644 index 0000000..f97f52c --- /dev/null +++ b/lib/phpxmlrpc/src/Helper/Date.php @@ -0,0 +1,63 @@ + 0) { + $chunkEnd = strpos($buffer, "\r\n", $chunkStart + $chunkSize); + + // just in case we got a broken connection + if ($chunkEnd == false) { + $chunk = substr($buffer, $chunkStart); + // append chunk-data to entity-body + $new .= $chunk; + $length += strlen($chunk); + break; + } + + // read chunk-data and crlf + $chunk = substr($buffer, $chunkStart, $chunkEnd - $chunkStart); + // append chunk-data to entity-body + $new .= $chunk; + // length := length + chunk-size + $length += strlen($chunk); + // read chunk-size and crlf + $chunkStart = $chunkEnd + 2; + + $chunkEnd = strpos($buffer, "\r\n", $chunkStart) + 2; + if ($chunkEnd == false) { + break; //just in case we got a broken connection + } + $temp = substr($buffer, $chunkStart, $chunkEnd - $chunkStart); + $chunkSize = hexdec(trim($temp)); + $chunkStart = $chunkEnd; + } + + return $new; + } + + /** + * Parses HTTP an http response headers and separates them from the body. + * + * @param string $data the http response,headers and body. It will be stripped of headers + * @param bool $headersProcessed when true, we assume that response inflating and dechunking has been already carried out + * + * @return array with keys 'headers' and 'cookies' + * @throws \Exception + */ + public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0) + { + $httpResponse = array('raw_data' => $data, 'headers'=> array(), 'cookies' => array()); + + // Support "web-proxy-tunelling" connections for https through proxies + if (preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data)) { + // Look for CR/LF or simple LF as line separator, + // (even though it is not valid http) + $pos = strpos($data, "\r\n\r\n"); + if ($pos || is_int($pos)) { + $bd = $pos + 4; + } else { + $pos = strpos($data, "\n\n"); + if ($pos || is_int($pos)) { + $bd = $pos + 2; + } else { + // No separation between response headers and body: fault? + $bd = 0; + } + } + if ($bd) { + // this filters out all http headers from proxy. + // maybe we could take them into account, too? + $data = substr($data, $bd); + } else { + error_log('XML-RPC: ' . __METHOD__ . ': HTTPS via proxy error, tunnel connection possibly failed'); + throw new \Exception(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (HTTPS via proxy error, tunnel connection possibly failed)', PhpXmlRpc::$xmlrpcerr['http_error']); + } + } + + // Strip HTTP 1.1 100 Continue header if present + while (preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data)) { + $pos = strpos($data, 'HTTP', 12); + // server sent a Continue header without any (valid) content following... + // give the client a chance to know it + if (!$pos && !is_int($pos)) { + // works fine in php 3, 4 and 5 + + break; + } + $data = substr($data, $pos); + } + if (!preg_match('/^HTTP\/[0-9.]+ 200 /', $data)) { + $errstr = substr($data, 0, strpos($data, "\n") - 1); + error_log('XML-RPC: ' . __METHOD__ . ': HTTP error, got response: ' . $errstr); + throw new \Exception(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (' . $errstr . ')', PhpXmlRpc::$xmlrpcerr['http_error']); + } + + // be tolerant to usage of \n instead of \r\n to separate headers and data + // (even though it is not valid http) + $pos = strpos($data, "\r\n\r\n"); + if ($pos || is_int($pos)) { + $bd = $pos + 4; + } else { + $pos = strpos($data, "\n\n"); + if ($pos || is_int($pos)) { + $bd = $pos + 2; + } else { + // No separation between response headers and body: fault? + // we could take some action here instead of going on... + $bd = 0; + } + } + // be tolerant to line endings, and extra empty lines + $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos))); + while (list(, $line) = @each($ar)) { + // take care of multi-line headers and cookies + $arr = explode(':', $line, 2); + if (count($arr) > 1) { + $headerName = strtolower(trim($arr[0])); + /// @todo some other headers (the ones that allow a CSV list of values) + /// do allow many values to be passed using multiple header lines. + /// We should add content to $xmlrpc->_xh['headers'][$headerName] + /// instead of replacing it for those... + if ($headerName == 'set-cookie' || $headerName == 'set-cookie2') { + if ($headerName == 'set-cookie2') { + // version 2 cookies: + // there could be many cookies on one line, comma separated + $cookies = explode(',', $arr[1]); + } else { + $cookies = array($arr[1]); + } + foreach ($cookies as $cookie) { + // glue together all received cookies, using a comma to separate them + // (same as php does with getallheaders()) + if (isset($httpResponse['headers'][$headerName])) { + $httpResponse['headers'][$headerName] .= ', ' . trim($cookie); + } else { + $httpResponse['headers'][$headerName] = trim($cookie); + } + // parse cookie attributes, in case user wants to correctly honour them + // feature creep: only allow rfc-compliant cookie attributes? + // @todo support for server sending multiple time cookie with same name, but using different PATHs + $cookie = explode(';', $cookie); + foreach ($cookie as $pos => $val) { + $val = explode('=', $val, 2); + $tag = trim($val[0]); + $val = trim(@$val[1]); + /// @todo with version 1 cookies, we should strip leading and trailing " chars + if ($pos == 0) { + $cookiename = $tag; + $httpResponse['cookies'][$tag] = array(); + $httpResponse['cookies'][$cookiename]['value'] = urldecode($val); + } else { + if ($tag != 'value') { + $httpResponse['cookies'][$cookiename][$tag] = $val; + } + } + } + } + } else { + $httpResponse['headers'][$headerName] = trim($arr[1]); + } + } elseif (isset($headerName)) { + /// @todo version1 cookies might span multiple lines, thus breaking the parsing above + $httpResponse['headers'][$headerName] .= ' ' . trim($line); + } + } + + $data = substr($data, $bd); + + if ($debug && count($httpResponse['headers'])) { + $msg = ''; + foreach ($httpResponse['headers'] as $header => $value) { + $msg .= "HEADER: $header: $value\n"; + } + foreach ($httpResponse['cookies'] as $header => $value) { + $msg .= "COOKIE: $header={$value['value']}\n"; + } + Logger::instance()->debugMessage($msg); + } + + // if CURL was used for the call, http headers have been processed, + // and dechunking + reinflating have been carried out + if (!$headersProcessed) { + // Decode chunked encoding sent by http 1.1 servers + if (isset($httpResponse['headers']['transfer-encoding']) && $httpResponse['headers']['transfer-encoding'] == 'chunked') { + if (!$data = Http::decodeChunked($data)) { + error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server'); + throw new \Exception(PhpXmlRpc::$xmlrpcstr['dechunk_fail'], PhpXmlRpc::$xmlrpcerr['dechunk_fail']); + } + } + + // Decode gzip-compressed stuff + // code shamelessly inspired from nusoap library by Dietrich Ayala + if (isset($httpResponse['headers']['content-encoding'])) { + $httpResponse['headers']['content-encoding'] = str_replace('x-', '', $httpResponse['headers']['content-encoding']); + if ($httpResponse['headers']['content-encoding'] == 'deflate' || $httpResponse['headers']['content-encoding'] == 'gzip') { + // if decoding works, use it. else assume data wasn't gzencoded + if (function_exists('gzinflate')) { + if ($httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) { + $data = $degzdata; + if ($debug) { + Logger::instance()->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---"); + } + } elseif ($httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) { + $data = $degzdata; + if ($debug) { + Logger::instance()->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---"); + } + } else { + error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server'); + throw new \Exception(PhpXmlRpc::$xmlrpcstr['decompress_fail'], PhpXmlRpc::$xmlrpcerr['decompress_fail']); + } + } else { + error_log('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); + throw new \Exception(PhpXmlRpc::$xmlrpcstr['cannot_decompress'], PhpXmlRpc::$xmlrpcerr['cannot_decompress']); + } + } + } + } // end of 'if needed, de-chunk, re-inflate response' + + return $httpResponse; + } +} diff --git a/lib/phpxmlrpc/src/Helper/Logger.php b/lib/phpxmlrpc/src/Helper/Logger.php new file mode 100644 index 0000000..77e0e14 --- /dev/null +++ b/lib/phpxmlrpc/src/Helper/Logger.php @@ -0,0 +1,52 @@ +\n".htmlentities($message, $flags, $encoding)."\n
    "; + } else { + print "
    \n".htmlentities($message, $flags)."\n
    "; + } + } else { + print "\n$message\n"; + } + + // let the user see this now in case there's a time out later... + flush(); + } +} diff --git a/lib/phpxmlrpc/src/Helper/XMLParser.php b/lib/phpxmlrpc/src/Helper/XMLParser.php new file mode 100644 index 0000000..b7d137f --- /dev/null +++ b/lib/phpxmlrpc/src/Helper/XMLParser.php @@ -0,0 +1,561 @@ + '', + 'stack' => array(), + 'valuestack' => array(), + 'isf' => 0, + 'isf_reason' => '', + 'method' => false, // so we can check later if we got a methodname or not + 'params' => array(), + 'pt' => array(), + 'rt' => '', + ); + + public $xmlrpc_valid_parents = array( + 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'), + 'BOOLEAN' => array('VALUE'), + 'I4' => array('VALUE'), + 'I8' => array('VALUE'), + 'EX:I8' => array('VALUE'), + 'INT' => array('VALUE'), + 'STRING' => array('VALUE'), + 'DOUBLE' => array('VALUE'), + 'DATETIME.ISO8601' => array('VALUE'), + 'BASE64' => array('VALUE'), + 'MEMBER' => array('STRUCT'), + 'NAME' => array('MEMBER'), + 'DATA' => array('ARRAY'), + 'ARRAY' => array('VALUE'), + 'STRUCT' => array('VALUE'), + 'PARAM' => array('PARAMS'), + 'METHODNAME' => array('METHODCALL'), + 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'), + 'FAULT' => array('METHODRESPONSE'), + 'NIL' => array('VALUE'), // only used when extension activated + 'EX:NIL' => array('VALUE'), // only used when extension activated + ); + + /** + * xml parser handler function for opening element tags. + */ + public function xmlrpc_se($parser, $name, $attrs, $acceptSingleVals = false) + { + // if invalid xmlrpc already detected, skip all processing + if ($this->_xh['isf'] < 2) { + // check for correct element nesting + // top level element can only be of 2 types + /// @todo optimization creep: save this check into a bool variable, instead of using count() every time: + /// there is only a single top level element in xml anyway + if (count($this->_xh['stack']) == 0) { + if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && ( + $name != 'VALUE' && !$acceptSingleVals) + ) { + $this->_xh['isf'] = 2; + $this->_xh['isf_reason'] = 'missing top level xmlrpc element'; + + return; + } else { + $this->_xh['rt'] = strtolower($name); + } + } else { + // not top level element: see if parent is OK + $parent = end($this->_xh['stack']); + if (!array_key_exists($name, $this->xmlrpc_valid_parents) || !in_array($parent, $this->xmlrpc_valid_parents[$name])) { + $this->_xh['isf'] = 2; + $this->_xh['isf_reason'] = "xmlrpc element $name cannot be child of $parent"; + + return; + } + } + + switch ($name) { + // optimize for speed switch cases: most common cases first + case 'VALUE': + /// @todo we could check for 2 VALUE elements inside a MEMBER or PARAM element + $this->_xh['vt'] = 'value'; // indicator: no value found yet + $this->_xh['ac'] = ''; + $this->_xh['lv'] = 1; + $this->_xh['php_class'] = null; + break; + case 'I8': + case 'EX:I8': + if (PHP_INT_SIZE === 4) { + /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!! + $this->_xh['isf'] = 2; + $this->_xh['isf_reason'] = "Received i8 element but php is compiled in 32 bit mode"; + + return; + } + // fall through voluntarily + case 'I4': + case 'INT': + case 'STRING': + case 'BOOLEAN': + case 'DOUBLE': + case 'DATETIME.ISO8601': + case 'BASE64': + if ($this->_xh['vt'] != 'value') { + // two data elements inside a value: an error occurred! + $this->_xh['isf'] = 2; + $this->_xh['isf_reason'] = "$name element following a {$this->_xh['vt']} element inside a single value"; + + return; + } + $this->_xh['ac'] = ''; // reset the accumulator + break; + case 'STRUCT': + case 'ARRAY': + if ($this->_xh['vt'] != 'value') { + //two data elements inside a value: an error occurred! + $this->_xh['isf'] = 2; + $this->_xh['isf_reason'] = "$name element following a {$this->_xh['vt']} element inside a single value"; + + return; + } + // create an empty array to hold child values, and push it onto appropriate stack + $curVal = array(); + $curVal['values'] = array(); + $curVal['type'] = $name; + // check for out-of-band information to rebuild php objs + // and in case it is found, save it + if (@isset($attrs['PHP_CLASS'])) { + $curVal['php_class'] = $attrs['PHP_CLASS']; + } + $this->_xh['valuestack'][] = $curVal; + $this->_xh['vt'] = 'data'; // be prepared for a data element next + break; + case 'DATA': + if ($this->_xh['vt'] != 'data') { + //two data elements inside a value: an error occurred! + $this->_xh['isf'] = 2; + $this->_xh['isf_reason'] = "found two data elements inside an array element"; + + return; + } + case 'METHODCALL': + case 'METHODRESPONSE': + case 'PARAMS': + // valid elements that add little to processing + break; + case 'METHODNAME': + case 'NAME': + /// @todo we could check for 2 NAME elements inside a MEMBER element + $this->_xh['ac'] = ''; + break; + case 'FAULT': + $this->_xh['isf'] = 1; + break; + case 'MEMBER': + $this->_xh['valuestack'][count($this->_xh['valuestack']) - 1]['name'] = ''; // set member name to null, in case we do not find in the xml later on + //$this->_xh['ac']=''; + // Drop trough intentionally + case 'PARAM': + // clear value type, so we can check later if no value has been passed for this param/member + $this->_xh['vt'] = null; + break; + case 'NIL': + case 'EX:NIL': + if (PhpXmlRpc::$xmlrpc_null_extension) { + if ($this->_xh['vt'] != 'value') { + //two data elements inside a value: an error occurred! + $this->_xh['isf'] = 2; + $this->_xh['isf_reason'] = "$name element following a {$this->_xh['vt']} element inside a single value"; + + return; + } + $this->_xh['ac'] = ''; // reset the accumulator + break; + } + // we do not support the extension, so + // drop through intentionally + default: + /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!! + $this->_xh['isf'] = 2; + $this->_xh['isf_reason'] = "found not-xmlrpc xml element $name"; + break; + } + + // Save current element name to stack, to validate nesting + $this->_xh['stack'][] = $name; + + /// @todo optimization creep: move this inside the big switch() above + if ($name != 'VALUE') { + $this->_xh['lv'] = 0; + } + } + } + + /** + * Used in decoding xml chunks that might represent single xmlrpc values. + */ + public function xmlrpc_se_any($parser, $name, $attrs) + { + $this->xmlrpc_se($parser, $name, $attrs, true); + } + + /** + * xml parser handler function for close element tags. + */ + public function xmlrpc_ee($parser, $name, $rebuildXmlrpcvals = true) + { + if ($this->_xh['isf'] < 2) { + // push this element name from stack + // NB: if XML validates, correct opening/closing is guaranteed and + // we do not have to check for $name == $currElem. + // we also checked for proper nesting at start of elements... + $currElem = array_pop($this->_xh['stack']); + + switch ($name) { + case 'VALUE': + // This if() detects if no scalar was inside + if ($this->_xh['vt'] == 'value') { + $this->_xh['value'] = $this->_xh['ac']; + $this->_xh['vt'] = Value::$xmlrpcString; + } + + if ($rebuildXmlrpcvals) { + // build the xmlrpc val out of the data received, and substitute it + $temp = new Value($this->_xh['value'], $this->_xh['vt']); + // in case we got info about underlying php class, save it + // in the object we're rebuilding + if (isset($this->_xh['php_class'])) { + $temp->_php_class = $this->_xh['php_class']; + } + // check if we are inside an array or struct: + // if value just built is inside an array, let's move it into array on the stack + $vscount = count($this->_xh['valuestack']); + if ($vscount && $this->_xh['valuestack'][$vscount - 1]['type'] == 'ARRAY') { + $this->_xh['valuestack'][$vscount - 1]['values'][] = $temp; + } else { + $this->_xh['value'] = $temp; + } + } else { + /// @todo this needs to treat correctly php-serialized objects, + /// since std deserializing is done by php_xmlrpc_decode, + /// which we will not be calling... + if (isset($this->_xh['php_class'])) { + } + + // check if we are inside an array or struct: + // if value just built is inside an array, let's move it into array on the stack + $vscount = count($this->_xh['valuestack']); + if ($vscount && $this->_xh['valuestack'][$vscount - 1]['type'] == 'ARRAY') { + $this->_xh['valuestack'][$vscount - 1]['values'][] = $this->_xh['value']; + } + } + break; + case 'BOOLEAN': + case 'I4': + case 'I8': + case 'EX:I8': + case 'INT': + case 'STRING': + case 'DOUBLE': + case 'DATETIME.ISO8601': + case 'BASE64': + $this->_xh['vt'] = strtolower($name); + /// @todo: optimization creep - remove the if/elseif cycle below + /// since the case() in which we are already did that + if ($name == 'STRING') { + $this->_xh['value'] = $this->_xh['ac']; + } elseif ($name == 'DATETIME.ISO8601') { + if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $this->_xh['ac'])) { + error_log('XML-RPC: ' . __METHOD__ . ': invalid value received in DATETIME: ' . $this->_xh['ac']); + } + $this->_xh['vt'] = Value::$xmlrpcDateTime; + $this->_xh['value'] = $this->_xh['ac']; + } elseif ($name == 'BASE64') { + /// @todo check for failure of base64 decoding / catch warnings + $this->_xh['value'] = base64_decode($this->_xh['ac']); + } elseif ($name == 'BOOLEAN') { + // special case here: we translate boolean 1 or 0 into PHP + // constants true or false. + // Strings 'true' and 'false' are accepted, even though the + // spec never mentions them (see eg. Blogger api docs) + // NB: this simple checks helps a lot sanitizing input, ie no + // security problems around here + if ($this->_xh['ac'] == '1' || strcasecmp($this->_xh['ac'], 'true') == 0) { + $this->_xh['value'] = true; + } else { + // log if receiving something strange, even though we set the value to false anyway + if ($this->_xh['ac'] != '0' && strcasecmp($this->_xh['ac'], 'false') != 0) { + error_log('XML-RPC: ' . __METHOD__ . ': invalid value received in BOOLEAN: ' . $this->_xh['ac']); + } + $this->_xh['value'] = false; + } + } elseif ($name == 'DOUBLE') { + // we have a DOUBLE + // we must check that only 0123456789-. are characters here + // NOTE: regexp could be much stricter than this... + if (!preg_match('/^[+-eE0123456789 \t.]+$/', $this->_xh['ac'])) { + /// @todo: find a better way of throwing an error than this! + error_log('XML-RPC: ' . __METHOD__ . ': non numeric value received in DOUBLE: ' . $this->_xh['ac']); + $this->_xh['value'] = 'ERROR_NON_NUMERIC_FOUND'; + } else { + // it's ok, add it on + $this->_xh['value'] = (double)$this->_xh['ac']; + } + } else { + // we have an I4/I8/INT + // we must check that only 0123456789- are characters here + if (!preg_match('/^[+-]?[0123456789 \t]+$/', $this->_xh['ac'])) { + /// @todo find a better way of throwing an error than this! + error_log('XML-RPC: ' . __METHOD__ . ': non numeric value received in INT: ' . $this->_xh['ac']); + $this->_xh['value'] = 'ERROR_NON_NUMERIC_FOUND'; + } else { + // it's ok, add it on + $this->_xh['value'] = (int)$this->_xh['ac']; + } + } + $this->_xh['lv'] = 3; // indicate we've found a value + break; + case 'NAME': + $this->_xh['valuestack'][count($this->_xh['valuestack']) - 1]['name'] = $this->_xh['ac']; + break; + case 'MEMBER': + // add to array in the stack the last element built, + // unless no VALUE was found + if ($this->_xh['vt']) { + $vscount = count($this->_xh['valuestack']); + $this->_xh['valuestack'][$vscount - 1]['values'][$this->_xh['valuestack'][$vscount - 1]['name']] = $this->_xh['value']; + } else { + error_log('XML-RPC: ' . __METHOD__ . ': missing VALUE inside STRUCT in received xml'); + } + break; + case 'DATA': + $this->_xh['vt'] = null; // reset this to check for 2 data elements in a row - even if they're empty + break; + case 'STRUCT': + case 'ARRAY': + // fetch out of stack array of values, and promote it to current value + $currVal = array_pop($this->_xh['valuestack']); + $this->_xh['value'] = $currVal['values']; + $this->_xh['vt'] = strtolower($name); + if (isset($currVal['php_class'])) { + $this->_xh['php_class'] = $currVal['php_class']; + } + break; + case 'PARAM': + // add to array of params the current value, + // unless no VALUE was found + if ($this->_xh['vt']) { + $this->_xh['params'][] = $this->_xh['value']; + $this->_xh['pt'][] = $this->_xh['vt']; + } else { + error_log('XML-RPC: ' . __METHOD__ . ': missing VALUE inside PARAM in received xml'); + } + break; + case 'METHODNAME': + $this->_xh['method'] = preg_replace('/^[\n\r\t ]+/', '', $this->_xh['ac']); + break; + case 'NIL': + case 'EX:NIL': + if (PhpXmlRpc::$xmlrpc_null_extension) { + $this->_xh['vt'] = 'null'; + $this->_xh['value'] = null; + $this->_xh['lv'] = 3; + break; + } + // drop through intentionally if nil extension not enabled + case 'PARAMS': + case 'FAULT': + case 'METHODCALL': + case 'METHORESPONSE': + break; + default: + // End of INVALID ELEMENT! + // shall we add an assert here for unreachable code??? + break; + } + } + } + + /** + * Used in decoding xmlrpc requests/responses without rebuilding xmlrpc Values. + */ + public function xmlrpc_ee_fast($parser, $name) + { + $this->xmlrpc_ee($parser, $name, false); + } + + /** + * xml parser handler function for character data. + */ + public function xmlrpc_cd($parser, $data) + { + // skip processing if xml fault already detected + if ($this->_xh['isf'] < 2) { + // "lookforvalue==3" means that we've found an entire value + // and should discard any further character data + if ($this->_xh['lv'] != 3) { + $this->_xh['ac'] .= $data; + } + } + } + + /** + * xml parser handler function for 'other stuff', ie. not char data or + * element start/end tag. In fact it only gets called on unknown entities... + */ + public function xmlrpc_dh($parser, $data) + { + // skip processing if xml fault already detected + if ($this->_xh['isf'] < 2) { + if (substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';') { + $this->_xh['ac'] .= $data; + } + } + + return true; + } + + /** + * xml charset encoding guessing helper function. + * Tries to determine the charset encoding of an XML chunk received over HTTP. + * NB: according to the spec (RFC 3023), if text/xml content-type is received over HTTP without a content-type, + * we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of non conforming (legacy?) clients/servers, + * which will be most probably using UTF-8 anyway... + * In order of importance checks: + * 1. http headers + * 2. BOM + * 3. XML declaration + * 4. guesses using mb_detect_encoding() + * + * @param string $httpHeader the http Content-type header + * @param string $xmlChunk xml content buffer + * @param string $encodingPrefs comma separated list of character encodings to be used as default (when mb extension is enabled). + * This can also be set globally using PhpXmlRpc::$xmlrpc_detectencodings + * @return string the encoding determined. Null if it can't be determined and mbstring is enabled, + * PhpXmlRpc::$xmlrpc_defencoding if it can't be determined and mbstring is not enabled + * + * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!! + */ + public static function guessEncoding($httpHeader = '', $xmlChunk = '', $encodingPrefs = null) + { + // discussion: see http://www.yale.edu/pclt/encoding/ + // 1 - test if encoding is specified in HTTP HEADERS + + // Details: + // LWS: (\13\10)?( |\t)+ + // token: (any char but excluded stuff)+ + // quoted string: " (any char but double quotes and control chars)* " + // header: Content-type = ...; charset=value(; ...)* + // where value is of type token, no LWS allowed between 'charset' and value + // Note: we do not check for invalid chars in VALUE: + // this had better be done using pure ereg as below + // Note 2: we might be removing whitespace/tabs that ought to be left in if + // the received charset is a quoted string. But nobody uses such charset names... + + /// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it? + $matches = array(); + if (preg_match('/;\s*charset\s*=([^;]+)/i', $httpHeader, $matches)) { + return strtoupper(trim($matches[1], " \t\"")); + } + + // 2 - scan the first bytes of the data for a UTF-16 (or other) BOM pattern + // (source: http://www.w3.org/TR/2000/REC-xml-20001006) + // NOTE: actually, according to the spec, even if we find the BOM and determine + // an encoding, we should check if there is an encoding specified + // in the xml declaration, and verify if they match. + /// @todo implement check as described above? + /// @todo implement check for first bytes of string even without a BOM? (It sure looks harder than for cases WITH a BOM) + if (preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlChunk)) { + return 'UCS-4'; + } elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlChunk)) { + return 'UTF-16'; + } elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlChunk)) { + return 'UTF-8'; + } + + // 3 - test if encoding is specified in the xml declaration + // Details: + // SPACE: (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+ + // EQ: SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]* + if (preg_match('/^<\?xml\s+version\s*=\s*' . "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))" . + '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/", + $xmlChunk, $matches)) { + return strtoupper(substr($matches[2], 1, -1)); + } + + // 4 - if mbstring is available, let it do the guesswork + if (extension_loaded('mbstring')) { + if ($encodingPrefs == null && PhpXmlRpc::$xmlrpc_detectencodings != null) { + $encodingPrefs = PhpXmlRpc::$xmlrpc_detectencodings; + } + if ($encodingPrefs) { + $enc = mb_detect_encoding($xmlChunk, $encodingPrefs); + } else { + $enc = mb_detect_encoding($xmlChunk); + } + // NB: mb_detect likes to call it ascii, xml parser likes to call it US_ASCII... + // IANA also likes better US-ASCII, so go with it + if ($enc == 'ASCII') { + $enc = 'US-' . $enc; + } + + return $enc; + } else { + // no encoding specified: as per HTTP1.1 assume it is iso-8859-1? + // Both RFC 2616 (HTTP 1.1) and 1945 (HTTP 1.0) clearly state that for text/xxx content types + // this should be the standard. And we should be getting text/xml as request and response. + // BUT we have to be backward compatible with the lib, which always used UTF-8 as default... + return PhpXmlRpc::$xmlrpc_defencoding; + } + } + + /** + * Helper function: checks if an xml chunk as a charset declaration (BOM or in the xml declaration) + * + * @param string $xmlChunk + * @return bool + */ + public static function hasEncoding($xmlChunk) + { + // scan the first bytes of the data for a UTF-16 (or other) BOM pattern + // (source: http://www.w3.org/TR/2000/REC-xml-20001006) + if (preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlChunk)) { + return true; + } elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlChunk)) { + return true; + } elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlChunk)) { + return true; + } + + // test if encoding is specified in the xml declaration + // Details: + // SPACE: (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+ + // EQ: SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]* + if (preg_match('/^<\?xml\s+version\s*=\s*' . "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))" . + '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/", + $xmlChunk, $matches)) { + return true; + } + + return false; + } +} diff --git a/lib/phpxmlrpc/src/PhpXmlRpc.php b/lib/phpxmlrpc/src/PhpXmlRpc.php new file mode 100644 index 0000000..c9b12ad --- /dev/null +++ b/lib/phpxmlrpc/src/PhpXmlRpc.php @@ -0,0 +1,150 @@ + 1, + 'invalid_return' => 2, + 'incorrect_params' => 3, + 'introspect_unknown' => 4, + 'http_error' => 5, + 'no_data' => 6, + 'no_ssl' => 7, + 'curl_fail' => 8, + 'invalid_request' => 15, + 'no_curl' => 16, + 'server_error' => 17, + 'multicall_error' => 18, + 'multicall_notstruct' => 9, + 'multicall_nomethod' => 10, + 'multicall_notstring' => 11, + 'multicall_recursion' => 12, + 'multicall_noparams' => 13, + 'multicall_notarray' => 14, + + 'cannot_decompress' => 103, + 'decompress_fail' => 104, + 'dechunk_fail' => 105, + 'server_cannot_decompress' => 106, + 'server_decompress_fail' => 107, + ); + + static public $xmlrpcstr = array( + 'unknown_method' => 'Unknown method', + 'invalid_return' => 'Invalid return payload: enable debugging to examine incoming payload', + 'incorrect_params' => 'Incorrect parameters passed to method', + 'introspect_unknown' => "Can't introspect: method unknown", + 'http_error' => "Didn't receive 200 OK from remote server.", + 'no_data' => 'No data received from server.', + 'no_ssl' => 'No SSL support compiled in.', + 'curl_fail' => 'CURL error', + 'invalid_request' => 'Invalid request payload', + 'no_curl' => 'No CURL support compiled in.', + 'server_error' => 'Internal server error', + 'multicall_error' => 'Received from server invalid multicall response', + 'multicall_notstruct' => 'system.multicall expected struct', + 'multicall_nomethod' => 'missing methodName', + 'multicall_notstring' => 'methodName is not a string', + 'multicall_recursion' => 'recursive system.multicall forbidden', + 'multicall_noparams' => 'missing params', + 'multicall_notarray' => 'params is not an array', + + 'cannot_decompress' => 'Received from server compressed HTTP and cannot decompress', + 'decompress_fail' => 'Received from server invalid compressed HTTP', + 'dechunk_fail' => 'Received from server invalid chunked HTTP', + 'server_cannot_decompress' => 'Received from client compressed HTTP request and cannot decompress', + 'server_decompress_fail' => 'Received from client invalid compressed HTTP request', + ); + + // The charset encoding used by the server for received requests and + // by the client for received responses when received charset cannot be determined + // and mbstring extension is not enabled + public static $xmlrpc_defencoding = "UTF-8"; + + // The list of encodings used by the server for requests and by the client for responses + // to detect the charset of the received payload when + // - the charset cannot be determined by looking at http headers, xml declaration or BOM + // - mbstring extension is enabled + public static $xmlrpc_detectencodings = array(); + + // The encoding used internally by PHP. + // String values received as xml will be converted to this, and php strings will be converted to xml + // as if having been coded with this. + // Valid also when defining names of xmlrpc methods + public static $xmlrpc_internalencoding = "UTF-8"; + + public static $xmlrpcName = "XML-RPC for PHP"; + public static $xmlrpcVersion = "4.1.0"; + + // let user errors start at 800 + public static $xmlrpcerruser = 800; + // let XML parse errors start at 100 + public static $xmlrpcerrxml = 100; + + // set to TRUE to enable correct decoding of and values + public static $xmlrpc_null_extension = false; + + // set to TRUE to enable encoding of php NULL values to instead of + public static $xmlrpc_null_apache_encoding = false; + + public static $xmlrpc_null_apache_encoding_ns = "http://ws.apache.org/xmlrpc/namespaces/extensions"; + + /** + * A function to be used for compatibility with legacy code: it creates all global variables which used to be declared, + * such as library version etc... + */ + public static function exportGlobals() + { + $reflection = new \ReflectionClass('PhpXmlRpc\PhpXmlRpc'); + foreach ($reflection->getStaticProperties() as $name => $value) { + $GLOBALS[$name] = $value; + } + + // NB: all the variables exported into the global namespace below here do NOT guarantee 100% + // compatibility, as they are NOT reimported back during calls to importGlobals() + + $reflection = new \ReflectionClass('PhpXmlRpc\Value'); + foreach ($reflection->getStaticProperties() as $name => $value) { + $GLOBALS[$name] = $value; + } + + $parser = new Helper\XMLParser(); + $reflection = new \ReflectionClass('PhpXmlRpc\Helper\XMLParser'); + foreach ($reflection->getProperties(\ReflectionProperty::IS_PUBLIC) as $name => $value) { + if (in_array($value->getName(), array('xmlrpc_valid_parents'))) + { + $GLOBALS[$value->getName()] = $value->getValue($parser); + } + } + + $charset = Helper\Charset::instance(); + $GLOBALS['xml_iso88591_Entities'] = $charset->getEntities('iso88591'); + } + + /** + * A function to be used for compatibility with legacy code: it gets the values of all global variables which used + * to be declared, such as library version etc... and sets them to php classes. + * It should be used by code which changed the values of those global variables to alter the working of the library. + * Example code: + * 1. include xmlrpc.inc + * 2. set the values, e.g. $GLOBALS['xmlrpc_internalencoding'] = 'UTF-8'; + * 3. import them: PhpXmlRpc\PhpXmlRpc::importGlobals(); + * 4. run your own code. + */ + public static function importGlobals() + { + $reflection = new \ReflectionClass('PhpXmlRpc\PhpXmlRpc'); + $staticProperties = $reflection->getStaticProperties(); + foreach ($staticProperties as $name => $value) { + if (isset($GLOBALS[$name])) { + self::$$name = $GLOBALS[$name]; + } + } + } + +} diff --git a/lib/phpxmlrpc/src/Request.php b/lib/phpxmlrpc/src/Request.php new file mode 100644 index 0000000..0051e46 --- /dev/null +++ b/lib/phpxmlrpc/src/Request.php @@ -0,0 +1,389 @@ +methodname = $methodName; + foreach ($params as $param) { + $this->addParam($param); + } + } + + public function xml_header($charsetEncoding = '') + { + if ($charsetEncoding != '') { + return "\n\n"; + } else { + return "\n\n"; + } + } + + public function xml_footer() + { + return ''; + } + + public function createPayload($charsetEncoding = '') + { + if ($charsetEncoding != '') { + $this->content_type = 'text/xml; charset=' . $charsetEncoding; + } else { + $this->content_type = 'text/xml'; + } + $this->payload = $this->xml_header($charsetEncoding); + $this->payload .= '' . Charset::instance()->encodeEntities( + $this->methodname, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "\n"; + $this->payload .= "\n"; + foreach ($this->params as $p) { + $this->payload .= "\n" . $p->serialize($charsetEncoding) . + "\n"; + } + $this->payload .= "\n"; + $this->payload .= $this->xml_footer(); + } + + /** + * Gets/sets the xmlrpc method to be invoked. + * + * @param string $methodName the method to be set (leave empty not to set it) + * + * @return string the method that will be invoked + */ + public function method($methodName = '') + { + if ($methodName != '') { + $this->methodname = $methodName; + } + + return $this->methodname; + } + + /** + * Returns xml representation of the message. XML prologue included. + * + * @param string $charsetEncoding + * + * @return string the xml representation of the message, xml prologue included + */ + public function serialize($charsetEncoding = '') + { + $this->createPayload($charsetEncoding); + + return $this->payload; + } + + /** + * Add a parameter to the list of parameters to be used upon method invocation. + * + * Checks that $params is actually a Value object and not a plain php value. + * + * @param Value $param + * + * @return boolean false on failure + */ + public function addParam($param) + { + // add check: do not add to self params which are not xmlrpc values + if (is_object($param) && is_a($param, 'PhpXmlRpc\Value')) { + $this->params[] = $param; + + return true; + } else { + return false; + } + } + + /** + * Returns the nth parameter in the request. The index zero-based. + * + * @param integer $i the index of the parameter to fetch (zero based) + * + * @return Value the i-th parameter + */ + public function getParam($i) + { + return $this->params[$i]; + } + + /** + * Returns the number of parameters in the message. + * + * @return integer the number of parameters currently set + */ + public function getNumParams() + { + return count($this->params); + } + + /** + * Given an open file handle, read all data available and parse it as an xmlrpc response. + * + * NB: the file handle is not closed by this function. + * NNB: might have trouble in rare cases to work on network streams, as we check for a read of 0 bytes instead of + * feof($fp). But since checking for feof(null) returns false, we would risk an infinite loop in that case, + * because we cannot trust the caller to give us a valid pointer to an open file... + * + * @param resource $fp stream pointer + * + * @return Response + * + * @todo add 2nd & 3rd param to be passed to ParseResponse() ??? + */ + public function parseResponseFile($fp) + { + $ipd = ''; + while ($data = fread($fp, 32768)) { + $ipd .= $data; + } + return $this->parseResponse($ipd); + } + + /** + * Parse the xmlrpc response contained in the string $data and return a Response object. + * + * When $this->debug has been set to a value greater than 0, will echo debug messages to screen while decoding. + * + * @param string $data the xmlrpc response, possibly including http headers + * @param bool $headersProcessed when true prevents parsing HTTP headers for interpretation of content-encoding and + * consequent decoding + * @param string $returnType decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or + * 'phpvals' + * + * @return Response + */ + public function parseResponse($data = '', $headersProcessed = false, $returnType = 'xmlrpcvals') + { + if ($this->debug) { + Logger::instance()->debugMessage("---GOT---\n$data\n---END---"); + } + + $this->httpResponse = array('raw_data' => $data, 'headers' => array(), 'cookies' => array()); + + if ($data == '') { + error_log('XML-RPC: ' . __METHOD__ . ': no response received from server.'); + return new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']); + } + + // parse the HTTP headers of the response, if present, and separate them from data + if (substr($data, 0, 4) == 'HTTP') { + $httpParser = new Http(); + try { + $this->httpResponse = $httpParser->parseResponseHeaders($data, $headersProcessed, $this->debug); + } catch(\Exception $e) { + $r = new Response(0, $e->getCode(), $e->getMessage()); + // failed processing of HTTP response headers + // save into response obj the full payload received, for debugging + $r->raw_data = $data; + + return $r; + } + } + + // be tolerant of extra whitespace in response body + $data = trim($data); + + /// @todo return an error msg if $data=='' ? + + // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts) + // idea from Luca Mariano originally in PEARified version of the lib + $pos = strrpos($data, ''); + if ($pos !== false) { + $data = substr($data, 0, $pos + 17); + } + + // try to 'guestimate' the character encoding of the received response + $respEncoding = XMLParser::guessEncoding(@$this->httpResponse['headers']['content-type'], $data); + + if ($this->debug) { + $start = strpos($data, '', $start); + $comments = substr($data, $start, $end - $start); + Logger::instance()->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" . + str_replace("\n", "\n\t", base64_decode($comments)) . "\n---END---", $respEncoding); + } + } + + // if user wants back raw xml, give it to him + if ($returnType == 'xml') { + $r = new Response($data, 0, '', 'xml'); + $r->hdrs = $this->httpResponse['headers']; + $r->_cookies = $this->httpResponse['cookies']; + $r->raw_data = $this->httpResponse['raw_data']; + + return $r; + } + + if ($respEncoding != '') { + + // Since parsing will fail if charset is not specified in the xml prologue, + // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that... + // The following code might be better for mb_string enabled installs, but + // makes the lib about 200% slower... + //if (!is_valid_charset($respEncoding, array('UTF-8'))) + if (!in_array($respEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($data)) { + if ($respEncoding == 'ISO-8859-1') { + $data = utf8_encode($data); + } else { + if (extension_loaded('mbstring')) { + $data = mb_convert_encoding($data, 'UTF-8', $respEncoding); + } else { + error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $respEncoding); + } + } + } + } + + $parser = xml_parser_create(); + xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true); + // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell + // the xml parser to give us back data in the expected charset. + // What if internal encoding is not in one of the 3 allowed? + // we use the broadest one, ie. utf8 + // This allows to send data which is native in various charset, + // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding + if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) { + xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8'); + } else { + xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding); + } + + $xmlRpcParser = new XMLParser(); + xml_set_object($parser, $xmlRpcParser); + + if ($returnType == 'phpvals') { + xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast'); + } else { + xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee'); + } + + xml_set_character_data_handler($parser, 'xmlrpc_cd'); + xml_set_default_handler($parser, 'xmlrpc_dh'); + + // first error check: xml not well formed + if (!xml_parse($parser, $data, count($data))) { + // thanks to Peter Kocks + if ((xml_get_current_line_number($parser)) == 1) { + $errStr = 'XML error at line 1, check URL'; + } else { + $errStr = sprintf('XML error: %s at line %d, column %d', + xml_error_string(xml_get_error_code($parser)), + xml_get_current_line_number($parser), xml_get_current_column_number($parser)); + } + error_log($errStr); + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' (' . $errStr . ')'); + xml_parser_free($parser); + if ($this->debug) { + print $errStr; + } + $r->hdrs = $this->httpResponse['headers']; + $r->_cookies = $this->httpResponse['cookies']; + $r->raw_data = $this->httpResponse['raw_data']; + + return $r; + } + xml_parser_free($parser); + // second error check: xml well formed but not xml-rpc compliant + if ($xmlRpcParser->_xh['isf'] > 1) { + if ($this->debug) { + /// @todo echo something for user? + } + + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], + PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']); + } + // third error check: parsing of the response has somehow gone boink. + // NB: shall we omit this check, since we trust the parsing code? + elseif ($returnType == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value'])) { + // something odd has happened + // and it's time to generate a client side error + // indicating something odd went on + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], + PhpXmlRpc::$xmlrpcstr['invalid_return']); + } else { + if ($this->debug > 1) { + Logger::instance()->debugMessage( + "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---" + ); + } + + // note that using =& will raise an error if $xmlRpcParser->_xh['st'] does not generate an object. + $v = &$xmlRpcParser->_xh['value']; + + if ($xmlRpcParser->_xh['isf']) { + /// @todo we should test here if server sent an int and a string, and/or coerce them into such... + if ($returnType == 'xmlrpcvals') { + $errNo_v = $v['faultCode']; + $errStr_v = $v['faultString']; + $errNo = $errNo_v->scalarval(); + $errStr = $errStr_v->scalarval(); + } else { + $errNo = $v['faultCode']; + $errStr = $v['faultString']; + } + + if ($errNo == 0) { + // FAULT returned, errno needs to reflect that + $errNo = -1; + } + + $r = new Response(0, $errNo, $errStr); + } else { + $r = new Response($v, 0, '', $returnType); + } + } + + $r->hdrs = $this->httpResponse['headers']; + $r->_cookies = $this->httpResponse['cookies']; + $r->raw_data = $this->httpResponse['raw_data']; + + return $r; + } + + /** + * Kept the old name even if Request class was renamed, for compatibility. + * + * @return string + */ + public function kindOf() + { + return 'msg'; + } + + /** + * Enables/disables the echoing to screen of the xmlrpc responses received. + * + * @param integer $in values 0, 1, 2 are supported + */ + public function setDebug($in) + { + $this->debug = $in; + } +} diff --git a/lib/phpxmlrpc/src/Response.php b/lib/phpxmlrpc/src/Response.php new file mode 100644 index 0000000..48ebca8 --- /dev/null +++ b/lib/phpxmlrpc/src/Response.php @@ -0,0 +1,158 @@ +errno = $fCode; + $this->errstr = $fString; + } else { + // successful response + $this->val = $val; + if ($valType == '') { + // user did not declare type of response value: try to guess it + if (is_object($this->val) && is_a($this->val, 'PhpXmlRpc\Value')) { + $this->valtyp = 'xmlrpcvals'; + } elseif (is_string($this->val)) { + $this->valtyp = 'xml'; + } else { + $this->valtyp = 'phpvals'; + } + } else { + // user declares type of resp value: believe him + $this->valtyp = $valType; + } + } + } + + /** + * Returns the error code of the response. + * + * @return integer the error code of this response (0 for not-error responses) + */ + public function faultCode() + { + return $this->errno; + } + + /** + * Returns the error code of the response. + * + * @return string the error string of this response ('' for not-error responses) + */ + public function faultString() + { + return $this->errstr; + } + + /** + * Returns the value received by the server. If the Response's faultCode is non-zero then the value returned by this + * method should not be used (it may not even be an object). + * + * @return Value|string|mixed the Value object returned by the server. Might be an xml string or plain php value + * depending on the convention adopted when creating the Response + */ + public function value() + { + return $this->val; + } + + /** + * Returns an array with the cookies received from the server. + * Array has the form: $cookiename => array ('value' => $val, $attr1 => $val1, $attr2 => $val2, ...) + * with attributes being e.g. 'expires', 'path', domain'. + * NB: cookies sent as 'expired' by the server (i.e. with an expiry date in the past) are still present in the array. + * It is up to the user-defined code to decide how to use the received cookies, and whether they have to be sent back + * with the next request to the server (using Client::setCookie) or not. + * + * @return array array of cookies received from the server + */ + public function cookies() + { + return $this->_cookies; + } + + /** + * Returns xml representation of the response. XML prologue not included. + * + * @param string $charsetEncoding the charset to be used for serialization. If null, US-ASCII is assumed + * + * @return string the xml representation of the response + * + * @throws \Exception + */ + public function serialize($charsetEncoding = '') + { + if ($charsetEncoding != '') { + $this->content_type = 'text/xml; charset=' . $charsetEncoding; + } else { + $this->content_type = 'text/xml'; + } + if (PhpXmlRpc::$xmlrpc_null_apache_encoding) { + $result = "\n"; + } else { + $result = "\n"; + } + if ($this->errno) { + // G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients + // by xml-encoding non ascii chars + $result .= "\n" . + "\nfaultCode\n" . $this->errno . + "\n\n\nfaultString\n" . + Charset::instance()->encodeEntities($this->errstr, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "\n\n" . + "\n\n"; + } else { + if (!is_object($this->val) || !is_a($this->val, 'PhpXmlRpc\Value')) { + if (is_string($this->val) && $this->valtyp == 'xml') { + $result .= "\n\n" . + $this->val . + "\n"; + } else { + /// @todo try to build something serializable? + throw new \Exception('cannot serialize xmlrpc response objects whose content is native php values'); + } + } else { + $result .= "\n\n" . + $this->val->serialize($charsetEncoding) . + "\n"; + } + } + $result .= "\n"; + $this->payload = $result; + + return $result; + } +} diff --git a/lib/phpxmlrpc/src/Server.php b/lib/phpxmlrpc/src/Server.php new file mode 100644 index 0000000..1a52fe6 --- /dev/null +++ b/lib/phpxmlrpc/src/Server.php @@ -0,0 +1,1068 @@ +accepted_compression = array('gzip', 'deflate'); + $this->compress_response = true; + } + + // by default the xml parser can support these 3 charset encodings + $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII'); + + // dispMap is a dispatch array of methods mapped to function names and signatures. + // If a method doesn't appear in the map then an unknown method error is generated + /* milosch - changed to make passing dispMap optional. + * instead, you can use the class add_to_map() function + * to add functions manually (borrowed from SOAPX4) + */ + if ($dispatchMap) { + $this->dmap = $dispatchMap; + if ($serviceNow) { + $this->service(); + } + } + } + + /** + * Set debug level of server. + * + * @param integer $level debug lvl: determines info added to xmlrpc responses (as xml comments) + * 0 = no debug info, + * 1 = msgs set from user with debugmsg(), + * 2 = add complete xmlrpc request (headers and body), + * 3 = add also all processing warnings happened during method processing + * (NB: this involves setting a custom error handler, and might interfere + * with the standard processing of the php function exposed as method. In + * particular, triggering an USER_ERROR level error will not halt script + * execution anymore, but just end up logged in the xmlrpc response) + * Note that info added at level 2 and 3 will be base64 encoded + */ + public function setDebug($level) + { + $this->debug = $level; + } + + /** + * Add a string to the debug info that can be later serialized by the server + * as part of the response message. + * Note that for best compatibility, the debug string should be encoded using + * the PhpXmlRpc::$xmlrpc_internalencoding character set. + * + * @param string $msg + * @access public + */ + public static function xmlrpc_debugmsg($msg) + { + static::$_xmlrpc_debuginfo .= $msg . "\n"; + } + + public static function error_occurred($msg) + { + static::$_xmlrpcs_occurred_errors .= $msg . "\n"; + } + + /** + * Return a string with the serialized representation of all debug info. + * + * @param string $charsetEncoding the target charset encoding for the serialization + * + * @return string an XML comment (or two) + */ + public function serializeDebug($charsetEncoding = '') + { + // Tough encoding problem: which internal charset should we assume for debug info? + // It might contain a copy of raw data received from client, ie with unknown encoding, + // intermixed with php generated data and user generated data... + // so we split it: system debug is base 64 encoded, + // user debug info should be encoded by the end user using the INTERNAL_ENCODING + $out = ''; + if ($this->debug_info != '') { + $out .= "\n"; + } + if (static::$_xmlrpc_debuginfo != '') { + $out .= "\n"; + // NB: a better solution MIGHT be to use CDATA, but we need to insert it + // into return payload AFTER the beginning tag + //$out .= "', ']_]_>', static::$_xmlrpc_debuginfo) . "\n]]>\n"; + } + + return $out; + } + + /** + * Execute the xmlrpc request, printing the response. + * + * @param string $data the request body. If null, the http POST request will be examined + * @param bool $returnPayload When true, return the response but do not echo it or any http header + * + * @return Response|string the response object (usually not used by caller...) or its xml serialization + * + * @throws \Exception in case the executed method does throw an exception (and depending on server configuration) + */ + public function service($data = null, $returnPayload = false) + { + if ($data === null) { + $data = file_get_contents('php://input'); + } + $rawData = $data; + + // reset internal debug info + $this->debug_info = ''; + + // Save what we received, before parsing it + if ($this->debug > 1) { + $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++"); + } + + $r = $this->parseRequestHeaders($data, $reqCharset, $respCharset, $respEncoding); + if (!$r) { + // this actually executes the request + $r = $this->parseRequest($data, $reqCharset); + } + + // save full body of request into response, for more debugging usages + $r->raw_data = $rawData; + + if ($this->debug > 2 && static::$_xmlrpcs_occurred_errors) { + $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" . + static::$_xmlrpcs_occurred_errors . "+++END+++"); + } + + $payload = $this->xml_header($respCharset); + if ($this->debug > 0) { + $payload = $payload . $this->serializeDebug($respCharset); + } + + // G. Giunta 2006-01-27: do not create response serialization if it has + // already happened. Helps building json magic + if (empty($r->payload)) { + $r->serialize($respCharset); + } + $payload = $payload . $r->payload; + + if ($returnPayload) { + return $payload; + } + + // if we get a warning/error that has output some text before here, then we cannot + // add a new header. We cannot say we are sending xml, either... + if (!headers_sent()) { + header('Content-Type: ' . $r->content_type); + // we do not know if client actually told us an accepted charset, but if he did + // we have to tell him what we did + header("Vary: Accept-Charset"); + + // http compression of output: only + // if we can do it, and we want to do it, and client asked us to, + // and php ini settings do not force it already + $phpNoSelfCompress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler'); + if ($this->compress_response && function_exists('gzencode') && $respEncoding != '' + && $phpNoSelfCompress + ) { + if (strpos($respEncoding, 'gzip') !== false) { + $payload = gzencode($payload); + header("Content-Encoding: gzip"); + header("Vary: Accept-Encoding"); + } elseif (strpos($respEncoding, 'deflate') !== false) { + $payload = gzcompress($payload); + header("Content-Encoding: deflate"); + header("Vary: Accept-Encoding"); + } + } + + // do not output content-length header if php is compressing output for us: + // it will mess up measurements + if ($phpNoSelfCompress) { + header('Content-Length: ' . (int)strlen($payload)); + } + } else { + error_log('XML-RPC: ' . __METHOD__ . ': http headers already sent before response is fully generated. Check for php warning or error messages'); + } + + print $payload; + + // return request, in case subclasses want it + return $r; + } + + /** + * Add a method to the dispatch map. + * + * @param string $methodName the name with which the method will be made available + * @param string $function the php function that will get invoked + * @param array $sig the array of valid method signatures + * @param string $doc method documentation + * @param array $sigDoc the array of valid method signatures docs (one string per param, one for return type) + */ + public function add_to_map($methodName, $function, $sig = null, $doc = false, $sigDoc = false) + { + $this->dmap[$methodName] = array( + 'function' => $function, + 'docstring' => $doc, + ); + if ($sig) { + $this->dmap[$methodName]['signature'] = $sig; + } + if ($sigDoc) { + $this->dmap[$methodName]['signature_docs'] = $sigDoc; + } + } + + /** + * Verify type and number of parameters received against a list of known signatures. + * + * @param array|Request $in array of either xmlrpc value objects or xmlrpc type definitions + * @param array $sigs array of known signatures to match against + * + * @return array + */ + protected function verifySignature($in, $sigs) + { + // check each possible signature in turn + if (is_object($in)) { + $numParams = $in->getNumParams(); + } else { + $numParams = count($in); + } + foreach ($sigs as $curSig) { + if (count($curSig) == $numParams + 1) { + $itsOK = 1; + for ($n = 0; $n < $numParams; $n++) { + if (is_object($in)) { + $p = $in->getParam($n); + if ($p->kindOf() == 'scalar') { + $pt = $p->scalartyp(); + } else { + $pt = $p->kindOf(); + } + } else { + $pt = ($in[$n] == 'i4') ? 'int' : strtolower($in[$n]); // dispatch maps never use i4... + } + + // param index is $n+1, as first member of sig is return type + if ($pt != $curSig[$n + 1] && $curSig[$n + 1] != Value::$xmlrpcValue) { + $itsOK = 0; + $pno = $n + 1; + $wanted = $curSig[$n + 1]; + $got = $pt; + break; + } + } + if ($itsOK) { + return array(1, ''); + } + } + } + if (isset($wanted)) { + return array(0, "Wanted ${wanted}, got ${got} at param ${pno}"); + } else { + return array(0, "No method signature matches number of parameters"); + } + } + + /** + * Parse http headers received along with xmlrpc request. If needed, inflate request. + * + * @return mixed Response|null on success or an error Response + */ + protected function parseRequestHeaders(&$data, &$reqEncoding, &$respEncoding, &$respCompression) + { + // check if $_SERVER is populated: it might have been disabled via ini file + // (this is true even when in CLI mode) + if (count($_SERVER) == 0) { + error_log('XML-RPC: ' . __METHOD__ . ': cannot parse request headers as $_SERVER is not populated'); + } + + if ($this->debug > 1) { + if (function_exists('getallheaders')) { + $this->debugmsg(''); // empty line + foreach (getallheaders() as $name => $val) { + $this->debugmsg("HEADER: $name: $val"); + } + } + } + + if (isset($_SERVER['HTTP_CONTENT_ENCODING'])) { + $contentEncoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']); + } else { + $contentEncoding = ''; + } + + // check if request body has been compressed and decompress it + if ($contentEncoding != '' && strlen($data)) { + if ($contentEncoding == 'deflate' || $contentEncoding == 'gzip') { + // if decoding works, use it. else assume data wasn't gzencoded + if (function_exists('gzinflate') && in_array($contentEncoding, $this->accepted_compression)) { + if ($contentEncoding == 'deflate' && $degzdata = @gzuncompress($data)) { + $data = $degzdata; + if ($this->debug > 1) { + $this->debugmsg("\n+++INFLATED REQUEST+++[" . strlen($data) . " chars]+++\n" . $data . "\n+++END+++"); + } + } elseif ($contentEncoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) { + $data = $degzdata; + if ($this->debug > 1) { + $this->debugmsg("+++INFLATED REQUEST+++[" . strlen($data) . " chars]+++\n" . $data . "\n+++END+++"); + } + } else { + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_decompress_fail'], PhpXmlRpc::$xmlrpcstr['server_decompress_fail']); + + return $r; + } + } else { + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_cannot_decompress'], PhpXmlRpc::$xmlrpcstr['server_cannot_decompress']); + + return $r; + } + } + } + + // check if client specified accepted charsets, and if we know how to fulfill + // the request + if ($this->response_charset_encoding == 'auto') { + $respEncoding = ''; + if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) { + // here we should check if we can match the client-requested encoding + // with the encodings we know we can generate. + /// @todo we should parse q=0.x preferences instead of getting first charset specified... + $clientAcceptedCharsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET'])); + // Give preference to internal encoding + $knownCharsets = array(PhpXmlRpc::$xmlrpc_internalencoding, 'UTF-8', 'ISO-8859-1', 'US-ASCII'); + foreach ($knownCharsets as $charset) { + foreach ($clientAcceptedCharsets as $accepted) { + if (strpos($accepted, $charset) === 0) { + $respEncoding = $charset; + break; + } + } + if ($respEncoding) { + break; + } + } + } + } else { + $respEncoding = $this->response_charset_encoding; + } + + if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) { + $respCompression = $_SERVER['HTTP_ACCEPT_ENCODING']; + } else { + $respCompression = ''; + } + + // 'guestimate' request encoding + /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check??? + $reqEncoding = XMLParser::guessEncoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '', + $data); + + return; + } + + /** + * Parse an xml chunk containing an xmlrpc request and execute the corresponding + * php function registered with the server. + * + * @param string $data the xml request + * @param string $reqEncoding (optional) the charset encoding of the xml request + * + * @return Response + * + * @throws \Exception in case the executed method does throw an exception (and depending on server configuration) + */ + public function parseRequest($data, $reqEncoding = '') + { + // decompose incoming XML into request structure + + if ($reqEncoding != '') { + // Since parsing will fail if charset is not specified in the xml prologue, + // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that... + // The following code might be better for mb_string enabled installs, but + // makes the lib about 200% slower... + //if (!is_valid_charset($reqEncoding, array('UTF-8'))) + if (!in_array($reqEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($data)) { + if ($reqEncoding == 'ISO-8859-1') { + $data = utf8_encode($data); + } else { + if (extension_loaded('mbstring')) { + $data = mb_convert_encoding($data, 'UTF-8', $reqEncoding); + } else { + error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received request: ' . $reqEncoding); + } + } + } + } + + $parser = xml_parser_create(); + xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true); + // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell + // the xml parser to give us back data in the expected charset + // What if internal encoding is not in one of the 3 allowed? + // we use the broadest one, ie. utf8 + // This allows to send data which is native in various charset, + // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding + if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) { + xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8'); + } else { + xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding); + } + + $xmlRpcParser = new XMLParser(); + xml_set_object($parser, $xmlRpcParser); + + if ($this->functions_parameters_type != 'xmlrpcvals') { + xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast'); + } else { + xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee'); + } + xml_set_character_data_handler($parser, 'xmlrpc_cd'); + xml_set_default_handler($parser, 'xmlrpc_dh'); + if (!xml_parse($parser, $data, 1)) { + // return XML error as a faultCode + $r = new Response(0, + PhpXmlRpc::$xmlrpcerrxml + xml_get_error_code($parser), + sprintf('XML error: %s at line %d, column %d', + xml_error_string(xml_get_error_code($parser)), + xml_get_current_line_number($parser), xml_get_current_column_number($parser))); + xml_parser_free($parser); + } elseif ($xmlRpcParser->_xh['isf']) { + xml_parser_free($parser); + $r = new Response(0, + PhpXmlRpc::$xmlrpcerr['invalid_request'], + PhpXmlRpc::$xmlrpcstr['invalid_request'] . ' ' . $xmlRpcParser->_xh['isf_reason']); + } else { + xml_parser_free($parser); + // small layering violation in favor of speed and memory usage: + // we should allow the 'execute' method handle this, but in the + // most common scenario (xmlrpc values type server with some methods + // registered as phpvals) that would mean a useless encode+decode pass + if ($this->functions_parameters_type != 'xmlrpcvals' || (isset($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type']) && ($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type'] == 'phpvals'))) { + if ($this->debug > 1) { + $this->debugmsg("\n+++PARSED+++\n" . var_export($xmlRpcParser->_xh['params'], true) . "\n+++END+++"); + } + $r = $this->execute($xmlRpcParser->_xh['method'], $xmlRpcParser->_xh['params'], $xmlRpcParser->_xh['pt']); + } else { + // build a Request object with data parsed from xml + $req = new Request($xmlRpcParser->_xh['method']); + // now add parameters in + for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) { + $req->addParam($xmlRpcParser->_xh['params'][$i]); + } + + if ($this->debug > 1) { + $this->debugmsg("\n+++PARSED+++\n" . var_export($req, true) . "\n+++END+++"); + } + $r = $this->execute($req); + } + } + + return $r; + } + + /** + * Execute a method invoked by the client, checking parameters used. + * + * @param mixed $req either a Request obj or a method name + * @param array $params array with method parameters as php types (if m is method name only) + * @param array $paramTypes array with xmlrpc types of method parameters (if m is method name only) + * + * @return Response + * + * @throws \Exception in case the executed method does throw an exception (and depending on server configuration) + */ + protected function execute($req, $params = null, $paramTypes = null) + { + static::$_xmlrpcs_occurred_errors = ''; + static::$_xmlrpc_debuginfo = ''; + + if (is_object($req)) { + $methName = $req->method(); + } else { + $methName = $req; + } + $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0); + $dmap = $sysCall ? $this->getSystemDispatchMap() : $this->dmap; + + if (!isset($dmap[$methName]['function'])) { + // No such method + return new Response(0, + PhpXmlRpc::$xmlrpcerr['unknown_method'], + PhpXmlRpc::$xmlrpcstr['unknown_method']); + } + + // Check signature + if (isset($dmap[$methName]['signature'])) { + $sig = $dmap[$methName]['signature']; + if (is_object($req)) { + list($ok, $errStr) = $this->verifySignature($req, $sig); + } else { + list($ok, $errStr) = $this->verifySignature($paramTypes, $sig); + } + if (!$ok) { + // Didn't match. + return new Response( + 0, + PhpXmlRpc::$xmlrpcerr['incorrect_params'], + PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": ${errStr}" + ); + } + } + + $func = $dmap[$methName]['function']; + // let the 'class::function' syntax be accepted in dispatch maps + if (is_string($func) && strpos($func, '::')) { + $func = explode('::', $func); + } + + if (is_array($func)) { + if (is_object($func[0])) { + $funcName = get_class($func[0]) . '->' . $func[1]; + } else { + $funcName = implode('::', $func); + } + } else if ($func instanceof \Closure) { + $funcName = 'Closure'; + } else { + $funcName = $func; + } + + // verify that function to be invoked is in fact callable + if (!is_callable($func)) { + error_log("XML-RPC: " . __METHOD__ . ": function '$funcName' registered as method handler is not callable"); + return new Response( + 0, + PhpXmlRpc::$xmlrpcerr['server_error'], + PhpXmlRpc::$xmlrpcstr['server_error'] . ": no function matches method" + ); + } + + // If debug level is 3, we should catch all errors generated during + // processing of user function, and log them as part of response + if ($this->debug > 2) { + self::$_xmlrpcs_prev_ehandler = set_error_handler(array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler')); + } + + try { + // Allow mixed-convention servers + if (is_object($req)) { + if ($sysCall) { + $r = call_user_func($func, $this, $req); + } else { + $r = call_user_func($func, $req); + } + if (!is_a($r, 'PhpXmlRpc\Response')) { + error_log("XML-RPC: " . __METHOD__ . ": function '$funcName' registered as method handler does not return an xmlrpc response object but a " . gettype($r)); + if (is_a($r, 'PhpXmlRpc\Value')) { + $r = new Response($r); + } else { + $r = new Response( + 0, + PhpXmlRpc::$xmlrpcerr['server_error'], + PhpXmlRpc::$xmlrpcstr['server_error'] . ": function does not return xmlrpc response object" + ); + } + } + } else { + // call a 'plain php' function + if ($sysCall) { + array_unshift($params, $this); + $r = call_user_func_array($func, $params); + } else { + // 3rd API convention for method-handling functions: EPI-style + if ($this->functions_parameters_type == 'epivals') { + $r = call_user_func_array($func, array($methName, $params, $this->user_data)); + // mimic EPI behaviour: if we get an array that looks like an error, make it + // an eror response + if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r)) { + $r = new Response(0, (integer)$r['faultCode'], (string)$r['faultString']); + } else { + // functions using EPI api should NOT return resp objects, + // so make sure we encode the return type correctly + $r = new Response(php_xmlrpc_encode($r, array('extension_api'))); + } + } else { + $r = call_user_func_array($func, $params); + } + } + // the return type can be either a Response object or a plain php value... + if (!is_a($r, '\PhpXmlRpc\Response')) { + // what should we assume here about automatic encoding of datetimes + // and php classes instances??? + $r = new Response(php_xmlrpc_encode($r, $this->phpvals_encoding_options)); + } + } + } catch (\Exception $e) { + // (barring errors in the lib) an uncatched exception happened + // in the called function, we wrap it in a proper error-response + switch ($this->exception_handling) { + case 2: + if ($this->debug > 2) { + if (self::$_xmlrpcs_prev_ehandler) { + set_error_handler(self::$_xmlrpcs_prev_ehandler); + } else { + restore_error_handler(); + } + } + throw $e; + break; + case 1: + $r = new Response(0, $e->getCode(), $e->getMessage()); + break; + default: + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_error'], PhpXmlRpc::$xmlrpcstr['server_error']); + } + } + if ($this->debug > 2) { + // note: restore the error handler we found before calling the + // user func, even if it has been changed inside the func itself + if (self::$_xmlrpcs_prev_ehandler) { + set_error_handler(self::$_xmlrpcs_prev_ehandler); + } else { + restore_error_handler(); + } + } + + return $r; + } + + /** + * Add a string to the 'internal debug message' (separate from 'user debug message'). + * + * @param string $string + */ + protected function debugmsg($string) + { + $this->debug_info .= $string . "\n"; + } + + /** + * @param string $charsetEncoding + * @return string + */ + protected function xml_header($charsetEncoding = '') + { + if ($charsetEncoding != '') { + return "\n"; + } else { + return "\n"; + } + } + + /* Functions that implement system.XXX methods of xmlrpc servers */ + + /** + * @return array + */ + public function getSystemDispatchMap() + { + return array( + 'system.listMethods' => array( + 'function' => 'PhpXmlRpc\Server::_xmlrpcs_listMethods', + // listMethods: signature was either a string, or nothing. + // The useless string variant has been removed + 'signature' => array(array(Value::$xmlrpcArray)), + 'docstring' => 'This method lists all the methods that the XML-RPC server knows how to dispatch', + 'signature_docs' => array(array('list of method names')), + ), + 'system.methodHelp' => array( + 'function' => 'PhpXmlRpc\Server::_xmlrpcs_methodHelp', + 'signature' => array(array(Value::$xmlrpcString, Value::$xmlrpcString)), + 'docstring' => 'Returns help text if defined for the method passed, otherwise returns an empty string', + 'signature_docs' => array(array('method description', 'name of the method to be described')), + ), + 'system.methodSignature' => array( + 'function' => 'PhpXmlRpc\Server::_xmlrpcs_methodSignature', + 'signature' => array(array(Value::$xmlrpcArray, Value::$xmlrpcString)), + 'docstring' => 'Returns an array of known signatures (an array of arrays) for the method name passed. If no signatures are known, returns a none-array (test for type != array to detect missing signature)', + 'signature_docs' => array(array('list of known signatures, each sig being an array of xmlrpc type names', 'name of method to be described')), + ), + 'system.multicall' => array( + 'function' => 'PhpXmlRpc\Server::_xmlrpcs_multicall', + 'signature' => array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)), + 'docstring' => 'Boxcar multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details', + 'signature_docs' => array(array('list of response structs, where each struct has the usual members', 'list of calls, with each call being represented as a struct, with members "methodname" and "params"')), + ), + 'system.getCapabilities' => array( + 'function' => 'PhpXmlRpc\Server::_xmlrpcs_getCapabilities', + 'signature' => array(array(Value::$xmlrpcStruct)), + 'docstring' => 'This method lists all the capabilites that the XML-RPC server has: the (more or less standard) extensions to the xmlrpc spec that it adheres to', + 'signature_docs' => array(array('list of capabilities, described as structs with a version number and url for the spec')), + ), + ); + } + + /** + * @return array + */ + public function getCapabilities() + { + $outAr = array( + // xmlrpc spec: always supported + 'xmlrpc' => array( + 'specUrl' => 'http://www.xmlrpc.com/spec', + 'specVersion' => 1 + ), + // if we support system.xxx functions, we always support multicall, too... + // Note that, as of 2006/09/17, the following URL does not respond anymore + 'system.multicall' => array( + 'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208', + 'specVersion' => 1 + ), + // introspection: version 2! we support 'mixed', too + 'introspection' => array( + 'specUrl' => 'http://phpxmlrpc.sourceforge.net/doc-2/ch10.html', + 'specVersion' => 2, + ), + ); + + // NIL extension + if (PhpXmlRpc::$xmlrpc_null_extension) { + $outAr['nil'] = array( + 'specUrl' => 'http://www.ontosys.com/xml-rpc/extensions.php', + 'specVersion' => 1 + ); + } + + return $outAr; + } + + public static function _xmlrpcs_getCapabilities($server, $req = null) + { + $encoder = new Encoder(); + return new Response($encoder->encode($server->getCapabilities())); + } + + public static function _xmlrpcs_listMethods($server, $req = null) // if called in plain php values mode, second param is missing + { + $outAr = array(); + foreach ($server->dmap as $key => $val) { + $outAr[] = new Value($key, 'string'); + } + if ($server->allow_system_funcs) { + foreach ($server->getSystemDispatchMap() as $key => $val) { + $outAr[] = new Value($key, 'string'); + } + } + + return new Response(new Value($outAr, 'array')); + } + + public static function _xmlrpcs_methodSignature($server, $req) + { + // let accept as parameter both an xmlrpc value or string + if (is_object($req)) { + $methName = $req->getParam(0); + $methName = $methName->scalarval(); + } else { + $methName = $req; + } + if (strpos($methName, "system.") === 0) { + $dmap = $server->getSystemDispatchMap(); + } else { + $dmap = $server->dmap; + } + if (isset($dmap[$methName])) { + if (isset($dmap[$methName]['signature'])) { + $sigs = array(); + foreach ($dmap[$methName]['signature'] as $inSig) { + $curSig = array(); + foreach ($inSig as $sig) { + $curSig[] = new Value($sig, 'string'); + } + $sigs[] = new Value($curSig, 'array'); + } + $r = new Response(new Value($sigs, 'array')); + } else { + // NB: according to the official docs, we should be returning a + // "none-array" here, which means not-an-array + $r = new Response(new Value('undef', 'string')); + } + } else { + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']); + } + + return $r; + } + + public static function _xmlrpcs_methodHelp($server, $req) + { + // let accept as parameter both an xmlrpc value or string + if (is_object($req)) { + $methName = $req->getParam(0); + $methName = $methName->scalarval(); + } else { + $methName = $req; + } + if (strpos($methName, "system.") === 0) { + $dmap = $server->getSystemDispatchMap(); + } else { + $dmap = $server->dmap; + } + if (isset($dmap[$methName])) { + if (isset($dmap[$methName]['docstring'])) { + $r = new Response(new Value($dmap[$methName]['docstring']), 'string'); + } else { + $r = new Response(new Value('', 'string')); + } + } else { + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']); + } + + return $r; + } + + public static function _xmlrpcs_multicall_error($err) + { + if (is_string($err)) { + $str = PhpXmlRpc::$xmlrpcstr["multicall_${err}"]; + $code = PhpXmlRpc::$xmlrpcerr["multicall_${err}"]; + } else { + $code = $err->faultCode(); + $str = $err->faultString(); + } + $struct = array(); + $struct['faultCode'] = new Value($code, 'int'); + $struct['faultString'] = new Value($str, 'string'); + + return new Value($struct, 'struct'); + } + + public static function _xmlrpcs_multicall_do_call($server, $call) + { + if ($call->kindOf() != 'struct') { + return static::_xmlrpcs_multicall_error('notstruct'); + } + $methName = @$call['methodName']; + if (!$methName) { + return static::_xmlrpcs_multicall_error('nomethod'); + } + if ($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string') { + return static::_xmlrpcs_multicall_error('notstring'); + } + if ($methName->scalarval() == 'system.multicall') { + return static::_xmlrpcs_multicall_error('recursion'); + } + + $params = @$call['params']; + if (!$params) { + return static::_xmlrpcs_multicall_error('noparams'); + } + if ($params->kindOf() != 'array') { + return static::_xmlrpcs_multicall_error('notarray'); + } + + $req = new Request($methName->scalarval()); + foreach($params as $i => $param) { + if (!$req->addParam($param)) { + $i++; // for error message, we count params from 1 + return static::_xmlrpcs_multicall_error(new Response(0, + PhpXmlRpc::$xmlrpcerr['incorrect_params'], + PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": probable xml error in param " . $i)); + } + } + + $result = $server->execute($req); + + if ($result->faultCode() != 0) { + return static::_xmlrpcs_multicall_error($result); // Method returned fault. + } + + return new Value(array($result->value()), 'array'); + } + + public static function _xmlrpcs_multicall_do_call_phpvals($server, $call) + { + if (!is_array($call)) { + return static::_xmlrpcs_multicall_error('notstruct'); + } + if (!array_key_exists('methodName', $call)) { + return static::_xmlrpcs_multicall_error('nomethod'); + } + if (!is_string($call['methodName'])) { + return static::_xmlrpcs_multicall_error('notstring'); + } + if ($call['methodName'] == 'system.multicall') { + return static::_xmlrpcs_multicall_error('recursion'); + } + if (!array_key_exists('params', $call)) { + return static::_xmlrpcs_multicall_error('noparams'); + } + if (!is_array($call['params'])) { + return static::_xmlrpcs_multicall_error('notarray'); + } + + // this is a real dirty and simplistic hack, since we might have received a + // base64 or datetime values, but they will be listed as strings here... + $numParams = count($call['params']); + $pt = array(); + $wrapper = new Wrapper(); + foreach ($call['params'] as $val) { + $pt[] = $wrapper->php2XmlrpcType(gettype($val)); + } + + $result = $server->execute($call['methodName'], $call['params'], $pt); + + if ($result->faultCode() != 0) { + return static::_xmlrpcs_multicall_error($result); // Method returned fault. + } + + return new Value(array($result->value()), 'array'); + } + + public static function _xmlrpcs_multicall($server, $req) + { + $result = array(); + // let accept a plain list of php parameters, beside a single xmlrpc msg object + if (is_object($req)) { + $calls = $req->getParam(0); + foreach($calls as $call) { + $result[] = static::_xmlrpcs_multicall_do_call($server, $call); + } + } else { + $numCalls = count($req); + for ($i = 0; $i < $numCalls; $i++) { + $result[$i] = static::_xmlrpcs_multicall_do_call_phpvals($server, $req[$i]); + } + } + + return new Response(new Value($result, 'array')); + } + + /** + * Error handler used to track errors that occur during server-side execution of PHP code. + * This allows to report back to the client whether an internal error has occurred or not + * using an xmlrpc response object, instead of letting the client deal with the html junk + * that a PHP execution error on the server generally entails. + * + * NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors. + */ + public static function _xmlrpcs_errorHandler($errCode, $errString, $filename = null, $lineNo = null, $context = null) + { + // obey the @ protocol + if (error_reporting() == 0) { + return; + } + + //if($errCode != E_NOTICE && $errCode != E_WARNING && $errCode != E_USER_NOTICE && $errCode != E_USER_WARNING) + if ($errCode != E_STRICT) { + \PhpXmlRpc\Server::error_occurred($errString); + } + // Try to avoid as much as possible disruption to the previous error handling + // mechanism in place + if (self::$_xmlrpcs_prev_ehandler == '') { + // The previous error handler was the default: all we should do is log error + // to the default error log (if level high enough) + if (ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errCode)) { + error_log($errString); + } + } else { + // Pass control on to previous error handler, trying to avoid loops... + if (self::$_xmlrpcs_prev_ehandler != array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler')) { + if (is_array(self::$_xmlrpcs_prev_ehandler)) { + // the following works both with static class methods and plain object methods as error handler + call_user_func_array(self::$_xmlrpcs_prev_ehandler, array($errCode, $errString, $filename, $lineNo, $context)); + } else { + $method = self::$_xmlrpcs_prev_ehandler; + $method($errCode, $errString, $filename, $lineNo, $context); + } + } + } + } +} diff --git a/lib/phpxmlrpc/src/Value.php b/lib/phpxmlrpc/src/Value.php new file mode 100644 index 0000000..bfdf521 --- /dev/null +++ b/lib/phpxmlrpc/src/Value.php @@ -0,0 +1,599 @@ + 1, + "i8" => 1, + "int" => 1, + "boolean" => 1, + "double" => 1, + "string" => 1, + "dateTime.iso8601" => 1, + "base64" => 1, + "array" => 2, + "struct" => 3, + "null" => 1, + ); + + /// @todo: do these need to be public? + public $me = array(); + public $mytype = 0; + public $_php_class = null; + + /** + * Build an xmlrpc value. + * + * When no value or type is passed in, the value is left uninitialized, and the value can be added later. + * + * @param mixed $val if passing in an array, all array elements should be PhpXmlRpc\Value themselves + * @param string $type any valid xmlrpc type name (lowercase): i4, int, boolean, string, double, dateTime.iso8601, + * base64, array, struct, null. + * If null, 'string' is assumed. + * You should refer to http://www.xmlrpc.com/spec for more information on what each of these mean. + */ + public function __construct($val = -1, $type = '') + { + // optimization creep - do not call addXX, do it all inline. + // downside: booleans will not be coerced anymore + if ($val !== -1 || $type != '') { + switch ($type) { + case '': + $this->mytype = 1; + $this->me['string'] = $val; + break; + case 'i4': + case 'i8': + case 'int': + case 'double': + case 'string': + case 'boolean': + case 'dateTime.iso8601': + case 'base64': + case 'null': + $this->mytype = 1; + $this->me[$type] = $val; + break; + case 'array': + $this->mytype = 2; + $this->me['array'] = $val; + break; + case 'struct': + $this->mytype = 3; + $this->me['struct'] = $val; + break; + default: + error_log("XML-RPC: " . __METHOD__ . ": not a known type ($type)"); + } + } + } + + /** + * Add a single php value to an xmlrpc value. + * + * If the xmlrpc value is an array, the php value is added as its last element. + * If the xmlrpc value is empty (uninitialized), this method makes it a scalar value, and sets that value. + * Fails if the xmlrpc value is not an array and already initialized. + * + * @param mixed $val + * @param string $type allowed values: i4, i8, int, boolean, string, double, dateTime.iso8601, base64, null. + * + * @return int 1 or 0 on failure + */ + public function addScalar($val, $type = 'string') + { + $typeOf = null; + if (isset(static::$xmlrpcTypes[$type])) { + $typeOf = static::$xmlrpcTypes[$type]; + } + + if ($typeOf !== 1) { + error_log("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)"); + return 0; + } + + // coerce booleans into correct values + // NB: we should either do it for datetimes, integers, i8 and doubles, too, + // or just plain remove this check, implemented on booleans only... + if ($type == static::$xmlrpcBoolean) { + if (strcasecmp($val, 'true') == 0 || $val == 1 || ($val == true && strcasecmp($val, 'false'))) { + $val = true; + } else { + $val = false; + } + } + + switch ($this->mytype) { + case 1: + error_log('XML-RPC: ' . __METHOD__ . ': scalar xmlrpc value can have only one value'); + return 0; + case 3: + error_log('XML-RPC: ' . __METHOD__ . ': cannot add anonymous scalar to struct xmlrpc value'); + return 0; + case 2: + // we're adding a scalar value to an array here + $this->me['array'][] = new Value($val, $type); + + return 1; + default: + // a scalar, so set the value and remember we're scalar + $this->me[$type] = $val; + $this->mytype = $typeOf; + + return 1; + } + } + + /** + * Add an array of xmlrpc value objects to an xmlrpc value. + * + * If the xmlrpc value is an array, the elements are appended to the existing ones. + * If the xmlrpc value is empty (uninitialized), this method makes it an array value, and sets that value. + * Fails otherwise. + * + * @param Value[] $values + * + * @return int 1 or 0 on failure + * + * @todo add some checking for $values to be an array of xmlrpc values? + */ + public function addArray($values) + { + if ($this->mytype == 0) { + $this->mytype = static::$xmlrpcTypes['array']; + $this->me['array'] = $values; + + return 1; + } elseif ($this->mytype == 2) { + // we're adding to an array here + $this->me['array'] = array_merge($this->me['array'], $values); + + return 1; + } else { + error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']'); + return 0; + } + } + + /** + * Merges an array of named xmlrpc value objects into an xmlrpc value. + * + * If the xmlrpc value is a struct, the elements are merged with the existing ones (overwriting existing ones). + * If the xmlrpc value is empty (uninitialized), this method makes it a struct value, and sets that value. + * Fails otherwise. + * + * @param Value[] $values + * + * @return int 1 or 0 on failure + * + * @todo add some checking for $values to be an array? + */ + public function addStruct($values) + { + if ($this->mytype == 0) { + $this->mytype = static::$xmlrpcTypes['struct']; + $this->me['struct'] = $values; + + return 1; + } elseif ($this->mytype == 3) { + // we're adding to a struct here + $this->me['struct'] = array_merge($this->me['struct'], $values); + + return 1; + } else { + error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']'); + return 0; + } + } + + /** + * Returns a string containing either "struct", "array", "scalar" or "undef", describing the base type of the value. + * + * @return string + */ + public function kindOf() + { + switch ($this->mytype) { + case 3: + return 'struct'; + break; + case 2: + return 'array'; + break; + case 1: + return 'scalar'; + break; + default: + return 'undef'; + } + } + + protected function serializedata($typ, $val, $charsetEncoding = '') + { + $rs = ''; + + if (!isset(static::$xmlrpcTypes[$typ])) { + return $rs; + } + + switch (static::$xmlrpcTypes[$typ]) { + case 1: + switch ($typ) { + case static::$xmlrpcBase64: + $rs .= "<${typ}>" . base64_encode($val) . ""; + break; + case static::$xmlrpcBoolean: + $rs .= "<${typ}>" . ($val ? '1' : '0') . ""; + break; + case static::$xmlrpcString: + // G. Giunta 2005/2/13: do NOT use htmlentities, since + // it will produce named html entities, which are invalid xml + $rs .= "<${typ}>" . Charset::instance()->encodeEntities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . ""; + break; + case static::$xmlrpcInt: + case static::$xmlrpcI4: + case static::$xmlrpcI8: + $rs .= "<${typ}>" . (int)$val . ""; + break; + case static::$xmlrpcDouble: + // avoid using standard conversion of float to string because it is locale-dependent, + // and also because the xmlrpc spec forbids exponential notation. + // sprintf('%F') could be most likely ok but it fails eg. on 2e-14. + // The code below tries its best at keeping max precision while avoiding exp notation, + // but there is of course no limit in the number of decimal places to be used... + $rs .= "<${typ}>" . preg_replace('/\\.?0+$/', '', number_format((double)$val, 128, '.', '')) . ""; + break; + case static::$xmlrpcDateTime: + if (is_string($val)) { + $rs .= "<${typ}>${val}"; + } elseif (is_a($val, 'DateTime')) { + $rs .= "<${typ}>" . $val->format('Ymd\TH:i:s') . ""; + } elseif (is_int($val)) { + $rs .= "<${typ}>" . strftime("%Y%m%dT%H:%M:%S", $val) . ""; + } else { + // not really a good idea here: but what shall we output anyway? left for backward compat... + $rs .= "<${typ}>${val}"; + } + break; + case static::$xmlrpcNull: + if (PhpXmlRpc::$xmlrpc_null_apache_encoding) { + $rs .= ""; + } else { + $rs .= ""; + } + break; + default: + // no standard type value should arrive here, but provide a possibility + // for xmlrpc values of unknown type... + $rs .= "<${typ}>${val}"; + } + break; + case 3: + // struct + if ($this->_php_class) { + $rs .= '\n"; + } else { + $rs .= "\n"; + } + $charsetEncoder = Charset::instance(); + foreach ($val as $key2 => $val2) { + $rs .= '' . $charsetEncoder->encodeEntities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "\n"; + //$rs.=$this->serializeval($val2); + $rs .= $val2->serialize($charsetEncoding); + $rs .= "\n"; + } + $rs .= ''; + break; + case 2: + // array + $rs .= "\n\n"; + foreach ($val as $element) { + //$rs.=$this->serializeval($val[$i]); + $rs .= $element->serialize($charsetEncoding); + } + $rs .= "\n"; + break; + default: + break; + } + + return $rs; + } + + /** + * Returns the xml representation of the value. XML prologue not included. + * + * @param string $charsetEncoding the charset to be used for serialization. if null, US-ASCII is assumed + * + * @return string + */ + public function serialize($charsetEncoding = '') + { + reset($this->me); + list($typ, $val) = $this->each($this->me); + + return '' . $this->serializedata($typ, $val, $charsetEncoding) . "\n"; + } + public function each(&$array) + { + $res = array(); + $key = key($array); + if($key !== null){ + next($array); + $res[1] = $res['value'] = $array[$key]; + $res[0] = $res['key'] = $key; + }else{ + $res = false; + } + return $res; + } + + /** + * Checks whether a struct member with a given name is present. + * + * Works only on xmlrpc values of type struct. + * + * @param string $key the name of the struct member to be looked up + * + * @return boolean + * + * @deprecated use array access, e.g. isset($val[$key]) + */ + public function structmemexists($key) + { + return array_key_exists($key, $this->me['struct']); + } + + /** + * Returns the value of a given struct member (an xmlrpc value object in itself). + * Will raise a php warning if struct member of given name does not exist. + * + * @param string $key the name of the struct member to be looked up + * + * @return Value + * + * @deprecated use array access, e.g. $val[$key] + */ + public function structmem($key) + { + return $this->me['struct'][$key]; + } + + /** + * Reset internal pointer for xmlrpc values of type struct. + * @deprecated iterate directly over the object using foreach instead + */ + public function structreset() + { + reset($this->me['struct']); + } + + /** + * Return next member element for xmlrpc values of type struct. + * + * @return Value + * + * @deprecated iterate directly over the object using foreach instead + */ + public function structeach() + { + return $this->each($this->me['struct']); + } + + /** + * Returns the value of a scalar xmlrpc value (base 64 decoding is automatically handled here) + * + * @return mixed + */ + public function scalarval() + { + reset($this->me); + list(, $b) = $this->each($this->me); + + return $b; + } + + /** + * Returns the type of the xmlrpc value. + * + * For integers, 'int' is always returned in place of 'i4'. 'i8' is considered a separate type and returned as such + * + * @return string + */ + public function scalartyp() + { + reset($this->me); + list($a,) = $this->each($this->me); + if ($a == static::$xmlrpcI4) { + $a = static::$xmlrpcInt; + } + + return $a; + } + + /** + * Returns the m-th member of an xmlrpc value of array type. + * + * @param integer $key the index of the value to be retrieved (zero based) + * + * @return Value + * + * @deprecated use array access, e.g. $val[$key] + */ + public function arraymem($key) + { + return $this->me['array'][$key]; + } + + /** + * Returns the number of members in an xmlrpc value of array type. + * + * @return integer + * + * @deprecated use count() instead + */ + public function arraysize() + { + return count($this->me['array']); + } + + /** + * Returns the number of members in an xmlrpc value of struct type. + * + * @return integer + * + * @deprecated use count() instead + */ + public function structsize() + { + return count($this->me['struct']); + } + + /** + * Returns the number of members in an xmlrpc value: + * - 0 for uninitialized values + * - 1 for scalar values + * - the number of elements for struct and array values + * + * @return integer + */ + public function count() + { + switch ($this->mytype) { + case 3: + return count($this->me['struct']); + case 2: + return count($this->me['array']); + case 1: + return 1; + default: + return 0; + } + } + + /** + * Implements the IteratorAggregate interface + * + * @return ArrayIterator + */ + public function getIterator() { + switch ($this->mytype) { + case 3: + return new \ArrayIterator($this->me['struct']); + case 2: + return new \ArrayIterator($this->me['array']); + case 1: + return new \ArrayIterator($this->me); + default: + return new \ArrayIterator(); + } + return new \ArrayIterator(); + } + + public function offsetSet($offset, $value) { + + switch ($this->mytype) { + case 3: + if (!($value instanceof \PhpXmlRpc\Value)) { + throw new \Exception('It is only possible to add Value objects to an XML-RPC Struct'); + } + if (is_null($offset)) { + // disallow struct members with empty names + throw new \Exception('It is not possible to add anonymous members to an XML-RPC Struct'); + } else { + $this->me['struct'][$offset] = $value; + } + return; + case 2: + if (!($value instanceof \PhpXmlRpc\Value)) { + throw new \Exception('It is only possible to add Value objects to an XML-RPC Array'); + } + if (is_null($offset)) { + $this->me['array'][] = $value; + } else { + // nb: we are not checking that $offset is above the existing array range... + $this->me['array'][$offset] = $value; + } + return; + case 1: +// todo: handle i4 vs int + reset($this->me); + list($type,) = $this->each($this->me); + if ($type != $offset) { + throw new \Exception(''); + } + $this->me[$type] = $value; + return; + default: + // it would be nice to allow empty values to be be turned into non-empty ones this way, but we miss info to do so + throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be set using array index"); + } + } + + public function offsetExists($offset) { + switch ($this->mytype) { + case 3: + return isset($this->me['struct'][$offset]); + case 2: + return isset($this->me['array'][$offset]); + case 1: +// todo: handle i4 vs int + return $offset == $this->scalartyp(); + default: + return false; + } + } + + public function offsetUnset($offset) { + switch ($this->mytype) { + case 3: + unset($this->me['struct'][$offset]); + return; + case 2: + unset($this->me['array'][$offset]); + return; + case 1: + // can not remove value from a scalar + throw new \Exception("XML-RPC Value is of type 'scalar' and its value can not be unset using array index"); + default: + throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be unset using array index"); + } + } + + public function offsetGet($offset) { + switch ($this->mytype) { + case 3: + return isset($this->me['struct'][$offset]) ? $this->me['struct'][$offset] : null; + case 2: + return isset($this->me['array'][$offset]) ? $this->me['array'][$offset] : null; + case 1: +// on bad type: null or exception? + reset($this->me); + list($type, $value) = $this->each($this->me); + return $type == $offset ? $value : null; + default: +// return null or exception? + throw new \Exception("XML-RPC Value is of type 'undef' and can not be accessed using array index"); + } + } +} diff --git a/lib/phpxmlrpc/src/Wrapper.php b/lib/phpxmlrpc/src/Wrapper.php new file mode 100644 index 0000000..ce12d9a --- /dev/null +++ b/lib/phpxmlrpc/src/Wrapper.php @@ -0,0 +1,1114 @@ +' . $callable[1]; + } + $exists = method_exists($callable[0], $callable[1]); + } else if ($callable instanceof \Closure) { + // we do not support creating code which wraps closures, as php does not allow to serialize them + if (!$buildIt) { + error_log('XML-RPC: ' . __METHOD__ . ': a closure can not be wrapped in generated source code'); + return false; + } + + $plainFuncName = 'Closure'; + $exists = true; + } else { + $plainFuncName = $callable; + $exists = function_exists($callable); + } + + if (!$exists) { + error_log('XML-RPC: ' . __METHOD__ . ': function to be wrapped is not defined: ' . $plainFuncName); + return false; + } + + $funcDesc = $this->introspectFunction($callable, $plainFuncName); + if (!$funcDesc) { + return false; + } + + $funcSigs = $this->buildMethodSignatures($funcDesc); + + if ($buildIt) { + $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc); + } else { + $newFuncName = $this->newFunctionName($callable, $newFuncName, $extraOptions); + $code = $this->buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc); + } + + $ret = array( + 'function' => $callable, + 'signature' => $funcSigs['sigs'], + 'docstring' => $funcDesc['desc'], + 'signature_docs' => $funcSigs['sigsDocs'], + ); + if (!$buildIt) { + $ret['function'] = $newFuncName; + $ret['source'] = $code; + } + return $ret; + } + + /** + * Introspect a php callable and its phpdoc block and extract information about its signature + * + * @param callable $callable + * @param string $plainFuncName + * @return array|false + */ + protected function introspectFunction($callable, $plainFuncName) + { + // start to introspect PHP code + if (is_array($callable)) { + $func = new \ReflectionMethod($callable[0], $callable[1]); + if ($func->isPrivate()) { + error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is private: ' . $plainFuncName); + return false; + } + if ($func->isProtected()) { + error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is protected: ' . $plainFuncName); + return false; + } + if ($func->isConstructor()) { + error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the constructor: ' . $plainFuncName); + return false; + } + if ($func->isDestructor()) { + error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the destructor: ' . $plainFuncName); + return false; + } + if ($func->isAbstract()) { + error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is abstract: ' . $plainFuncName); + return false; + } + /// @todo add more checks for static vs. nonstatic? + } else { + $func = new \ReflectionFunction($callable); + } + if ($func->isInternal()) { + // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs + // instead of getparameters to fully reflect internal php functions ? + error_log('XML-RPC: ' . __METHOD__ . ': function to be wrapped is internal: ' . $plainFuncName); + return false; + } + + // retrieve parameter names, types and description from javadoc comments + + // function description + $desc = ''; + // type of return val: by default 'any' + $returns = Value::$xmlrpcValue; + // desc of return val + $returnsDocs = ''; + // type + name of function parameters + $paramDocs = array(); + + $docs = $func->getDocComment(); + if ($docs != '') { + $docs = explode("\n", $docs); + $i = 0; + foreach ($docs as $doc) { + $doc = trim($doc, " \r\t/*"); + if (strlen($doc) && strpos($doc, '@') !== 0 && !$i) { + if ($desc) { + $desc .= "\n"; + } + $desc .= $doc; + } elseif (strpos($doc, '@param') === 0) { + // syntax: @param type $name [desc] + if (preg_match('/@param\s+(\S+)\s+(\$\S+)\s*(.+)?/', $doc, $matches)) { + $name = strtolower(trim($matches[2])); + //$paramDocs[$name]['name'] = trim($matches[2]); + $paramDocs[$name]['doc'] = isset($matches[3]) ? $matches[3] : ''; + $paramDocs[$name]['type'] = $matches[1]; + } + $i++; + } elseif (strpos($doc, '@return') === 0) { + // syntax: @return type [desc] + if (preg_match('/@return\s+(\S+)(\s+.+)?/', $doc, $matches)) { + $returns = $matches[1]; + if (isset($matches[2])) { + $returnsDocs = trim($matches[2]); + } + } + } + } + } + + // execute introspection of actual function prototype + $params = array(); + $i = 0; + foreach ($func->getParameters() as $paramObj) { + $params[$i] = array(); + $params[$i]['name'] = '$' . $paramObj->getName(); + $params[$i]['isoptional'] = $paramObj->isOptional(); + $i++; + } + + return array( + 'desc' => $desc, + 'docs' => $docs, + 'params' => $params, // array, positionally indexed + 'paramDocs' => $paramDocs, // array, indexed by name + 'returns' => $returns, + 'returnsDocs' =>$returnsDocs, + ); + } + + /** + * Given the method description given by introspection, create method signature data + * + * @todo support better docs with multiple types separated by pipes by creating multiple signatures + * (this is questionable, as it might produce a big matrix of possible signatures with many such occurrences) + * + * @param array $funcDesc as generated by self::introspectFunction() + * + * @return array + */ + protected function buildMethodSignatures($funcDesc) + { + $i = 0; + $parsVariations = array(); + $pars = array(); + $pNum = count($funcDesc['params']); + foreach ($funcDesc['params'] as $param) { + /* // match by name real param and documented params + $name = strtolower($param['name']); + if (!isset($funcDesc['paramDocs'][$name])) { + $funcDesc['paramDocs'][$name] = array(); + } + if (!isset($funcDesc['paramDocs'][$name]['type'])) { + $funcDesc['paramDocs'][$name]['type'] = 'mixed'; + }*/ + + if ($param['isoptional']) { + // this particular parameter is optional. save as valid previous list of parameters + $parsVariations[] = $pars; + } + + $pars[] = "\$p$i"; + $i++; + if ($i == $pNum) { + // last allowed parameters combination + $parsVariations[] = $pars; + } + } + + if (count($parsVariations) == 0) { + // only known good synopsis = no parameters + $parsVariations[] = array(); + } + + $sigs = array(); + $sigsDocs = array(); + foreach ($parsVariations as $pars) { + // build a signature + $sig = array($this->php2XmlrpcType($funcDesc['returns'])); + $pSig = array($funcDesc['returnsDocs']); + for ($i = 0; $i < count($pars); $i++) { + $name = strtolower($funcDesc['params'][$i]['name']); + if (isset($funcDesc['paramDocs'][$name]['type'])) { + $sig[] = $this->php2XmlrpcType($funcDesc['paramDocs'][$name]['type']); + } else { + $sig[] = Value::$xmlrpcValue; + } + $pSig[] = isset($funcDesc['paramDocs'][$name]['doc']) ? $funcDesc['paramDocs'][$name]['doc'] : ''; + } + $sigs[] = $sig; + $sigsDocs[] = $pSig; + } + + return array( + 'sigs' => $sigs, + 'sigsDocs' => $sigsDocs + ); + } + + /** + * Creates a closure that will execute $callable + * @todo validate params? In theory all validation is left to the dispatch map... + * @todo add support for $catchWarnings + * + * @param $callable + * @param array $extraOptions + * @param string $plainFuncName + * @param string $funcDesc + * @return \Closure + */ + protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc) + { + $function = function($req) use($callable, $extraOptions, $funcDesc) + { + $nameSpace = '\\PhpXmlRpc\\'; + $encoderClass = $nameSpace.'Encoder'; + $responseClass = $nameSpace.'Response'; + $valueClass = $nameSpace.'Value'; + + // validate number of parameters received + // this should be optional really, as we assume the server does the validation + $minPars = count($funcDesc['params']); + $maxPars = $minPars; + foreach ($funcDesc['params'] as $i => $param) { + if ($param['isoptional']) { + // this particular parameter is optional. We assume later ones are as well + $minPars = $i; + break; + } + } + $numPars = $req->getNumParams(); + if ($numPars < $minPars || $numPars > $maxPars) { + return new $responseClass(0, 3, 'Incorrect parameters passed to method'); + } + + $encoder = new $encoderClass(); + $options = array(); + if (isset($extraOptions['decode_php_objs']) && $extraOptions['decode_php_objs']) { + $options[] = 'decode_php_objs'; + } + $params = $encoder->decode($req, $options); + + $result = call_user_func_array($callable, $params); + + if (! is_a($result, $responseClass)) { + if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) { + $result = new $valueClass($result, $funcDesc['returns']); + } else { + $options = array(); + if (isset($extraOptions['encode_php_objs']) && $extraOptions['encode_php_objs']) { + $options[] = 'encode_php_objs'; + } + + $result = $encoder->encode($result, $options); + } + $result = new $responseClass($result); + } + + return $result; + }; + + return $function; + } + + /** + * Return a name for a new function, based on $callable, insuring its uniqueness + * @param mixed $callable a php callable, or the name of an xmlrpc method + * @param string $newFuncName when not empty, it is used instead of the calculated version + * @return string + */ + protected function newFunctionName($callable, $newFuncName, $extraOptions) + { + // determine name of new php function + + $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc'; + + if ($newFuncName == '') { + if (is_array($callable)) { + if (is_string($callable[0])) { + $xmlrpcFuncName = "{$prefix}_" . implode('_', $callable); + } else { + $xmlrpcFuncName = "{$prefix}_" . get_class($callable[0]) . '_' . $callable[1]; + } + } else { + if ($callable instanceof \Closure) { + $xmlrpcFuncName = "{$prefix}_closure"; + } else { + $callable = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'), + array('_', ''), $callable); + $xmlrpcFuncName = "{$prefix}_$callable"; + } + } + } else { + $xmlrpcFuncName = $newFuncName; + } + + while (function_exists($xmlrpcFuncName)) { + $xmlrpcFuncName .= 'x'; + } + + return $xmlrpcFuncName; + } + + /** + * @param $callable + * @param string $newFuncName + * @param array $extraOptions + * @param string $plainFuncName + * @param array $funcDesc + * @return string + * + * @todo add a nice phpdoc block in the generated source + */ + protected function buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc) + { + $namespace = '\\PhpXmlRpc\\'; + + $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false; + $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; + $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : ''; + + $i = 0; + $parsVariations = array(); + $pars = array(); + $pNum = count($funcDesc['params']); + foreach ($funcDesc['params'] as $param) { + + if ($param['isoptional']) { + // this particular parameter is optional. save as valid previous list of parameters + $parsVariations[] = $pars; + } + + $pars[] = "\$p[$i]"; + $i++; + if ($i == $pNum) { + // last allowed parameters combination + $parsVariations[] = $pars; + } + } + + if (count($parsVariations) == 0) { + // only known good synopsis = no parameters + $parsVariations[] = array(); + $minPars = 0; + $maxPars = 0; + } else { + $minPars = count($parsVariations[0]); + $maxPars = count($parsVariations[count($parsVariations)-1]); + } + + // build body of new function + + $innerCode = "\$paramCount = \$req->getNumParams();\n"; + $innerCode .= "if (\$paramCount < $minPars || \$paramCount > $maxPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "');\n"; + + $innerCode .= "\$encoder = new {$namespace}Encoder();\n"; + if ($decodePhpObjects) { + $innerCode .= "\$p = \$encoder->decode(\$req, array('decode_php_objs'));\n"; + } else { + $innerCode .= "\$p = \$encoder->decode(\$req);\n"; + } + + // since we are building source code for later use, if we are given an object instance, + // we go out of our way and store a pointer to it in a static class var var... + if (is_array($callable) && is_object($callable[0])) { + self::$objHolder[$newFuncName] = $callable[0]; + $innerCode .= "\$obj = PhpXmlRpc\\Wrapper::\$objHolder['$newFuncName'];\n"; + $realFuncName = '$obj->' . $callable[1]; + } else { + $realFuncName = $plainFuncName; + } + foreach ($parsVariations as $i => $pars) { + $innerCode .= "if (\$paramCount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . ");\n"; + if ($i < (count($parsVariations) - 1)) + $innerCode .= "else\n"; + } + $innerCode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n"; + if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) { + $innerCode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '{$funcDesc['returns']}'));"; + } else { + if ($encodePhpObjects) { + $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n"; + } else { + $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n"; + } + } + // shall we exclude functions returning by ref? + // if($func->returnsReference()) + // return false; + + $code = "function $newFuncName(\$req) {\n" . $innerCode . "\n}"; + + return $code; + } + + /** + * Given a user-defined PHP class or php object, map its methods onto a list of + * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server + * object and called from remote clients (as well as their corresponding signature info). + * + * @param string|object $className the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class + * @param array $extraOptions see the docs for wrapPhpMethod for basic options, plus + * - string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on whether $className is a class name or object instance + * - string method_filter a regexp used to filter methods to wrap based on their names + * - string prefix used for the names of the xmlrpc methods created + * + * @return array|false false on failure + */ + public function wrapPhpClass($className, $extraOptions = array()) + { + $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : ''; + $methodType = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto'; + $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : ''; + + $results = array(); + $mList = get_class_methods($className); + foreach ($mList as $mName) { + if ($methodFilter == '' || preg_match($methodFilter, $mName)) { + $func = new \ReflectionMethod($className, $mName); + if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) { + if (($func->isStatic() && ($methodType == 'all' || $methodType == 'static' || ($methodType == 'auto' && is_string($className)))) || + (!$func->isStatic() && ($methodType == 'all' || $methodType == 'nonstatic' || ($methodType == 'auto' && is_object($className)))) + ) { + $methodWrap = $this->wrapPhpFunction(array($className, $mName), '', $extraOptions); + if ($methodWrap) { + if (is_object($className)) { + $realClassName = get_class($className); + }else { + $realClassName = $className; + } + $results[$prefix."$realClassName.$mName"] = $methodWrap; + } + } + } + } + } + + return $results; + } + + /** + * Given an xmlrpc client and a method name, register a php wrapper function + * that will call it and return results using native php types for both + * params and results. The generated php function will return a Response + * object for failed xmlrpc calls. + * + * Known limitations: + * - server must support system.methodsignature for the wanted xmlrpc method + * - for methods that expose many signatures, only one can be picked (we + * could in principle check if signatures differ only by number of params + * and not by type, but it would be more complication than we can spare time) + * - nested xmlrpc params: the caller of the generated php function has to + * encode on its own the params passed to the php function if these are structs + * or arrays whose (sub)members include values of type datetime or base64 + * + * Notes: the connection properties of the given client will be copied + * and reused for the connection used during the call to the generated + * php function. + * Calling the generated php function 'might' be slow: a new xmlrpc client + * is created on every invocation and an xmlrpc-connection opened+closed. + * An extra 'debug' param is appended to param list of xmlrpc method, useful + * for debugging purposes. + * + * @todo allow caller to give us the method signature instead of querying for it, or just say 'skip it' + * @todo if we can not retrieve method signature, create a php function with varargs + * @todo allow the created function to throw exceptions on method calls failures + * @todo if caller did not specify a specific sig, shall we support all of them? + * It might be hard (hence slow) to match based on type and number of arguments... + * + * @param Client $client an xmlrpc client set up correctly to communicate with target server + * @param string $methodName the xmlrpc method to be mapped to a php function + * @param array $extraOptions array of options that specify conversion details. Valid options include + * - integer signum the index of the method signature to use in mapping (if method exposes many sigs) + * - integer timeout timeout (in secs) to be used when executing function/calling remote method + * - string protocol 'http' (default), 'http11' or 'https' + * - string new_function_name the name of php function to create, when return_source is used. If unspecified, lib will pick an appropriate name + * - string return_source if true return php code w. function definition instead of function itself (closure) + * - bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects + * - bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers --- + * - mixed return_on_fault a php value to be returned when the xmlrpc call fails/returns a fault response (by default the Response object is returned in this case). If a string is used, '%faultCode%' and '%faultString%' tokens will be substituted with actual error values + * - bool debug set it to 1 or 2 to see debug results of querying server for method synopsis + * - int simple_client_copy set it to 1 to have a lightweight copy of the $client object made in the generated code (only used when return_source = true) + * + * @return \closure|array|false false on failure, closure by default and array for return_source = true + */ + public function wrapXmlrpcMethod($client, $methodName, $extraOptions = array()) + { + $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : ''; + + $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true; + + $mSig = $this->retrieveMethodSignature($client, $methodName, $extraOptions); + if (!$mSig) { + return false; + } + + if ($buildIt) { + return $this->buildWrapMethodClosure($client, $methodName, $extraOptions, $mSig); + } else { + // if in 'offline' mode, retrieve method description too. + // in online mode, favour speed of operation + $mDesc = $this->retrieveMethodHelp($client, $methodName, $extraOptions); + + $newFuncName = $this->newFunctionName($methodName, $newFuncName, $extraOptions); + + $results = $this->buildWrapMethodSource($client, $methodName, $extraOptions, $newFuncName, $mSig, $mDesc); + /* was: $results = $this->build_remote_method_wrapper_code($client, $methodName, + $newFuncName, $mSig, $mDesc, $timeout, $protocol, $simpleClientCopy, + $prefix, $decodePhpObjects, $encodePhpObjects, $decodeFault, + $faultResponse, $namespace);*/ + + $results['function'] = $newFuncName; + + return $results; + } + + } + + /** + * Retrieves an xmlrpc method signature from a server which supports system.methodSignature + * @param Client $client + * @param string $methodName + * @param array $extraOptions + * @return false|array + */ + protected function retrieveMethodSignature($client, $methodName, array $extraOptions = array()) + { + $namespace = '\\PhpXmlRpc\\'; + $reqClass = $namespace . 'Request'; + $valClass = $namespace . 'Value'; + $decoderClass = $namespace . 'Encoder'; + + $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0; + $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; + $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; + $sigNum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0; + + $req = new $reqClass('system.methodSignature'); + $req->addparam(new $valClass($methodName)); + $client->setDebug($debug); + $response = $client->send($req, $timeout, $protocol); + if ($response->faultCode()) { + error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature from remote server for method ' . $methodName); + return false; + } + + $mSig = $response->value(); + if ($client->return_type != 'phpvals') { + $decoder = new $decoderClass(); + $mSig = $decoder->decode($mSig); + } + + if (!is_array($mSig) || count($mSig) <= $sigNum) { + error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature nr.' . $sigNum . ' from remote server for method ' . $methodName); + return false; + } + + return $mSig[$sigNum]; + } + + /** + * @param Client $client + * @param string $methodName + * @param array $extraOptions + * @return string in case of any error, an empty string is returned, no warnings generated + */ + protected function retrieveMethodHelp($client, $methodName, array $extraOptions = array()) + { + $namespace = '\\PhpXmlRpc\\'; + $reqClass = $namespace . 'Request'; + $valClass = $namespace . 'Value'; + + $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0; + $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; + $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; + + $mDesc = ''; + + $req = new $reqClass('system.methodHelp'); + $req->addparam(new $valClass($methodName)); + $client->setDebug($debug); + $response = $client->send($req, $timeout, $protocol); + if (!$response->faultCode()) { + $mDesc = $response->value(); + if ($client->return_type != 'phpvals') { + $mDesc = $mDesc->scalarval(); + } + } + + return $mDesc; + } + + /** + * @param Client $client + * @param string $methodName + * @param array $extraOptions + * @param string $mSig + * @return \Closure + * + * @todo should we allow usage of parameter simple_client_copy to mean 'do not clone' in this case? + */ + protected function buildWrapMethodClosure($client, $methodName, array $extraOptions, $mSig) + { + // we clone the client, so that we can modify it a bit independently of the original + $clientClone = clone $client; + $function = function() use($clientClone, $methodName, $extraOptions, $mSig) + { + $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; + $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; + $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false; + $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; + if (isset($extraOptions['return_on_fault'])) { + $decodeFault = true; + $faultResponse = $extraOptions['return_on_fault']; + } else { + $decodeFault = false; + } + + $namespace = '\\PhpXmlRpc\\'; + $reqClass = $namespace . 'Request'; + $encoderClass = $namespace . 'Encoder'; + $valueClass = $namespace . 'Value'; + + $encoder = new $encoderClass(); + $encodeOptions = array(); + if ($encodePhpObjects) { + $encodeOptions[] = 'encode_php_objs'; + } + $decodeOptions = array(); + if ($decodePhpObjects) { + $decodeOptions[] = 'decode_php_objs'; + } + + /// @todo check for insufficient nr. of args besides excess ones? note that 'source' version does not... + + // support one extra parameter: debug + $maxArgs = count($mSig)-1; // 1st element is the return type + $currentArgs = func_get_args(); + if (func_num_args() == ($maxArgs+1)) { + $debug = array_pop($currentArgs); + $clientClone->setDebug($debug); + } + + $xmlrpcArgs = array(); + foreach($currentArgs as $i => $arg) { + if ($i == $maxArgs) { + break; + } + $pType = $mSig[$i+1]; + if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' || + $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null' + ) { + // by building directly xmlrpc values when type is known and scalar (instead of encode() calls), + // we make sure to honour the xmlrpc signature + $xmlrpcArgs[] = new $valueClass($arg, $pType); + } else { + $xmlrpcArgs[] = $encoder->encode($arg, $encodeOptions); + } + } + + $req = new $reqClass($methodName, $xmlrpcArgs); + // use this to get the maximum decoding flexibility + $clientClone->return_type = 'xmlrpcvals'; + $resp = $clientClone->send($req, $timeout, $protocol); + if ($resp->faultcode()) { + if ($decodeFault) { + if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) || + (strpos($faultResponse, '%faultString%') !== false))) { + $faultResponse = str_replace(array('%faultCode%', '%faultString%'), + array($resp->faultCode(), $resp->faultString()), $faultResponse); + } + return $faultResponse; + } else { + return $resp; + } + } else { + return $encoder->decode($resp->value(), $decodeOptions); + } + }; + + return $function; + } + + /** + * @param Client $client + * @param string $methodName + * @param array $extraOptions + * @param string $newFuncName + * @param array $mSig + * @param string $mDesc + * @return array + */ + public function buildWrapMethodSource($client, $methodName, array $extraOptions, $newFuncName, $mSig, $mDesc='') + { + $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; + $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; + $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false; + $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; + $clientCopyMode = isset($extraOptions['simple_client_copy']) ? (int)($extraOptions['simple_client_copy']) : 0; + $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc'; + if (isset($extraOptions['return_on_fault'])) { + $decodeFault = true; + $faultResponse = $extraOptions['return_on_fault']; + } else { + $decodeFault = false; + $faultResponse = ''; + } + + $namespace = '\\PhpXmlRpc\\'; + + $code = "function $newFuncName ("; + if ($clientCopyMode < 2) { + // client copy mode 0 or 1 == full / partial client copy in emitted code + $verbatimClientCopy = !$clientCopyMode; + $innerCode = $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace); + $innerCode .= "\$client->setDebug(\$debug);\n"; + $this_ = ''; + } else { + // client copy mode 2 == no client copy in emitted code + $innerCode = ''; + $this_ = 'this->'; + } + $innerCode .= "\$req = new {$namespace}Request('$methodName');\n"; + + if ($mDesc != '') { + // take care that PHP comment is not terminated unwillingly by method description + $mDesc = "/**\n* " . str_replace('*/', '* /', $mDesc) . "\n"; + } else { + $mDesc = "/**\nFunction $newFuncName\n"; + } + + // param parsing + $innerCode .= "\$encoder = new {$namespace}Encoder();\n"; + $plist = array(); + $pCount = count($mSig); + for ($i = 1; $i < $pCount; $i++) { + $plist[] = "\$p$i"; + $pType = $mSig[$i]; + if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' || + $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null' + ) { + // only build directly xmlrpc values when type is known and scalar + $innerCode .= "\$p$i = new {$namespace}Value(\$p$i, '$pType');\n"; + } else { + if ($encodePhpObjects) { + $innerCode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n"; + } else { + $innerCode .= "\$p$i = \$encoder->encode(\$p$i);\n"; + } + } + $innerCode .= "\$req->addparam(\$p$i);\n"; + $mDesc .= '* @param ' . $this->xmlrpc2PhpType($pType) . " \$p$i\n"; + } + if ($clientCopyMode < 2) { + $plist[] = '$debug=0'; + $mDesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n"; + } + $plist = implode(', ', $plist); + $mDesc .= '* @return ' . $this->xmlrpc2PhpType($mSig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n"; + + $innerCode .= "\$res = \${$this_}client->send(\$req, $timeout, '$protocol');\n"; + if ($decodeFault) { + if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) || (strpos($faultResponse, '%faultString%') !== false))) { + $respCode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $faultResponse) . "')"; + } else { + $respCode = var_export($faultResponse, true); + } + } else { + $respCode = '$res'; + } + if ($decodePhpObjects) { + $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));"; + } else { + $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value());"; + } + + $code = $code . $plist . ") {\n" . $innerCode . "\n}\n"; + + return array('source' => $code, 'docstring' => $mDesc); + } + + /** + * Similar to wrapXmlrpcMethod, but will generate a php class that wraps + * all xmlrpc methods exposed by the remote server as own methods. + * For more details see wrapXmlrpcMethod. + * + * For a slimmer alternative, see the code in demo/client/proxy.php + * + * Note that unlike wrapXmlrpcMethod, we always have to generate php code here. It seems that php 7 will have anon classes... + * + * @param Client $client the client obj all set to query the desired server + * @param array $extraOptions list of options for wrapped code. See the ones from wrapXmlrpcMethod plus + * - string method_filter regular expression + * - string new_class_name + * - string prefix + * - bool simple_client_copy set it to true to avoid copying all properties of $client into the copy made in the new class + * + * @return mixed false on error, the name of the created class if all ok or an array with code, class name and comments (if the appropriatevoption is set in extra_options) + */ + public function wrapXmlrpcServer($client, $extraOptions = array()) + { + $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : ''; + $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; + $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; + $newClassName = isset($extraOptions['new_class_name']) ? $extraOptions['new_class_name'] : ''; + $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false; + $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; + $verbatimClientCopy = isset($extraOptions['simple_client_copy']) ? !($extraOptions['simple_client_copy']) : true; + $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true; + $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc'; + $namespace = '\\PhpXmlRpc\\'; + + $reqClass = $namespace . 'Request'; + $decoderClass = $namespace . 'Encoder'; + + $req = new $reqClass('system.listMethods'); + $response = $client->send($req, $timeout, $protocol); + if ($response->faultCode()) { + error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method list from remote server'); + + return false; + } else { + $mList = $response->value(); + if ($client->return_type != 'phpvals') { + $decoder = new $decoderClass(); + $mList = $decoder->decode($mList); + } + if (!is_array($mList) || !count($mList)) { + error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve meaningful method list from remote server'); + + return false; + } else { + // pick a suitable name for the new function, avoiding collisions + if ($newClassName != '') { + $xmlrpcClassName = $newClassName; + } else { + $xmlrpcClassName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'), + array('_', ''), $client->server) . '_client'; + } + while ($buildIt && class_exists($xmlrpcClassName)) { + $xmlrpcClassName .= 'x'; + } + + /// @todo add function setdebug() to new class, to enable/disable debugging + $source = "class $xmlrpcClassName\n{\npublic \$client;\n\n"; + $source .= "function __construct()\n{\n"; + $source .= $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace); + $source .= "\$this->client = \$client;\n}\n\n"; + $opts = array( + 'return_source' => true, + 'simple_client_copy' => 2, // do not produce code to copy the client object + 'timeout' => $timeout, + 'protocol' => $protocol, + 'encode_php_objs' => $encodePhpObjects, + 'decode_php_objs' => $decodePhpObjects, + 'prefix' => $prefix, + ); + /// @todo build phpdoc for class definition, too + foreach ($mList as $mName) { + if ($methodFilter == '' || preg_match($methodFilter, $mName)) { + // note: this will fail if server exposes 2 methods called f.e. do.something and do_something + $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'), + array('_', ''), $mName); + $methodWrap = $this->wrapXmlrpcMethod($client, $mName, $opts); + if ($methodWrap) { + if (!$buildIt) { + $source .= $methodWrap['docstring']; + } + $source .= $methodWrap['source'] . "\n"; + } else { + error_log('XML-RPC: ' . __METHOD__ . ': will not create class method to wrap remote method ' . $mName); + } + } + } + $source .= "}\n"; + if ($buildIt) { + $allOK = 0; + eval($source . '$allOK=1;'); + if ($allOK) { + return $xmlrpcClassName; + } else { + error_log('XML-RPC: ' . __METHOD__ . ': could not create class ' . $xmlrpcClassName . ' to wrap remote server ' . $client->server); + return false; + } + } else { + return array('class' => $xmlrpcClassName, 'code' => $source, 'docstring' => ''); + } + } + } + } + + /** + * Given necessary info, generate php code that will build a client object just like the given one. + * Take care that no full checking of input parameters is done to ensure that + * valid php code is emitted. + * @param Client $client + * @param bool $verbatimClientCopy when true, copy all of the state of the client, except for 'debug' and 'return_type' + * @param string $prefix used for the return_type of the created client + * @param string $namespace + * + * @return string + */ + protected function buildClientWrapperCode($client, $verbatimClientCopy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' ) + { + $code = "\$client = new {$namespace}Client('" . str_replace("'", "\'", $client->path) . + "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n"; + + // copy all client fields to the client that will be generated runtime + // (this provides for future expansion or subclassing of client obj) + if ($verbatimClientCopy) { + foreach ($client as $fld => $val) { + if ($fld != 'debug' && $fld != 'return_type') { + $val = var_export($val, true); + $code .= "\$client->$fld = $val;\n"; + } + } + } + // only make sure that client always returns the correct data type + $code .= "\$client->return_type = '{$prefix}vals';\n"; + //$code .= "\$client->setDebug(\$debug);\n"; + return $code; + } +} diff --git a/lib/phpxmlrpc/tests/0CharsetTest.php b/lib/phpxmlrpc/tests/0CharsetTest.php new file mode 100644 index 0000000..8a62506 --- /dev/null +++ b/lib/phpxmlrpc/tests/0CharsetTest.php @@ -0,0 +1,92 @@ +latinString = "\n\r\t"; + for($i = 32; $i < 127; $i++) { + $this->latinString .= chr($i); + } + for($i = 160; $i < 256; $i++) { + $this->latinString .= chr($i); + } + } + + protected function utfToLatin($data) + { + return Charset::instance()->encodeEntities( + $data, + 'UTF-8', + 'ISO-8859-1' + ); + } + + public function testUtf8ToLatin1All() + { + /*$this->assertEquals( + 'ISO-8859-1', + mb_detect_encoding($this->latinString, 'ISO-8859-1, UTF-8, WINDOWS-1251, ASCII', true), + 'Setup latinString is not ISO-8859-1 encoded...' + );*/ + $string = utf8_encode($this->latinString); + $encoded = $this->utfToLatin($string); + $this->assertEquals(str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $this->latinString), $encoded); + } + + public function testUtf8ToLatin1EuroSymbol() + { + $string = 'a.b.c.å.ä.ö.€.'; + $encoded = $this->utfToLatin($string); + $this->assertEquals(utf8_decode('a.b.c.å.ä.ö.€.'), $encoded); + } + + public function testUtf8ToLatin1Runes() + { + $string = $this->runes; + $encoded = $this->utfToLatin($string); + $this->assertEquals('ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ', $encoded); + } + + public function testUtf8ToLatin1Greek() + { + $string = $this->greek; + $encoded = $this->utfToLatin($string); + $this->assertEquals('Τὴ γλῶσσα μοῦ ἔδωσαν ἑλληνικὴ', $encoded); + } + + public function testUtf8ToLatin1Russian() + { + $string = $this->russian; + $encoded = $this->utfToLatin($string); + $this->assertEquals('Река неслася; бедный чёлн', $encoded); + } + + public function testUtf8ToLatin1Chinese() + { + $string = $this->chinese; + $encoded = $this->utfToLatin($string); + $this->assertEquals('我能吞下玻璃而不伤身体。', $encoded); + } +} diff --git a/lib/phpxmlrpc/tests/1ParsingBugsTest.php b/lib/phpxmlrpc/tests/1ParsingBugsTest.php new file mode 100644 index 0000000..ce463f7 --- /dev/null +++ b/lib/phpxmlrpc/tests/1ParsingBugsTest.php @@ -0,0 +1,639 @@ +args = argParser::getArgs(); + if ($this->args['DEBUG'] == 1) + ob_start(); + } + + protected function tearDown() + { + if ($this->args['DEBUG'] != 1) + return; + $out = ob_get_clean(); + $status = $this->getStatus(); + if ($status == PHPUnit_Runner_BaseTestRunner::STATUS_ERROR + || $status == PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE) { + echo $out; + } + } + + protected function newMsg($methodName, $params = array()) + { + $msg = new xmlrpcmsg($methodName, $params); + $msg->setDebug($this->args['DEBUG']); + return $msg; + } + + public function testMinusOneString() + { + $v = new xmlrpcval('-1'); + $u = new xmlrpcval('-1', 'string'); + $t = new xmlrpcval(-1, 'string'); + $this->assertEquals($v->scalarval(), $u->scalarval()); + $this->assertEquals($v->scalarval(), $t->scalarval()); + } + + /** + * This looks funny, and we might call it a bug. But we strive for 100 backwards compat... + */ + public function testMinusOneInt() + { + $u = new xmlrpcval(); + $v = new xmlrpcval(-1); + $this->assertEquals($u->scalarval(), $v->scalarval()); + } + + public function testUnicodeInMemberName() + { + $str = "G" . chr(252) . "nter, El" . chr(232) . "ne"; + $v = array($str => new xmlrpcval(1)); + $r = new xmlrpcresp(new xmlrpcval($v, 'struct')); + $r = $r->serialize(); + $m = $this->newMsg('dummy'); + $r = $m->parseResponse($r); + $v = $r->value(); + $this->assertEquals(true, $v->structmemexists($str)); + } + + public function testUnicodeInErrorString() + { + $response = utf8_encode( + ' + + + + + + + + +faultCode +888 + + +faultString +' . chr(224) . chr(252) . chr(232) . 'àüè + + + + +'); + $m = $this->newMsg('dummy'); + $r = $m->parseResponse($response); + $v = $r->faultString(); + $this->assertEquals(chr(224) . chr(252) . chr(232) . chr(224) . chr(252) . chr(232), $v); + } + + public function testValidNumbers() + { + $m = $this->newMsg('dummy'); + $fp = + ' + + + + + + +integer1 +01 + + +integer2 ++1 + + +integer3 +1 + + +float1 +01.10 + + +float2 ++1.10 + + +float3 +-1.10e2 + + + + + +'; + $r = $m->parseResponse($fp); + $v = $r->value(); + $s = $v->structmem('integer1'); + $t = $v->structmem('integer2'); + $u = $v->structmem('integer3'); + $x = $v->structmem('float1'); + $y = $v->structmem('float2'); + $z = $v->structmem('float3'); + $this->assertEquals(1, $s->scalarval()); + $this->assertEquals(1, $t->scalarval()); + $this->assertEquals(1, $u->scalarval()); + + $this->assertEquals(1.1, $x->scalarval()); + $this->assertEquals(1.1, $y->scalarval()); + $this->assertEquals(-110.0, $z->scalarval()); + } + + public function testI8() + { + if (PHP_INT_SIZE == 4 ) { + $this->markTestSkipped('did not find a locale which sets decimal separator to comma'); + return; + } + + $m = $this->newMsg('dummy'); + $fp = + ' + + + + + + +integer1 +1 + + + + + +'; + $r = $m->parseResponse($fp); + $v = $r->value(); + $s = $v->structmem('integer1'); + $this->assertEquals(1, $s->scalarval()); + } + + public function testAddScalarToStruct() + { + $v = new xmlrpcval(array('a' => 'b'), 'struct'); + // use @ operator in case error_log gets on screen + $r = @$v->addscalar('c'); + $this->assertEquals(0, $r); + } + + public function testAddStructToStruct() + { + $v = new xmlrpcval(array('a' => new xmlrpcval('b')), 'struct'); + $r = $v->addstruct(array('b' => new xmlrpcval('c'))); + $this->assertEquals(2, $v->structsize()); + $this->assertEquals(1, $r); + $r = $v->addstruct(array('b' => new xmlrpcval('b'))); + $this->assertEquals(2, $v->structsize()); + } + + public function testAddArrayToArray() + { + $v = new xmlrpcval(array(new xmlrpcval('a'), new xmlrpcval('b')), 'array'); + $r = $v->addarray(array(new xmlrpcval('b'), new xmlrpcval('c'))); + $this->assertEquals(4, $v->arraysize()); + $this->assertEquals(1, $r); + } + + public function testEncodeArray() + { + $r = range(1, 100); + $v = php_xmlrpc_encode($r); + $this->assertEquals('array', $v->kindof()); + } + + public function testEncodeRecursive() + { + $v = php_xmlrpc_encode(php_xmlrpc_encode('a simple string')); + $this->assertEquals('scalar', $v->kindof()); + } + + public function testBrokenRequests() + { + $s = new xmlrpc_server(); + // omitting the 'params' tag: not tolerated by the lib anymore + $f = ' + +system.methodHelp + +system.methodHelp + +'; + $r = $s->parserequest($f); + $this->assertEquals(15, $r->faultCode()); + // omitting a 'param' tag + $f = ' + +system.methodHelp + +system.methodHelp + +'; + $r = $s->parserequest($f); + $this->assertEquals(15, $r->faultCode()); + // omitting a 'value' tag + $f = ' + +system.methodHelp + +system.methodHelp + +'; + $r = $s->parserequest($f); + $this->assertEquals(15, $r->faultCode()); + } + + public function testBrokenResponses() + { + $m = $this->newMsg('dummy'); + // omitting the 'params' tag: no more tolerated by the lib... + $f = ' + + +system.methodHelp + +'; + $r = $m->parseResponse($f); + $this->assertEquals(2, $r->faultCode()); + // omitting the 'param' tag: no more tolerated by the lib... + $f = ' + + +system.methodHelp + +'; + $r = $m->parseResponse($f); + $this->assertEquals(2, $r->faultCode()); + // omitting a 'value' tag: KO + $f = ' + + +system.methodHelp + +'; + $r = $m->parseResponse($f); + $this->assertEquals(2, $r->faultCode()); + } + + public function testBuggyHttp() + { + $s = $this->newMsg('dummy'); + $f = 'HTTP/1.1 100 Welcome to the jungle + +HTTP/1.0 200 OK +X-Content-Marx-Brothers: Harpo + Chico and Groucho +Content-Length: who knows? + + + + + +userid311127 +dateCreated20011126T09:17:52contenthello world. 2 newlines follow + + +and there they were.postid7414222 + + '; + $r = $s->parseResponse($f); + $v = $r->value(); + $s = $v->structmem('content'); + $this->assertEquals("hello world. 2 newlines follow\n\n\nand there they were.", $s->scalarval()); + } + + public function testStringBug() + { + $s = $this->newMsg('dummy'); + $f = ' + + + + + + + + +success + +1 + + + +sessionID + +S300510007I + + + + + + + '; + $r = $s->parseResponse($f); + $v = $r->value(); + $s = $v->structmem('sessionID'); + $this->assertEquals('S300510007I', $s->scalarval()); + } + + public function testWhiteSpace() + { + $s = $this->newMsg('dummy'); + $f = 'userid311127 +dateCreated20011126T09:17:52contenthello world. 2 newlines follow + + +and there they were.postid7414222 +'; + $r = $s->parseResponse($f); + $v = $r->value(); + $s = $v->structmem('content'); + $this->assertEquals("hello world. 2 newlines follow\n\n\nand there they were.", $s->scalarval()); + } + + public function testDoubleDataInArrayTag() + { + $s = $this->newMsg('dummy'); + $f = ' + + + +'; + $r = $s->parseResponse($f); + $v = $r->faultCode(); + $this->assertEquals(2, $v); + $f = ' +Hello world + + +'; + $r = $s->parseResponse($f); + $v = $r->faultCode(); + $this->assertEquals(2, $v); + } + + public function testDoubleStuffInValueTag() + { + $s = $this->newMsg('dummy'); + $f = ' +hello world + + +'; + $r = $s->parseResponse($f); + $v = $r->faultCode(); + $this->assertEquals(2, $v); + $f = ' +hello +world + +'; + $r = $s->parseResponse($f); + $v = $r->faultCode(); + $this->assertEquals(2, $v); + $f = ' +hello +hello>world + +'; + $r = $s->parseResponse($f); + $v = $r->faultCode(); + $this->assertEquals(2, $v); + } + + public function testAutodecodeResponse() + { + $s = $this->newMsg('dummy'); + $f = 'userid311127 +dateCreated20011126T09:17:52contenthello world. 2 newlines follow + + +and there they were.postid7414222 +'; + $r = $s->parseResponse($f, true, 'phpvals'); + $v = $r->value(); + $s = $v['content']; + $this->assertEquals("hello world. 2 newlines follow\n\n\nand there they were.", $s); + } + + public function testNoDecodeResponse() + { + $s = $this->newMsg('dummy'); + $f = 'userid311127 +dateCreated20011126T09:17:52contenthello world. 2 newlines follow + + +and there they were.postid7414222'; + $r = $s->parseResponse($f, true, 'xml'); + $v = $r->value(); + $this->assertEquals($f, $v); + } + + public function testAutoCoDec() + { + $data1 = array(1, 1.0, 'hello world', true, '20051021T23:43:00', -1, 11.0, '~!@#$%^&*()_+|', false, '20051021T23:43:00'); + $data2 = array('zero' => $data1, 'one' => $data1, 'two' => $data1, 'three' => $data1, 'four' => $data1, 'five' => $data1, 'six' => $data1, 'seven' => $data1, 'eight' => $data1, 'nine' => $data1); + $data = array($data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2); + //$keys = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'); + $v1 = php_xmlrpc_encode($data, array('auto_dates')); + $v2 = php_xmlrpc_decode_xml($v1->serialize()); + $this->assertEquals($v1, $v2); + $r1 = new PhpXmlRpc\Response($v1); + $r2 = php_xmlrpc_decode_xml($r1->serialize()); + $r2->serialize(); // needed to set internal member payload + $this->assertEquals($r1, $r2); + $m1 = new PhpXmlRpc\Request('hello dolly', array($v1)); + $m2 = php_xmlrpc_decode_xml($m1->serialize()); + $m2->serialize(); // needed to set internal member payload + $this->assertEquals($m1, $m2); + } + + public function testUTF8Request() + { + $sendstring = 'κόσμε'; // Greek word 'kosme'. NB: NOT a valid ISO8859 string! + $GLOBALS['xmlrpc_internalencoding'] = 'UTF-8'; + \PhpXmlRpc\PhpXmlRpc::importGlobals(); + $f = new xmlrpcval($sendstring, 'string'); + $v = $f->serialize(); + $this->assertEquals("κόσμε\n", $v); + $GLOBALS['xmlrpc_internalencoding'] = 'ISO-8859-1'; + \PhpXmlRpc\PhpXmlRpc::importGlobals(); + } + + public function testUTF8Response() + { + $string = chr(224) . chr(252) . chr(232); + + $s = $this->newMsg('dummy'); + $f = "HTTP/1.1 200 OK\r\nContent-type: text/xml; charset=UTF-8\r\n\r\n" . 'userid311127 +dateCreated20011126T09:17:52content' . utf8_encode($string) . 'postid7414222 +'; + $r = $s->parseResponse($f, false, 'phpvals'); + $v = $r->value(); + $v = $v['content']; + $this->assertEquals($string, $v); + + $f = 'userid311127 +dateCreated20011126T09:17:52content' . utf8_encode($string) . 'postid7414222 +'; + $r = $s->parseResponse($f, false, 'phpvals'); + $v = $r->value(); + $v = $v['content']; + $this->assertEquals($string, $v); + + $r = php_xmlrpc_decode_xml($f); + $v = $r->value(); + $v = $v->structmem('content')->scalarval(); + $this->assertEquals($string, $v); + } + + public function testLatin1Response() + { + $string = chr(224) . chr(252) . chr(232); + + $s = $this->newMsg('dummy'); + $f = "HTTP/1.1 200 OK\r\nContent-type: text/xml; charset=ISO-8859-1\r\n\r\n" . 'userid311127 +dateCreated20011126T09:17:52content' . $string . 'postid7414222 +'; + $r = $s->parseResponse($f, false, 'phpvals'); + $v = $r->value(); + $v = $v['content']; + $this->assertEquals($string, $v); + + $f = 'userid311127 +dateCreated20011126T09:17:52content' . $string . 'postid7414222 +'; + $r = $s->parseResponse($f, false, 'phpvals'); + $v = $r->value(); + $v = $v['content']; + $this->assertEquals($string, $v); + + $r = php_xmlrpc_decode_xml($f); + $v = $r->value(); + $v = $v->structmem('content')->scalarval(); + $this->assertEquals($string, $v); + } + + public function testUTF8IntString() + { + $v = new xmlrpcval(100, 'int'); + $s = $v->serialize('UTF-8'); + $this->assertequals("100\n", $s); + } + + public function testStringInt() + { + $v = new xmlrpcval('hello world', 'int'); + $s = $v->serialize(); + $this->assertequals("0\n", $s); + } + + public function testStructMemExists() + { + $v = php_xmlrpc_encode(array('hello' => 'world')); + $b = $v->structmemexists('hello'); + $this->assertequals(true, $b); + $b = $v->structmemexists('world'); + $this->assertequals(false, $b); + } + + public function testNilvalue() + { + // default case: we do not accept nil values received + $v = new xmlrpcval('hello', 'null'); + $r = new xmlrpcresp($v); + $s = $r->serialize(); + $m = $this->newMsg('dummy'); + $r = $m->parseresponse($s); + $this->assertequals(2, $r->faultCode()); + // enable reception of nil values + $GLOBALS['xmlrpc_null_extension'] = true; + \PhpXmlRpc\PhpXmlRpc::importGlobals(); + $r = $m->parseresponse($s); + $v = $r->value(); + $this->assertequals('null', $v->scalartyp()); + // test with the apache version: EX:NIL + $GLOBALS['xmlrpc_null_apache_encoding'] = true; + \PhpXmlRpc\PhpXmlRpc::importGlobals(); + // serialization + $v = new xmlrpcval('hello', 'null'); + $s = $v->serialize(); + $this->assertequals(1, preg_match('##', $s)); + // deserialization + $r = new xmlrpcresp($v); + $s = $r->serialize(); + $r = $m->parseresponse($s); + $v = $r->value(); + $this->assertequals('null', $v->scalartyp()); + $GLOBALS['xmlrpc_null_extension'] = false; + \PhpXmlRpc\PhpXmlRpc::importGlobals(); + $r = $m->parseresponse($s); + $this->assertequals(2, $r->faultCode()); + } + + public function testLocale() + { + $locale = setlocale(LC_NUMERIC, 0); + /// @todo on php 5.3/win setting locale to german does not seem to set decimal separator to comma... + if (setlocale(LC_NUMERIC, 'deu', 'de_DE@euro', 'de_DE', 'de', 'ge') !== false) { + $v = new xmlrpcval(1.1, 'double'); + if (strpos($v->scalarval(), ',') == 1) { + $r = $v->serialize(); + $this->assertequals(false, strpos($r, ',')); + setlocale(LC_NUMERIC, $locale); + } else { + setlocale(LC_NUMERIC, $locale); + $this->markTestSkipped('did not find a locale which sets decimal separator to comma'); + } + } else { + $this->markTestSkipped('did not find a locale which sets decimal separator to comma'); + } + } + + public function testArrayAccess() + { + $v1 = new xmlrpcval(array(new xmlrpcval('one'), new xmlrpcval('two')), 'array'); + $this->assertequals(1, count($v1)); + $out = array('me' => array(), 'mytype' => 2, '_php_class' => null); + foreach($v1 as $key => $val) + { + $expected = each($out); + $this->assertequals($expected['key'], $key); + if (gettype($expected['value']) == 'array') { + $this->assertequals('array', gettype($val)); + } else { + $this->assertequals($expected['value'], $val); + } + } + + $v2 = new \PhpXmlRpc\Value(array(new \PhpXmlRpc\Value('one'), new \PhpXmlRpc\Value('two')), 'array'); + $this->assertequals(2, count($v2)); + $out = array(0 => 'object', 1 => 'object'); + foreach($v2 as $key => $val) + { + $expected = each($out); + $this->assertequals($expected['key'], $key); + $this->assertequals($expected['value'], gettype($val)); + } + } +} diff --git a/lib/phpxmlrpc/tests/2InvalidHostTest.php b/lib/phpxmlrpc/tests/2InvalidHostTest.php new file mode 100644 index 0000000..1c81b55 --- /dev/null +++ b/lib/phpxmlrpc/tests/2InvalidHostTest.php @@ -0,0 +1,94 @@ +args = argParser::getArgs(); + + $this->client = new xmlrpc_client('/NOTEXIST.php', $this->args['LOCALSERVER'], 80); + $this->client->setDebug($this->args['DEBUG']); + + if ($this->args['DEBUG'] == 1) + ob_start(); + } + + protected function tearDown() + { + if ($this->args['DEBUG'] != 1) + return; + $out = ob_get_clean(); + $status = $this->getStatus(); + if ($status == PHPUnit_Runner_BaseTestRunner::STATUS_ERROR + || $status == PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE) { + echo $out; + } + } + + public function test404() + { + $m = new xmlrpcmsg('examples.echo', array( + new xmlrpcval('hello', 'string'), + )); + $r = $this->client->send($m, 5); + $this->assertEquals(5, $r->faultCode()); + } + + public function testSrvNotFound() + { + $m = new xmlrpcmsg('examples.echo', array( + new xmlrpcval('hello', 'string'), + )); + $this->client->server .= 'XXX'; + $r = $this->client->send($m, 5); + // make sure there's no freaking catchall DNS in effect + $dnsinfo = dns_get_record($this->client->server); + if ($dnsinfo) { + $this->markTestSkipped('Seems like there is a catchall DNS in effect: host ' . $this->client->server . ' found'); + } else { + $this->assertEquals(5, $r->faultCode()); + } + } + + public function testCurlKAErr() + { + if (!function_exists('curl_init')) { + $this->markTestSkipped('CURL missing: cannot test curl keepalive errors'); + + return; + } + $m = new xmlrpcmsg('examples.stringecho', array( + new xmlrpcval('hello', 'string'), + )); + // test 2 calls w. keepalive: 1st time connection ko, second time ok + $this->client->server .= 'XXX'; + $this->client->keepalive = true; + $r = $this->client->send($m, 5, 'http11'); + // in case we have a "universal dns resolver" getting in the way, we might get a 302 instead of a 404 + $this->assertTrue($r->faultCode() === 8 || $r->faultCode() == 5); + + // now test a successful connection + $server = explode(':', $this->args['LOCALSERVER']); + if (count($server) > 1) { + $this->client->port = $server[1]; + } + $this->client->server = $server[0]; + $this->client->path = $this->args['URI']; + + $r = $this->client->send($m, 5, 'http11'); + $this->assertEquals(0, $r->faultCode()); + $ro = $r->value(); + is_object($ro) && $this->assertEquals('hello', $ro->scalarVal()); + } +} diff --git a/lib/phpxmlrpc/tests/3LocalhostTest.php b/lib/phpxmlrpc/tests/3LocalhostTest.php new file mode 100644 index 0000000..0290dbf --- /dev/null +++ b/lib/phpxmlrpc/tests/3LocalhostTest.php @@ -0,0 +1,955 @@ +testId = get_class($this) . '__' . $this->getName(); + + if ($result === NULL) { + $result = $this->createResult(); + } + + $this->collectCodeCoverageInformation = $result->getCollectCodeCoverageInformation(); + + parent::run($result); + + if ($this->collectCodeCoverageInformation) { + $coverage = new PHPUnit_Extensions_SeleniumCommon_RemoteCoverage( + $this->coverageScriptUrl, + $this->testId + ); + $result->getCodeCoverage()->append( + $coverage->get(), $this + ); + } + + // do not call this before to give the time to the Listeners to run + //$this->getStrategy()->endOfTest($this->session); + + return $result; + } + + public function setUp() + { + $this->args = argParser::getArgs(); + + $server = explode(':', $this->args['LOCALSERVER']); + if (count($server) > 1) { + $this->client = new xmlrpc_client($this->args['URI'], $server[0], $server[1]); + } else { + $this->client = new xmlrpc_client($this->args['URI'], $this->args['LOCALSERVER']); + } + + $this->client->setDebug($this->args['DEBUG']); + $this->client->request_compression = $this->request_compression; + $this->client->accepted_compression = $this->accepted_compression; + + $this->coverageScriptUrl = 'http://' . $this->args['LOCALSERVER'] . '/' . str_replace( '/demo/server/server.php', 'tests/phpunit_coverage.php', $this->args['URI'] ); + + if ($this->args['DEBUG'] == 1) + ob_start(); + } + + protected function tearDown() + { + if ($this->args['DEBUG'] != 1) + return; + $out = ob_get_clean(); + $status = $this->getStatus(); + if ($status == PHPUnit_Runner_BaseTestRunner::STATUS_ERROR + || $status == PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE) { + echo $out; + } + } + + /** + * @param PhpXmlRpc\Request|array $msg + * @param int|array $errorCode + * @param bool $returnResponse + * @return mixed|\PhpXmlRpc\Response|\PhpXmlRpc\Response[]|\PhpXmlRpc\Value|string|void + */ + protected function send($msg, $errorCode = 0, $returnResponse = false) + { + if ($this->collectCodeCoverageInformation) { + $this->client->setCookie('PHPUNIT_SELENIUM_TEST_ID', $this->testId); + } + + $r = $this->client->send($msg, $this->timeout, $this->method); + // for multicall, return directly array of responses + if (is_array($r)) { + return $r; + } + if (is_array($errorCode)) { + $this->assertContains($r->faultCode(), $errorCode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); + } else { + $this->assertEquals($errorCode, $r->faultCode(), 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); + } + if (!$r->faultCode()) { + if ($returnResponse) { + return $r; + } else { + return $r->value(); + } + } else { + return; + } + } + + public function testString() + { + $sendString = "here are 3 \"entities\": < > & " . + "and here's a dollar sign: \$pretendvarname and a backslash too: " . chr(92) . + " - isn't that great? \\\"hackery\\\" at it's best " . + " also don't want to miss out on \$item[0]. " . + "The real weird stuff follows: CRLF here" . chr(13) . chr(10) . + "a simple CR here" . chr(13) . + "a simple LF here" . chr(10) . + "and then LFCR" . chr(10) . chr(13) . + "last but not least weird names: G" . chr(252) . "nter, El" . chr(232) . "ne, and an xml comment closing tag: -->"; + $m = new xmlrpcmsg('examples.stringecho', array( + new xmlrpcval($sendString, 'string'), + )); + $v = $this->send($m); + if ($v) { + // when sending/receiving non-US-ASCII encoded strings, XML says cr-lf can be normalized. + // so we relax our tests... + $l1 = strlen($sendString); + $l2 = strlen($v->scalarval()); + if ($l1 == $l2) { + $this->assertEquals($sendString, $v->scalarval()); + } else { + $this->assertEquals(str_replace(array("\r\n", "\r"), array("\n", "\n"), $sendString), $v->scalarval()); + } + } + } + + public function testLatin1String() + { + $sendString = + "last but not least weird names: G" . chr(252) . "nter, El" . chr(232) . "ne"; + $x = 'examples.stringecho'. + $sendString. + ''; + $v = $this->send($x); + if ($v) { + $this->assertEquals($sendString, $v->scalarval()); + } + } + + public function testExoticCharsetsRequests() + { + // note that we should disable this call also when mbstring is missing server-side + if (!function_exists('mb_convert_encoding')) { + $this->markTestSkipped('Miss mbstring extension to test exotic charsets'); + return; + } + $sendString = 'κόσμε'; // Greek word 'kosme'. NB: NOT a valid ISO8859 string! + $str = ' + + examples.stringecho + + + '.$sendString.' + + +'; + + PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'UTF-8'; + // we have to set the encoding declaration either in the http header or xml prolog, as mb_detect_encoding + // (used on the server side) will fail recognizing these 2 charsets + $v = $this->send(mb_convert_encoding(str_replace('_ENC_', 'UCS-4', $str), 'UCS-4', 'UTF-8')); + $this->assertEquals($sendString, $v->scalarval()); + $v = $this->send(mb_convert_encoding(str_replace('_ENC_', 'UTF-16', $str), 'UTF-16', 'UTF-8')); + $this->assertEquals($sendString, $v->scalarval()); + PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'ISO-8859-1'; + } + + public function testExoticCharsetsRequests2() + { + // note that we should disable this call also when mbstring is missing server-side + if (!function_exists('mb_convert_encoding')) { + $this->markTestSkipped('Miss mbstring extension to test exotic charsets'); + return; + } + $sendString = '安室奈美恵'; // No idea what this means :-) NB: NOT a valid ISO8859 string! + $str = ' + + examples.stringecho + + + '.$sendString.' + + +'; + + PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'UTF-8'; + // no encoding declaration either in the http header or xml prolog, let mb_detect_encoding + // (used on the server side) sort it out + $this->client->path = $this->args['URI'].'?DETECT_ENCODINGS[]=EUC-JP&DETECT_ENCODINGS[]=UTF-8'; + $v = $this->send(mb_convert_encoding($str, 'EUC-JP', 'UTF-8')); + $this->assertEquals($sendString, $v->scalarval()); + PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'ISO-8859-1'; + } + + public function testExoticCharsetsRequests3() + { + // note that we should disable this call also when mbstring is missing server-side + if (!function_exists('mb_convert_encoding')) { + $this->markTestSkipped('Miss mbstring extension to test exotic charsets'); + return; + } + $sendString = utf8_decode('élève'); + $str = ' + + examples.stringecho + + + '.$sendString.' + + +'; + + // no encoding declaration either in the http header or xml prolog, let mb_detect_encoding + // (used on the server side) sort it out + $this->client->path = $this->args['URI'].'?DETECT_ENCODINGS[]=ISO-8859-1&DETECT_ENCODINGS[]=UTF-8'; + $v = $this->send($str); + $this->assertEquals($sendString, $v->scalarval()); + } + + /*public function testLatin1Method() + { + $f = new xmlrpcmsg("tests.iso88591methodname." . chr(224) . chr(252) . chr(232), array( + new xmlrpcval('hello') + )); + $v = $this->send($f); + if ($v) { + $this->assertEquals('hello', $v->scalarval()); + } + }*/ + + public function testUtf8Method() + { + PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'UTF-8'; + $m = new xmlrpcmsg("tests.utf8methodname." . 'κόσμε', array( + new xmlrpcval('hello') + )); + $v = $this->send($m); + if ($v) { + $this->assertEquals('hello', $v->scalarval()); + } + PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'ISO-8859-1'; + } + + public function testAddingDoubles() + { + // note that rounding errors mean we + // keep precision to sensible levels here ;-) + $a = 12.13; + $b = -23.98; + $m = new xmlrpcmsg('examples.addtwodouble', array( + new xmlrpcval($a, 'double'), + new xmlrpcval($b, 'double'), + )); + $v = $this->send($m); + if ($v) { + $this->assertEquals($a + $b, $v->scalarval()); + } + } + + public function testAdding() + { + $m = new xmlrpcmsg('examples.addtwo', array( + new xmlrpcval(12, 'int'), + new xmlrpcval(-23, 'int'), + )); + $v = $this->send($m); + if ($v) { + $this->assertEquals(12 - 23, $v->scalarval()); + } + } + + public function testInvalidNumber() + { + $m = new xmlrpcmsg('examples.addtwo', array( + new xmlrpcval('fred', 'int'), + new xmlrpcval("\"; exec('ls')", 'int'), + )); + $v = $this->send($m); + /// @todo a fault condition should be generated here + /// by the server, which we pick up on + if ($v) { + $this->assertEquals(0, $v->scalarval()); + } + } + + public function testBoolean() + { + $m = new xmlrpcmsg('examples.invertBooleans', array( + new xmlrpcval(array( + new xmlrpcval(true, 'boolean'), + new xmlrpcval(false, 'boolean'), + new xmlrpcval(1, 'boolean'), + new xmlrpcval(0, 'boolean') + ), + 'array' + ),)); + $answer = '0101'; + $v = $this->send($m); + if ($v) { + $sz = $v->arraysize(); + $got = ''; + for ($i = 0; $i < $sz; $i++) { + $b = $v->arraymem($i); + if ($b->scalarval()) { + $got .= '1'; + } else { + $got .= '0'; + } + } + $this->assertEquals($answer, $got); + } + } + + public function testBase64() + { + $sendString = 'Mary had a little lamb, +Whose fleece was white as snow, +And everywhere that Mary went +the lamb was sure to go. + +Mary had a little lamb +She tied it to a pylon +Ten thousand volts went down its back +And turned it into nylon'; + $m = new xmlrpcmsg('examples.decode64', array( + new xmlrpcval($sendString, 'base64'), + )); + $v = $this->send($m); + if ($v) { + if (strlen($sendString) == strlen($v->scalarval())) { + $this->assertEquals($sendString, $v->scalarval()); + } else { + $this->assertEquals(str_replace(array("\r\n", "\r"), array("\n", "\n"), $sendString), $v->scalarval()); + } + } + } + + public function testDateTime() + { + $time = time(); + $t1 = new xmlrpcval($time, 'dateTime.iso8601'); + $t2 = new xmlrpcval(iso8601_encode($time), 'dateTime.iso8601'); + $this->assertEquals($t1->serialize(), $t2->serialize()); + if (class_exists('DateTime')) { + $datetime = new DateTime(); + // skip this test for php 5.2. It is a bit harder there to build a DateTime from unix timestamp with proper TZ info + if (is_callable(array($datetime, 'setTimestamp'))) { + $t3 = new xmlrpcval($datetime->setTimestamp($time), 'dateTime.iso8601'); + $this->assertEquals($t1->serialize(), $t3->serialize()); + } + } + } + + public function testCountEntities() + { + $sendString = "h'fd>onc>>l>>rw&bpu>q>esend($m); + if ($v) { + $got = ''; + $expected = '37210'; + $expect_array = array('ctLeftAngleBrackets', 'ctRightAngleBrackets', 'ctAmpersands', 'ctApostrophes', 'ctQuotes'); + while (list(, $val) = each($expect_array)) { + $b = $v->structmem($val); + $got .= $b->me['int']; + } + $this->assertEquals($expected, $got); + } + } + + public function _multicall_msg($method, $params) + { + $struct['methodName'] = new xmlrpcval($method, 'string'); + $struct['params'] = new xmlrpcval($params, 'array'); + + return new xmlrpcval($struct, 'struct'); + } + + public function testServerMulticall() + { + // We manually construct a system.multicall() call to ensure + // that the server supports it. + + // NB: This test will NOT pass if server does not support system.multicall. + + // Based on http://xmlrpc-c.sourceforge.net/hacks/test_multicall.py + $good1 = $this->_multicall_msg( + 'system.methodHelp', + array(php_xmlrpc_encode('system.listMethods'))); + $bad = $this->_multicall_msg( + 'test.nosuch', + array(php_xmlrpc_encode(1), php_xmlrpc_encode(2))); + $recursive = $this->_multicall_msg( + 'system.multicall', + array(new xmlrpcval(array(), 'array'))); + $good2 = $this->_multicall_msg( + 'system.methodSignature', + array(php_xmlrpc_encode('system.listMethods'))); + $arg = new xmlrpcval( + array($good1, $bad, $recursive, $good2), + 'array' + ); + + $m = new xmlrpcmsg('system.multicall', array($arg)); + $v = $this->send($m); + if ($v) { + //$this->assertTrue($r->faultCode() == 0, "fault from system.multicall"); + $this->assertTrue($v->arraysize() == 4, "bad number of return values"); + + $r1 = $v->arraymem(0); + $this->assertTrue( + $r1->kindOf() == 'array' && $r1->arraysize() == 1, + "did not get array of size 1 from good1" + ); + + $r2 = $v->arraymem(1); + $this->assertTrue( + $r2->kindOf() == 'struct', + "no fault from bad" + ); + + $r3 = $v->arraymem(2); + $this->assertTrue( + $r3->kindOf() == 'struct', + "recursive system.multicall did not fail" + ); + + $r4 = $v->arraymem(3); + $this->assertTrue( + $r4->kindOf() == 'array' && $r4->arraysize() == 1, + "did not get array of size 1 from good2" + ); + } + } + + public function testClientMulticall1() + { + // NB: This test will NOT pass if server does not support system.multicall. + + $this->client->no_multicall = false; + + $good1 = new xmlrpcmsg('system.methodHelp', + array(php_xmlrpc_encode('system.listMethods'))); + $bad = new xmlrpcmsg('test.nosuch', + array(php_xmlrpc_encode(1), php_xmlrpc_encode(2))); + $recursive = new xmlrpcmsg('system.multicall', + array(new xmlrpcval(array(), 'array'))); + $good2 = new xmlrpcmsg('system.methodSignature', + array(php_xmlrpc_encode('system.listMethods')) + ); + + $r = $this->send(array($good1, $bad, $recursive, $good2)); + if ($r) { + $this->assertTrue(count($r) == 4, "wrong number of return values"); + } + + $this->assertTrue($r[0]->faultCode() == 0, "fault from good1"); + if (!$r[0]->faultCode()) { + $val = $r[0]->value(); + $this->assertTrue( + $val->kindOf() == 'scalar' && $val->scalartyp() == 'string', + "good1 did not return string" + ); + } + $this->assertTrue($r[1]->faultCode() != 0, "no fault from bad"); + $this->assertTrue($r[2]->faultCode() != 0, "no fault from recursive system.multicall"); + $this->assertTrue($r[3]->faultCode() == 0, "fault from good2"); + if (!$r[3]->faultCode()) { + $val = $r[3]->value(); + $this->assertTrue($val->kindOf() == 'array', "good2 did not return array"); + } + // This is the only assert in this test which should fail + // if the test server does not support system.multicall. + $this->assertTrue($this->client->no_multicall == false, + "server does not support system.multicall" + ); + } + + public function testClientMulticall2() + { + // NB: This test will NOT pass if server does not support system.multicall. + + $this->client->no_multicall = true; + + $good1 = new xmlrpcmsg('system.methodHelp', + array(php_xmlrpc_encode('system.listMethods'))); + $bad = new xmlrpcmsg('test.nosuch', + array(php_xmlrpc_encode(1), php_xmlrpc_encode(2))); + $recursive = new xmlrpcmsg('system.multicall', + array(new xmlrpcval(array(), 'array'))); + $good2 = new xmlrpcmsg('system.methodSignature', + array(php_xmlrpc_encode('system.listMethods')) + ); + + $r = $this->send(array($good1, $bad, $recursive, $good2)); + if ($r) { + $this->assertTrue(count($r) == 4, "wrong number of return values"); + } + + $this->assertTrue($r[0]->faultCode() == 0, "fault from good1"); + if (!$r[0]->faultCode()) { + $val = $r[0]->value(); + $this->assertTrue( + $val->kindOf() == 'scalar' && $val->scalartyp() == 'string', + "good1 did not return string"); + } + $this->assertTrue($r[1]->faultCode() != 0, "no fault from bad"); + $this->assertTrue($r[2]->faultCode() == 0, "fault from (non recursive) system.multicall"); + $this->assertTrue($r[3]->faultCode() == 0, "fault from good2"); + if (!$r[3]->faultCode()) { + $val = $r[3]->value(); + $this->assertTrue($val->kindOf() == 'array', "good2 did not return array"); + } + } + + public function testClientMulticall3() + { + // NB: This test will NOT pass if server does not support system.multicall. + + $this->client->return_type = 'phpvals'; + $this->client->no_multicall = false; + + $good1 = new xmlrpcmsg('system.methodHelp', + array(php_xmlrpc_encode('system.listMethods'))); + $bad = new xmlrpcmsg('test.nosuch', + array(php_xmlrpc_encode(1), php_xmlrpc_encode(2))); + $recursive = new xmlrpcmsg('system.multicall', + array(new xmlrpcval(array(), 'array'))); + $good2 = new xmlrpcmsg('system.methodSignature', + array(php_xmlrpc_encode('system.listMethods')) + ); + + $r = $this->send(array($good1, $bad, $recursive, $good2)); + if ($r) { + $this->assertTrue(count($r) == 4, "wrong number of return values"); + } + $this->assertTrue($r[0]->faultCode() == 0, "fault from good1"); + if (!$r[0]->faultCode()) { + $val = $r[0]->value(); + $this->assertTrue( + is_string($val), "good1 did not return string"); + } + $this->assertTrue($r[1]->faultCode() != 0, "no fault from bad"); + $this->assertTrue($r[2]->faultCode() != 0, "no fault from recursive system.multicall"); + $this->assertTrue($r[3]->faultCode() == 0, "fault from good2"); + if (!$r[3]->faultCode()) { + $val = $r[3]->value(); + $this->assertTrue(is_array($val), "good2 did not return array"); + } + $this->client->return_type = 'xmlrpcvals'; + } + + public function testCatchWarnings() + { + $m = new xmlrpcmsg('tests.generatePHPWarning', array( + new xmlrpcval('whatever', 'string'), + )); + $v = $this->send($m); + if ($v) { + $this->assertEquals(true, $v->scalarval()); + } + } + + public function testCatchExceptions() + { + $m = new xmlrpcmsg('tests.raiseException', array( + new xmlrpcval('whatever', 'string'), + )); + $v = $this->send($m, $GLOBALS['xmlrpcerr']['server_error']); + $this->client->path = $this->args['URI'] . '?EXCEPTION_HANDLING=1'; + $v = $this->send($m, 1); // the error code of the expected exception + $this->client->path = $this->args['URI'] . '?EXCEPTION_HANDLING=2'; + // depending on whether display_errors is ON or OFF on the server, we will get back a different error here, + // as php will generate an http status code of either 200 or 500... + $v = $this->send($m, array($GLOBALS['xmlrpcerr']['invalid_return'], $GLOBALS['xmlrpcerr']['http_error'])); + } + + public function testZeroParams() + { + $m = new xmlrpcmsg('system.listMethods'); + $v = $this->send($m); + } + + public function testNullParams() + { + $m = new xmlrpcmsg('tests.getStateName.12', array( + new xmlrpcval('whatever', 'null'), + new xmlrpcval(23, 'int'), + )); + $v = $this->send($m); + if ($v) { + $this->assertEquals('Michigan', $v->scalarval()); + } + $m = new xmlrpcmsg('tests.getStateName.12', array( + new xmlrpcval(23, 'int'), + new xmlrpcval('whatever', 'null'), + )); + $v = $this->send($m); + if ($v) { + $this->assertEquals('Michigan', $v->scalarval()); + } + $m = new xmlrpcmsg('tests.getStateName.12', array( + new xmlrpcval(23, 'int') + )); + $v = $this->send($m, array($GLOBALS['xmlrpcerr']['incorrect_params'])); + } + + public function testCodeInjectionServerSide() + { + $m = new xmlrpcmsg('system.MethodHelp'); + $m->payload = "validator1.echoStructTest','')); echo('gotcha!'); die(); //"; + $v = $this->send($m); + if ($v) { + $this->assertEquals(0, $v->structsize()); + } + } + + public function testServerWrappedFunction() + { + $m = new xmlrpcmsg('tests.getStateName.2', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($m); + $this->assertEquals('Michigan', $v->scalarval()); + + // this generates an exception in the function which was wrapped, which is by default wrapped in a known error response + $m = new xmlrpcmsg('tests.getStateName.2', array( + new xmlrpcval(0, 'int'), + )); + $v = $this->send($m, $GLOBALS['xmlrpcerr']['server_error']); + + // check if the generated function dispatch map is fine, by checking if the server registered it + $m = new xmlrpcmsg('system.methodSignature', array( + new xmlrpcval('tests.getStateName.2'), + )); + $v = $this->send($m); + $encoder = new \PhpXmlRpc\Encoder(); + $this->assertEquals(array(array('string', 'int')), $encoder->decode($v)); + } + + public function testServerWrappedFunctionAsSource() + { + $m = new xmlrpcmsg('tests.getStateName.6', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($m); + $this->assertEquals('Michigan', $v->scalarval()); + + // this generates an exception in the function which was wrapped, which is by default wrapped in a known error response + $m = new xmlrpcmsg('tests.getStateName.6', array( + new xmlrpcval(0, 'int'), + )); + $v = $this->send($m, $GLOBALS['xmlrpcerr']['server_error']); + } + + public function testServerWrappedObjectMethods() + { + $m = new xmlrpcmsg('tests.getStateName.3', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($m); + $this->assertEquals('Michigan', $v->scalarval()); + + $m = new xmlrpcmsg('tests.getStateName.4', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($m); + $this->assertEquals('Michigan', $v->scalarval()); + + $m = new xmlrpcmsg('tests.getStateName.5', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($m); + $this->assertEquals('Michigan', $v->scalarval()); + + $m = new xmlrpcmsg('tests.getStateName.7', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($m); + $this->assertEquals('Michigan', $v->scalarval()); + + $m = new xmlrpcmsg('tests.getStateName.8', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($m); + $this->assertEquals('Michigan', $v->scalarval()); + + $m = new xmlrpcmsg('tests.getStateName.9', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($m); + $this->assertEquals('Michigan', $v->scalarval()); + } + + public function testServerWrappedObjectMethodsAsSource() + { + $m = new xmlrpcmsg('tests.getStateName.7', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($m); + $this->assertEquals('Michigan', $v->scalarval()); + + $m = new xmlrpcmsg('tests.getStateName.8', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($m); + $this->assertEquals('Michigan', $v->scalarval()); + + $m = new xmlrpcmsg('tests.getStateName.9', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($m); + $this->assertEquals('Michigan', $v->scalarval()); + } + + public function testServerClosure() + { + $m = new xmlrpcmsg('tests.getStateName.10', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($m); + $this->assertEquals('Michigan', $v->scalarval()); + } + + public function testServerWrappedClosure() + { + $m = new xmlrpcmsg('tests.getStateName.11', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($m); + $this->assertEquals('Michigan', $v->scalarval()); + } + + public function testServerWrappedClass() + { + $m = new xmlrpcmsg('tests.xmlrpcServerMethodsContainer.findState', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($m); + $this->assertEquals('Michigan', $v->scalarval()); + } + + public function testWrappedMethod() + { + // make a 'deep client copy' as the original one might have many properties set + $func = wrap_xmlrpc_method($this->client, 'examples.getStateName', array('simple_client_copy' => 0)); + if ($func == false) { + $this->fail('Registration of examples.getStateName failed'); + } else { + $v = $func(23); + // work around bug in current (or old?) version of phpunit when reporting the error + /*if (is_object($v)) { + $v = var_export($v, true); + }*/ + $this->assertEquals('Michigan', $v); + } + } + + public function testWrappedMethodAsSource() + { + // make a 'deep client copy' as the original one might have many properties set + $func = wrap_xmlrpc_method($this->client, 'examples.getStateName', array('simple_client_copy' => 0, 'return_source' => true)); + if ($func == false) { + $this->fail('Registration of examples.getStateName failed'); + } else { + eval($func['source']); + $func = $func['function']; + $v = $func(23); + // work around bug in current (or old?) version of phpunit when reporting the error + /*if (is_object($v)) { + $v = var_export($v, true); + }*/ + $this->assertEquals('Michigan', $v); + } + } + + public function testWrappedClass() + { + // make a 'deep client copy' as the original one might have many properties set + // also for speed only wrap one method of the whole server + $class = wrap_xmlrpc_server($this->client, array('simple_client_copy' => 0, 'method_filter' => '/examples\.getStateName/' )); + if ($class == '') { + $this->fail('Registration of remote server failed'); + } else { + $obj = new $class(); + $v = $obj->examples_getStateName(23); + // work around bug in current (or old?) version of phpunit when reporting the error + /*if (is_object($v)) { + $v = var_export($v, true); + }*/ + $this->assertEquals('Michigan', $v); + } + } + + public function testTransferOfObjectViaWrapping() + { + // make a 'deep client copy' as the original one might have many properties set + $func = wrap_xmlrpc_method($this->client, 'tests.returnPhpObject', array('simple_client_copy' => true, + 'decode_php_objs' => true)); + if ($func == false) { + $this->fail('Registration of tests.returnPhpObject failed'); + } else { + $v = $func(); + $obj = new stdClass(); + $obj->hello = 'world'; + $this->assertEquals($obj, $v); + } + } + + public function testGetCookies() + { + // let server set to us some cookies we tell it + $cookies = array( + //'c1' => array(), + 'c2' => array('value' => 'c2'), + 'c3' => array('value' => 'c3', 'expires' => time() + 60 * 60 * 24 * 30), + 'c4' => array('value' => 'c4', 'expires' => time() + 60 * 60 * 24 * 30, 'path' => '/'), + 'c5' => array('value' => 'c5', 'expires' => time() + 60 * 60 * 24 * 30, 'path' => '/', 'domain' => 'localhost'), + ); + $cookiesval = php_xmlrpc_encode($cookies); + $m = new xmlrpcmsg('examples.setcookies', array($cookiesval)); + $r = $this->send($m, 0, true); + if ($r) { + $v = $r->value(); + $this->assertEquals(1, $v->scalarval()); + // now check if we decoded the cookies as we had set them + $rcookies = $r->cookies(); + // remove extra cookies which might have been set by proxies + foreach ($rcookies as $c => $v) { + if (!in_array($c, array('c2', 'c3', 'c4', 'c5'))) { + unset($rcookies[$c]); + } + // Seems like we get this when using php-fpm and php 5.5+ ... + if (isset($rcookies[$c]['Max-Age'])) { + unset($rcookies[$c]['Max-Age']); + } + } + foreach ($cookies as $c => $v) { + // format for date string in cookies: 'Mon, 31 Oct 2005 13:50:56 GMT' + // but PHP versions differ on that, some use 'Mon, 31-Oct-2005 13:50:56 GMT'... + if (isset($v['expires'])) { + if (isset($rcookies[$c]['expires']) && strpos($rcookies[$c]['expires'], '-')) { + $cookies[$c]['expires'] = gmdate('D, d\-M\-Y H:i:s \G\M\T', $cookies[$c]['expires']); + } else { + $cookies[$c]['expires'] = gmdate('D, d M Y H:i:s \G\M\T', $cookies[$c]['expires']); + } + } + } + + $this->assertEquals($cookies, $rcookies); + } + } + + public function testSetCookies() + { + // let server set to us some cookies we tell it + $cookies = array( + 'c0' => null, + 'c1' => 1, + 'c2' => '2 3', + 'c3' => '!@#$%^&*()_+|}{":?><,./\';[]\\=-', + ); + $m = new xmlrpcmsg('examples.getcookies', array()); + foreach ($cookies as $cookie => $val) { + $this->client->setCookie($cookie, $val); + $cookies[$cookie] = (string)$cookies[$cookie]; + } + $r = $this->client->send($m, $this->timeout, $this->method); + $this->assertEquals(0, $r->faultCode(), 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); + if (!$r->faultCode()) { + $v = $r->value(); + $v = php_xmlrpc_decode($v); + + // take care for the extra cookie used for coverage collection + if (isset($v['PHPUNIT_SELENIUM_TEST_ID'])) { + unset($v['PHPUNIT_SELENIUM_TEST_ID']); + } + + // on IIS and Apache getallheaders returns something slightly different... + $this->assertEquals($cookies, $v); + } + } + + public function testServerComments() + { + $m = new xmlrpcmsg('tests.xmlrpcServerMethodsContainer.debugMessageGenerator', array( + new xmlrpcval('hello world', 'string'), + )); + $r = $this->send($m, 0, true); + $this->assertContains('hello world', $r->raw_data); + } + + public function testSendTwiceSameMsg() + { + $m = new xmlrpcmsg('examples.stringecho', array( + new xmlrpcval('hello world', 'string'), + )); + $v1 = $this->send($m); + $v2 = $this->send($m); + if ($v1 && $v2) { + $this->assertEquals($v1, $v2); + } + } +} diff --git a/lib/phpxmlrpc/tests/4LocalhostMultiTest.php b/lib/phpxmlrpc/tests/4LocalhostMultiTest.php new file mode 100644 index 0000000..e5d365a --- /dev/null +++ b/lib/phpxmlrpc/tests/4LocalhostMultiTest.php @@ -0,0 +1,215 @@ +$method(); + } + /*if ($this->_failed) + { + break; + }*/ + } + } + + function testDeflate() + { + if(!function_exists('gzdeflate')) + { + $this->markTestSkipped('Zlib missing: cannot test deflate functionality'); + return; + } + $this->client->accepted_compression = array('deflate'); + $this->client->request_compression = 'deflate'; + $this->_runtests(); + } + + function testGzip() + { + if(!function_exists('gzdeflate')) + { + $this->markTestSkipped('Zlib missing: cannot test gzip functionality'); + return; + } + $this->client->accepted_compression = array('gzip'); + $this->client->request_compression = 'gzip'; + $this->_runtests(); + } + + function testKeepAlives() + { + if(!function_exists('curl_init')) + { + $this->markTestSkipped('CURL missing: cannot test http 1.1'); + return; + } + $this->method = 'http11'; + $this->client->keepalive = true; + $this->_runtests(); + } + + function testProxy() + { + if ($this->args['PROXYSERVER']) + { + $this->client->setProxy($this->args['PROXYSERVER'], $this->args['PROXYPORT']); + $this->_runtests(); + } + else + $this->markTestSkipped('PROXY definition missing: cannot test proxy'); + } + + function testHttp11() + { + if(!function_exists('curl_init')) + { + $this->markTestSkipped('CURL missing: cannot test http 1.1'); + return; + } + $this->method = 'http11'; // not an error the double assignment! + $this->client->method = 'http11'; + //$this->client->verifyhost = 0; + //$this->client->verifypeer = 0; + $this->client->keepalive = false; + $this->_runtests(); + } + + function testHttp11Gzip() + { + if(!function_exists('curl_init')) + { + $this->markTestSkipped('CURL missing: cannot test http 1.1'); + return; + } + $this->method = 'http11'; // not an error the double assignment! + $this->client->method = 'http11'; + $this->client->keepalive = false; + $this->client->accepted_compression = array('gzip'); + $this->client->request_compression = 'gzip'; + $this->_runtests(); + } + + function testHttp11Deflate() + { + if(!function_exists('curl_init')) + { + $this->markTestSkipped('CURL missing: cannot test http 1.1'); + return; + } + $this->method = 'http11'; // not an error the double assignment! + $this->client->method = 'http11'; + $this->client->keepalive = false; + $this->client->accepted_compression = array('deflate'); + $this->client->request_compression = 'deflate'; + $this->_runtests(); + } + + function testHttp11Proxy() + { + if(!function_exists('curl_init')) + { + $this->markTestSkipped('CURL missing: cannot test http 1.1 w. proxy'); + return; + } + else if ($this->args['PROXYSERVER'] == '') + { + $this->markTestSkipped('PROXY definition missing: cannot test proxy w. http 1.1'); + return; + } + $this->method = 'http11'; // not an error the double assignment! + $this->client->method = 'http11'; + $this->client->setProxy($this->args['PROXYSERVER'], $this->args['PROXYPORT']); + //$this->client->verifyhost = 0; + //$this->client->verifypeer = 0; + $this->client->keepalive = false; + $this->_runtests(); + } + + function testHttps() + { + if(!function_exists('curl_init')) + { + $this->markTestSkipped('CURL missing: cannot test https functionality'); + return; + } + $this->client->server = $this->args['HTTPSSERVER']; + $this->method = 'https'; + $this->client->method = 'https'; + $this->client->path = $this->args['HTTPSURI']; + $this->client->setSSLVerifyPeer(!$this->args['HTTPSIGNOREPEER']); + $this->client->setSSLVerifyHost($this->args['HTTPSVERIFYHOST']); + $this->client->setSSLVersion($this->args['SSLVERSION']); + $this->_runtests(); + } + + function testHttpsProxy() + { + if(!function_exists('curl_init')) + { + $this->markTestSkipped('CURL missing: cannot test https functionality'); + return; + } + else if ($this->args['PROXYSERVER'] == '') + { + $this->markTestSkipped('PROXY definition missing: cannot test proxy w. http 1.1'); + return; + } + $this->client->server = $this->args['HTTPSSERVER']; + $this->method = 'https'; + $this->client->method = 'https'; + $this->client->setProxy($this->args['PROXYSERVER'], $this->args['PROXYPORT']); + $this->client->path = $this->args['HTTPSURI']; + $this->client->setSSLVerifyPeer(!$this->args['HTTPSIGNOREPEER']); + $this->client->setSSLVerifyHost($this->args['HTTPSVERIFYHOST']); + $this->client->setSSLVersion($this->args['SSLVERSION']); + $this->_runtests(); + } + + function testUTF8Responses() + { + //$this->client->path = strpos($URI, '?') === null ? $URI.'?RESPONSE_ENCODING=UTF-8' : $URI.'&RESPONSE_ENCODING=UTF-8'; + $this->client->path = $this->args['URI'].'?RESPONSE_ENCODING=UTF-8'; + $this->_runtests(); + } + + function testUTF8Requests() + { + $this->client->request_charset_encoding = 'UTF-8'; + $this->_runtests(); + } + + function testISOResponses() + { + //$this->client->path = strpos($URI, '?') === null ? $URI.'?RESPONSE_ENCODING=UTF-8' : $URI.'&RESPONSE_ENCODING=UTF-8'; + $this->client->path = $this->args['URI'].'?RESPONSE_ENCODING=ISO-8859-1'; + $this->_runtests(); + } + + function testISORequests() + { + $this->client->request_charset_encoding = 'ISO-8859-1'; + $this->_runtests(); + } +} diff --git a/lib/phpxmlrpc/tests/5DemofilesTest.php b/lib/phpxmlrpc/tests/5DemofilesTest.php new file mode 100644 index 0000000..3cbb5b4 --- /dev/null +++ b/lib/phpxmlrpc/tests/5DemofilesTest.php @@ -0,0 +1,76 @@ +args = argParser::getArgs(); + + $this->baseUrl = $this->args['LOCALSERVER'] . str_replace( '/demo/server/server.php', '/demo/', $this->args['URI'] ); + + $this->coverageScriptUrl = 'http://' . $this->args['LOCALSERVER'] . '/' . str_replace( '/demo/server/server.php', 'tests/phpunit_coverage.php', $this->args['URI'] ); + } + + public function testAgeSort() + { + $page = $this->request('client/agesort.php'); + } + + public function testGetStateName() + { + $page = $this->request('client/getstatename.php'); + $page = $this->request('client/getstatename.php', 'POST', array('stateno' => '1')); + } + + public function testIntrospect() + { + $page = $this->request('client/introspect.php'); + } + + public function testMail() + { + $page = $this->request('client/mail.php'); + $page = $this->request('client/mail.php', 'POST', array( + "mailto" => '', + "mailsub" => '', + "mailmsg" => '', + "mailfrom" => '', + "mailcc" => '', + "mailbcc" => '', + )); + } + + public function testProxy() + { + $page = $this->request('client/proxy.php', 'GET', null, true); + } + + public function testWhich() + { + $page = $this->request('client/which.php'); + } + + public function testWrap() + { + $page = $this->request('client/wrap.php'); + } + + public function testDiscussServer() + { + $page = $this->request('server/discuss.php'); + $this->assertContains('faultCode', $page); + $this->assertRegexp('#10(5|3)#', $page); + } + + public function testProxyServer() + { + $page = $this->request('server/proxy.php'); + $this->assertContains('faultCode', $page); + $this->assertRegexp('#10(5|3)#', $page); + } +} diff --git a/lib/phpxmlrpc/tests/6DebuggerTest.php b/lib/phpxmlrpc/tests/6DebuggerTest.php new file mode 100644 index 0000000..db0e850 --- /dev/null +++ b/lib/phpxmlrpc/tests/6DebuggerTest.php @@ -0,0 +1,37 @@ +args = argParser::getArgs(); + + $this->baseUrl = $this->args['LOCALSERVER'] . str_replace( '/demo/server/server.php', '/debugger/', $this->args['URI'] ); + + $this->coverageScriptUrl = 'http://' . $this->args['LOCALSERVER'] . '/' . str_replace( '/demo/server/server.php', 'tests/phpunit_coverage.php', $this->args['URI'] ); + } + + public function testIndex() + { + $page = $this->request('index.php'); + } + + public function testController() + { + $page = $this->request('controller.php'); + } + + /** + * @todo test: + * - list methods + * - describe a method + * - execute a method + * - wrap a method + */ + public function testAction() + { + $page = $this->request('action.php'); + } +} diff --git a/lib/phpxmlrpc/tests/7ExtraTest.php b/lib/phpxmlrpc/tests/7ExtraTest.php new file mode 100644 index 0000000..14488e8 --- /dev/null +++ b/lib/phpxmlrpc/tests/7ExtraTest.php @@ -0,0 +1,23 @@ +args = argParser::getArgs(); + + $this->baseUrl = $this->args['LOCALSERVER'] . str_replace( '/demo/server/server.php', '/tests/', $this->args['URI'] ); + + $this->coverageScriptUrl = 'http://' . $this->args['LOCALSERVER'] . '/' . str_replace( '/demo/server/server.php', 'tests/phpunit_coverage.php', $this->args['URI'] ); + } + + public function testVerifyCompat() + { + $page = $this->request('verify_compat.php'); + } +} \ No newline at end of file diff --git a/lib/phpxmlrpc/tests/LocalFileTestCase.php b/lib/phpxmlrpc/tests/LocalFileTestCase.php new file mode 100644 index 0000000..59818c8 --- /dev/null +++ b/lib/phpxmlrpc/tests/LocalFileTestCase.php @@ -0,0 +1,80 @@ +testId = get_class($this) . '__' . $this->getName(); + + if ($result === NULL) { + $result = $this->createResult(); + } + + $this->collectCodeCoverageInformation = $result->getCollectCodeCoverageInformation(); + + parent::run($result); + + if ($this->collectCodeCoverageInformation) { + $coverage = new PHPUnit_Extensions_SeleniumCommon_RemoteCoverage( + $this->coverageScriptUrl, + $this->testId + ); + $result->getCodeCoverage()->append( + $coverage->get(), $this + ); + } + + // do not call this before to give the time to the Listeners to run + //$this->getStrategy()->endOfTest($this->session); + + return $result; + } + + protected function request($file, $method = 'GET', $payload = '', $emptyPageOk = false) + { + $url = $this->baseUrl . $file; + + $ch = curl_init($url); + curl_setopt_array($ch, array( + CURLOPT_RETURNTRANSFER => true, + CURLOPT_FAILONERROR => true + )); + if ($method == 'POST') + { + curl_setopt_array($ch, array( + CURLOPT_POST => true, + CURLOPT_POSTFIELDS => $payload + )); + } + if ($this->collectCodeCoverageInformation) + { + curl_setopt($ch, CURLOPT_COOKIE, 'PHPUNIT_SELENIUM_TEST_ID=true'); + } + if ($this->args['DEBUG'] > 0) { + curl_setopt($ch, CURLOPT_VERBOSE, 1); + } + $page = curl_exec($ch); + curl_close($ch); + + $this->assertNotFalse($page); + if (!$emptyPageOk) { + $this->assertNotEquals('', $page); + } + $this->assertNotContains('Fatal error', $page); + $this->assertNotContains('Notice:', $page); + + return $page; + } + +} diff --git a/lib/phpxmlrpc/tests/benchmark.php b/lib/phpxmlrpc/tests/benchmark.php new file mode 100644 index 0000000..43cbc42 --- /dev/null +++ b/lib/phpxmlrpc/tests/benchmark.php @@ -0,0 +1,311 @@ + $data1, 'one' => $data1, 'two' => $data1, 'three' => $data1, 'four' => $data1, 'five' => $data1, 'six' => $data1, 'seven' => $data1, 'eight' => $data1, 'nine' => $data1); +$data = array($data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2); +$keys = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'); + +// Begin execution + +$test_results = array(); +$is_web = isset($_SERVER['REQUEST_METHOD']); +$xd = extension_loaded('xdebug') && ini_get('xdebug.profiler_enable'); +if ($xd) { + $num_tests = 1; +} else { + $num_tests = 10; +} + +$title = 'XML-RPC Benchmark Tests'; + +if ($is_web) { + echo "\n\n\n$title\n\n\n

    $title

    \n
    \n";
    +} else {
    +    echo "$title\n\n";
    +}
    +
    +if ($is_web) {
    +    echo "

    Using lib version: " . PhpXmlRpc::$xmlrpcVersion . " on PHP version: " . phpversion() . "

    \n"; + if ($xd) { + echo "

    XDEBUG profiling enabled: skipping remote tests. Trace file is: " . htmlspecialchars(xdebug_get_profiler_filename()) . "

    \n"; + } + flush(); + ob_flush(); +} else { + echo "Using lib version: " . PhpXmlRpc::$xmlrpcVersion . " on PHP version: " . phpversion() . "\n"; + if ($xd) { + echo "XDEBUG profiling enabled: skipping remote tests\nTrace file is: " . xdebug_get_profiler_filename() . "\n"; + } +} + +// test 'manual style' data encoding vs. 'automatic style' encoding +begin_test('Data encoding (large array)', 'manual encoding'); +for ($i = 0; $i < $num_tests; $i++) { + $vals = array(); + for ($j = 0; $j < 10; $j++) { + $valarray = array(); + foreach ($data[$j] as $key => $val) { + $values = array(); + $values[] = new Value($val[0], 'int'); + $values[] = new Value($val[1], 'double'); + $values[] = new Value($val[2], 'string'); + $values[] = new Value($val[3], 'boolean'); + $values[] = new Value($val[4], 'dateTime.iso8601'); + $values[] = new Value($val[5], 'int'); + $values[] = new Value($val[6], 'double'); + $values[] = new Value($val[7], 'string'); + $values[] = new Value($val[8], 'boolean'); + $values[] = new Value($val[9], 'dateTime.iso8601'); + $valarray[$key] = new Value($values, 'array'); + } + $vals[] = new Value($valarray, 'struct'); + } + $value = new Value($vals, 'array'); + $out = $value->serialize(); +} +end_test('Data encoding (large array)', 'manual encoding', $out); + +begin_test('Data encoding (large array)', 'automatic encoding'); +$encoder = new Encoder(); +for ($i = 0; $i < $num_tests; $i++) { + $value = $encoder->encode($data, array('auto_dates')); + $out = $value->serialize(); +} +end_test('Data encoding (large array)', 'automatic encoding', $out); + +if (function_exists('xmlrpc_set_type')) { + begin_test('Data encoding (large array)', 'xmlrpc-epi encoding'); + for ($i = 0; $i < $num_tests; $i++) { + for ($j = 0; $j < 10; $j++) { + foreach ($keys as $k) { + xmlrpc_set_type($data[$j][$k][4], 'datetime'); + xmlrpc_set_type($data[$j][$k][8], 'datetime'); + } + } + $out = xmlrpc_encode($data); + } + end_test('Data encoding (large array)', 'xmlrpc-epi encoding', $out); +} + +// test 'old style' data decoding vs. 'automatic style' decoding +$dummy = new Request(''); +$out = new Response($value); +$in = '' . "\n" . $out->serialize(); + +begin_test('Data decoding (large array)', 'manual decoding'); +for ($i = 0; $i < $num_tests; $i++) { + $response = $dummy->ParseResponse($in, true); + $value = $response->value(); + $result = array(); + foreach($value as $val1) { + $out = array(); + foreach($val1 as $name => $val) { + $out[$name] = array(); + foreach($val as $data) { + $out[$name][] = $data->scalarval(); + } + } + $result[] = $out; + } +} +end_test('Data decoding (large array)', 'manual decoding', $result); + +begin_test('Data decoding (large array)', 'manual decoding deprecated'); +for ($i = 0; $i < $num_tests; $i++) { + $response = $dummy->ParseResponse($in, true); + $value = $response->value(); + $result = array(); + $l = $value->arraysize(); + for ($k = 0; $k < $l; $k++) { + $val1 = $value->arraymem($k); + $out = array(); + while (list($name, $val) = $val1->structeach()) { + $out[$name] = array(); + $m = $val->arraysize(); + for ($j = 0; $j < $m; $j++) { + $data = $val->arraymem($j); + $out[$name][] = $data->scalarval(); + } + } // while + $result[] = $out; + } +} +end_test('Data decoding (large array)', 'manual decoding deprecated', $result); + +begin_test('Data decoding (large array)', 'automatic decoding'); +for ($i = 0; $i < $num_tests; $i++) { + $response = $dummy->ParseResponse($in, true, 'phpvals'); + $value = $response->value(); +} +end_test('Data decoding (large array)', 'automatic decoding', $value); + +if (function_exists('xmlrpc_decode')) { + begin_test('Data decoding (large array)', 'xmlrpc-epi decoding'); + for ($i = 0; $i < $num_tests; $i++) { + $response = $dummy->ParseResponse($in, true, 'xml'); + $value = xmlrpc_decode($response->value()); + } + end_test('Data decoding (large array)', 'xmlrpc-epi decoding', $value); +} + +if (!$xd) { + + /// test multicall vs. many calls vs. keep-alives + $encoder = new Encoder(); + $value = $encoder->encode($data1, array('auto_dates')); + $req = new Request('interopEchoTests.echoValue', array($value)); + $reqs = array(); + for ($i = 0; $i < 25; $i++) { + $reqs[] = $req; + } + $server = explode(':', $args['LOCALSERVER']); + if (count($server) > 1) { + $srv = $server[1] . '://' . $server[0] . $args['URI']; + $c = new Client($args['URI'], $server[0], $server[1]); + } else { + $srv = $args['LOCALSERVER'] . $args['URI']; + $c = new Client($args['URI'], $args['LOCALSERVER']); + } + // do not interfere with http compression + $c->accepted_compression = array(); + //$c->debug=true; + + $testName = "Repeated send (small array) to $srv"; + + if (function_exists('gzinflate')) { + $c->accepted_compression = null; + } + begin_test($testName, 'http 10'); + $response = array(); + for ($i = 0; $i < 25; $i++) { + $resp = $c->send($req); + $response[] = $resp->value(); + } + end_test($testName, 'http 10', $response); + + if (function_exists('curl_init')) { + begin_test($testName, 'http 11 w. keep-alive'); + $response = array(); + for ($i = 0; $i < 25; $i++) { + $resp = $c->send($req, 10, 'http11'); + $response[] = $resp->value(); + } + end_test($testName, 'http 11 w. keep-alive', $response); + + $c->keepalive = false; + begin_test($testName, 'http 11'); + $response = array(); + for ($i = 0; $i < 25; $i++) { + $resp = $c->send($req, 10, 'http11'); + $response[] = $resp->value(); + } + end_test($testName, 'http 11', $response); + } + + begin_test($testName, 'multicall'); + $response = $c->send($reqs); + foreach ($response as $key => & $val) { + $val = $val->value(); + } + end_test($testName, 'multicall', $response); + + if (function_exists('gzinflate')) { + $c->accepted_compression = array('gzip'); + $c->request_compression = 'gzip'; + + begin_test($testName, 'http 10 w. compression'); + $response = array(); + for ($i = 0; $i < 25; $i++) { + $resp = $c->send($req); + $response[] = $resp->value(); + } + end_test($testName, 'http 10 w. compression', $response); + + if (function_exists('curl_init')) { + begin_test($testName, 'http 11 w. keep-alive and compression'); + $response = array(); + for ($i = 0; $i < 25; $i++) { + $resp = $c->send($req, 10, 'http11'); + $response[] = $resp->value(); + } + end_test($testName, 'http 11 w. keep-alive and compression', $response); + + $c->keepalive = false; + begin_test($testName, 'http 11 w. compression'); + $response = array(); + for ($i = 0; $i < 25; $i++) { + $resp = $c->send($req, 10, 'http11'); + $response[] = $resp->value(); + } + end_test($testName, 'http 11 w. compression', $response); + } + + begin_test($testName, 'multicall w. compression'); + $response = $c->send($reqs); + foreach ($response as $key => & $val) { + $val = $val->value(); + } + end_test($testName, 'multicall w. compression', $response); + } +} // end of 'if no xdebug profiling' + + +echo "\n"; +foreach ($test_results as $test => $results) { + echo "\nTEST: $test\n"; + foreach ($results as $case => $data) { + echo " $case: {$data['time']} secs - Output data CRC: " . crc32(serialize($data['result'])) . "\n"; + } +} + +if ($is_web) { + echo "\n
    \n\n\n"; +} diff --git a/lib/phpxmlrpc/tests/ci/travis/apache_vhost b/lib/phpxmlrpc/tests/ci/travis/apache_vhost new file mode 100644 index 0000000..87841d6 --- /dev/null +++ b/lib/phpxmlrpc/tests/ci/travis/apache_vhost @@ -0,0 +1,68 @@ +# Configuration file for Apache running on Travis. +# PHP setup in FCGI mode + + + + DocumentRoot %TRAVIS_BUILD_DIR% + + ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log" + CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined + + + Options FollowSymLinks MultiViews ExecCGI + AllowOverride All + Order deny,allow + Allow from all + + + # Wire up Apache to use Travis CI's php-fpm. + + AddHandler php5-fcgi .php + Action php5-fcgi /php5-fcgi + Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi + FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -pass-header Authorization + + + + + + + + + DocumentRoot %TRAVIS_BUILD_DIR% + + ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log" + CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined + + + Options FollowSymLinks MultiViews ExecCGI + AllowOverride All + Order deny,allow + Allow from all + + + # Wire up Apache to use Travis CI's php-fpm. + + AddHandler php5-fcgi .php + Action php5-fcgi /php5-fcgi + Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi + #FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -pass-header Authorization + + + SSLEngine on + # This cert is bundled by default in Ubuntu + SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem + SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key + + + SSLOptions +StdEnvVars + + + BrowserMatch "MSIE [2-6]" \ + nokeepalive ssl-unclean-shutdown \ + downgrade-1.0 force-response-1.0 + BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown + + + + diff --git a/lib/phpxmlrpc/tests/ci/travis/apache_vhost_hhvm b/lib/phpxmlrpc/tests/ci/travis/apache_vhost_hhvm new file mode 100644 index 0000000..63e57da --- /dev/null +++ b/lib/phpxmlrpc/tests/ci/travis/apache_vhost_hhvm @@ -0,0 +1,74 @@ +# Configuration file for Apache running on Travis. +# HHVM setup in FCGI mode + + + + DocumentRoot %TRAVIS_BUILD_DIR% + + ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log" + CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined + + + Options FollowSymLinks MultiViews ExecCGI + AllowOverride All + Order deny,allow + Allow from all + + + # Configure Apache for HHVM FastCGI. + # See https://github.com/facebook/hhvm/wiki/fastcgi + + + SetHandler hhvm-php-extension + + Alias /hhvm /hhvm + Action hhvm-php-extension /hhvm virtual + FastCgiExternalServer /hhvm -host 127.0.0.1:9000 -pass-header Authorization -idle-timeout 300 + + + + + + + + + DocumentRoot %TRAVIS_BUILD_DIR% + + ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log" + CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined + + + Options FollowSymLinks MultiViews ExecCGI + AllowOverride All + Order deny,allow + Allow from all + + + # Configure Apache for HHVM FastCGI. + # See https://github.com/facebook/hhvm/wiki/fastcgi + + + SetHandler hhvm-php-extension + + Alias /hhvm /hhvm + Action hhvm-php-extension /hhvm virtual + #FastCgiExternalServer /hhvm -host 127.0.0.1:9000 -pass-header Authorization -idle-timeout 300 + + + SSLEngine on + # This cert is bundled by default in Ubuntu + SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem + SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key + + + SSLOptions +StdEnvVars + + + BrowserMatch "MSIE [2-6]" \ + nokeepalive ssl-unclean-shutdown \ + downgrade-1.0 force-response-1.0 + BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown + + + + diff --git a/lib/phpxmlrpc/tests/ci/travis/privoxy b/lib/phpxmlrpc/tests/ci/travis/privoxy new file mode 100644 index 0000000..67d8ff8 --- /dev/null +++ b/lib/phpxmlrpc/tests/ci/travis/privoxy @@ -0,0 +1 @@ +listen-address 127.0.0.1:8080 diff --git a/lib/phpxmlrpc/tests/ci/travis/setup_apache.sh b/lib/phpxmlrpc/tests/ci/travis/setup_apache.sh new file mode 100644 index 0000000..a39d676 --- /dev/null +++ b/lib/phpxmlrpc/tests/ci/travis/setup_apache.sh @@ -0,0 +1,11 @@ +#!/bin/sh + +# set up Apache for php-fpm +# @see https://github.com/travis-ci/travis-ci.github.com/blob/master/docs/user/languages/php.md#apache--php + +sudo a2enmod rewrite actions fastcgi alias ssl + +# configure apache virtual hosts +sudo cp -f tests/ci/travis/apache_vhost /etc/apache2/sites-available/default +sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/default +sudo service apache2 restart diff --git a/lib/phpxmlrpc/tests/ci/travis/setup_apache_hhvm.sh b/lib/phpxmlrpc/tests/ci/travis/setup_apache_hhvm.sh new file mode 100644 index 0000000..a72941d --- /dev/null +++ b/lib/phpxmlrpc/tests/ci/travis/setup_apache_hhvm.sh @@ -0,0 +1,11 @@ +#!/bin/sh + +# set up Apache for hhvm-fcgi +# @see https://github.com/travis-ci/travis-ci.github.com/blob/master/docs/user/languages/php.md#apache--php + +sudo a2enmod rewrite actions fastcgi alias ssl + +# configure apache virtual hosts +sudo cp -f tests/ci/travis/apache_vhost_hhvm /etc/apache2/sites-available/default +sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/default +sudo service apache2 restart diff --git a/lib/phpxmlrpc/tests/ci/travis/setup_hhvm.sh b/lib/phpxmlrpc/tests/ci/travis/setup_hhvm.sh new file mode 100644 index 0000000..289e750 --- /dev/null +++ b/lib/phpxmlrpc/tests/ci/travis/setup_hhvm.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +# start HHVM +hhvm -m daemon -vServer.Type=fastcgi -vServer.Port=9000 -vServer.FixPathInfo=true diff --git a/lib/phpxmlrpc/tests/ci/travis/setup_php_fpm.sh b/lib/phpxmlrpc/tests/ci/travis/setup_php_fpm.sh new file mode 100644 index 0000000..7788fdc --- /dev/null +++ b/lib/phpxmlrpc/tests/ci/travis/setup_php_fpm.sh @@ -0,0 +1,11 @@ +#!/bin/sh + +# enable php-fpm +sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf +# work around travis issue #3385 +if [ "$TRAVIS_PHP_VERSION" = "7.0" -a -n "$(ls -A ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d)" ]; then + sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/www.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/www.conf +fi +echo "cgi.fix_pathinfo = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini +echo "always_populate_raw_post_data = -1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini +~/.phpenv/versions/$(phpenv version-name)/sbin/php-fpm diff --git a/lib/phpxmlrpc/tests/ci/travis/setup_privoxy.sh b/lib/phpxmlrpc/tests/ci/travis/setup_privoxy.sh new file mode 100644 index 0000000..12e0e61 --- /dev/null +++ b/lib/phpxmlrpc/tests/ci/travis/setup_privoxy.sh @@ -0,0 +1,6 @@ +#!/bin/sh + +# configure privoxy + +sudo cp -f tests/ci/travis/privoxy /etc/privoxy/config +sudo service privoxy restart diff --git a/lib/phpxmlrpc/tests/parse_args.php b/lib/phpxmlrpc/tests/parse_args.php new file mode 100644 index 0000000..6660b9e --- /dev/null +++ b/lib/phpxmlrpc/tests/parse_args.php @@ -0,0 +1,124 @@ + 0, + 'LOCALSERVER' => 'localhost', + 'HTTPSSERVER' => 'gggeek.ssl.altervista.org', + 'HTTPSURI' => '/sw/xmlrpc/demo/server/server.php', + 'HTTPSIGNOREPEER' => false, + 'HTTPSVERIFYHOST' => 2, + 'SSLVERSION' => 0, + 'PROXYSERVER' => null, + 'NOPROXY' => false, + 'LOCALPATH' => __DIR__, + ); + + // check for command line vs web page input params + if (!isset($_SERVER['REQUEST_METHOD'])) { + if (isset($argv)) { + foreach ($argv as $param) { + $param = explode('=', $param); + if (count($param) > 1) { + $pname = strtoupper(ltrim($param[0], '-')); + $$pname = $param[1]; + } + } + } + } else { + // NB: we might as well consider using $_GET stuff later on... + extract($_GET); + extract($_POST); + } + + if (isset($DEBUG)) { + $args['DEBUG'] = intval($DEBUG); + } + if (isset($LOCALSERVER)) { + $args['LOCALSERVER'] = $LOCALSERVER; + } else { + if (isset($HTTP_HOST)) { + $args['LOCALSERVER'] = $HTTP_HOST; + } elseif (isset($_SERVER['HTTP_HOST'])) { + $args['LOCALSERVER'] = $_SERVER['HTTP_HOST']; + } + } + if (isset($HTTPSSERVER)) { + $args['HTTPSSERVER'] = $HTTPSSERVER; + } + if (isset($HTTPSURI)) { + $args['HTTPSURI'] = $HTTPSURI; + } + if (isset($HTTPSIGNOREPEER)) { + $args['HTTPSIGNOREPEER'] = (bool)$HTTPSIGNOREPEER; + } + if (isset($HTTPSVERIFYHOST)) { + $args['HTTPSVERIFYHOST'] = (int)$HTTPSVERIFYHOST; + } + if (isset($SSLVERSION)) { + $args['SSLVERSION'] = (int)$SSLVERSION; + } + if (isset($PROXY)) { + $arr = explode(':', $PROXY); + $args['PROXYSERVER'] = $arr[0]; + if (count($arr) > 1) { + $args['PROXYPORT'] = $arr[1]; + } else { + $args['PROXYPORT'] = 8080; + } + } + // used to silence testsuite warnings about proxy code not being tested + if (isset($NOPROXY)) { + $args['NOPROXY'] = true; + } + if (!isset($URI)) { + // GUESTIMATE the url of local demo server + // play nice to php 3 and 4-5 in retrieving URL of server.php + /// @todo filter out query string from REQUEST_URI + if (isset($REQUEST_URI)) { + $URI = str_replace('/tests/testsuite.php', '/demo/server/server.php', $REQUEST_URI); + $URI = str_replace('/testsuite.php', '/server.php', $URI); + $URI = str_replace('/tests/benchmark.php', '/demo/server/server.php', $URI); + $URI = str_replace('/benchmark.php', '/server.php', $URI); + } elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['REQUEST_METHOD'])) { + $URI = str_replace('/tests/testsuite.php', '/demo/server/server.php', $_SERVER['PHP_SELF']); + $URI = str_replace('/testsuite.php', '/server.php', $URI); + $URI = str_replace('/tests/benchmark.php', '/demo/server/server.php', $URI); + $URI = str_replace('/benchmark.php', '/server.php', $URI); + } else { + $URI = '/demo/server/server.php'; + } + } + if ($URI[0] != '/') { + $URI = '/' . $URI; + } + $args['URI'] = $URI; + if (isset($LOCALPATH)) { + $args['LOCALPATH'] = $LOCALPATH; + } + + return $args; + } +} diff --git a/lib/phpxmlrpc/tests/phpunit_coverage.php b/lib/phpxmlrpc/tests/phpunit_coverage.php new file mode 100644 index 0000000..ae7b998 --- /dev/null +++ b/lib/phpxmlrpc/tests/phpunit_coverage.php @@ -0,0 +1,16 @@ + + + + + PHP XMLRPC compatibility assessment + + + +

    PHPXMLRPC compatibility assessment with the current PHP install

    +

    For phpxmlrpc version 4.0 or later

    + +

    Server usage

    + + + + + + + + + $result) { + echo '\n"; + } + ?> + +
    TestResult
    ' . htmlspecialchars($test) . '' . htmlspecialchars($result['description']) . "
    +

    Client usage

    + + + + + + + + + $result) { + echo '\n"; + } + ?> + +
    TestResult
    ' . htmlspecialchars($test) . '' . htmlspecialchars($result['description']) . "
    + + diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc new file mode 100644 index 0000000..0c3702e --- /dev/null +++ b/lib/xmlrpc.inc @@ -0,0 +1,3640 @@ + +// $Id: xmlrpc.inc,v 1.158 2007/03/01 21:21:02 ggiunta Exp $ + +// Copyright (c) 1999,2000,2002 Edd Dumbill. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// +// * Neither the name of the "XML-RPC for PHP" nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +// OF THE POSSIBILITY OF SUCH DAMAGE. + + if(!function_exists('xml_parser_create')) + { + // For PHP 4 onward, XML functionality is always compiled-in on windows: + // no more need to dl-open it. It might have been compiled out on *nix... + if(strtoupper(substr(PHP_OS, 0, 3) != 'WIN')) + { + dl('xml.so'); + } + } + + // Try to be backward compat with php < 4.2 (are we not being nice ?) + $phpversion = phpversion(); + if($phpversion[0] == '4' && $phpversion[2] < 2) + { + // give an opportunity to user to specify where to include other files from + if(!defined('PHP_XMLRPC_COMPAT_DIR')) + { + define('PHP_XMLRPC_COMPAT_DIR',dirname(__FILE__).'/compat/'); + } + if($phpversion[2] == '0') + { + if($phpversion[4] < 6) + { + include(PHP_XMLRPC_COMPAT_DIR.'is_callable.php'); + } + include(PHP_XMLRPC_COMPAT_DIR.'is_scalar.php'); + include(PHP_XMLRPC_COMPAT_DIR.'array_key_exists.php'); + include(PHP_XMLRPC_COMPAT_DIR.'version_compare.php'); + } + include(PHP_XMLRPC_COMPAT_DIR.'var_export.php'); + include(PHP_XMLRPC_COMPAT_DIR.'is_a.php'); + } + + // G. Giunta 2005/01/29: declare global these variables, + // so that xmlrpc.inc will work even if included from within a function + // Milosch: 2005/08/07 - explicitly request these via $GLOBALS where used. + $GLOBALS['xmlrpcI4']='i4'; + $GLOBALS['xmlrpcInt']='int'; + $GLOBALS['xmlrpcBoolean']='boolean'; + $GLOBALS['xmlrpcDouble']='double'; + $GLOBALS['xmlrpcString']='string'; + $GLOBALS['xmlrpcDateTime']='dateTime.iso8601'; + $GLOBALS['xmlrpcBase64']='base64'; + $GLOBALS['xmlrpcArray']='array'; + $GLOBALS['xmlrpcStruct']='struct'; + $GLOBALS['xmlrpcValue']='undefined'; + + $GLOBALS['xmlrpcTypes']=array( + $GLOBALS['xmlrpcI4'] => 1, + $GLOBALS['xmlrpcInt'] => 1, + $GLOBALS['xmlrpcBoolean'] => 1, + $GLOBALS['xmlrpcString'] => 1, + $GLOBALS['xmlrpcDouble'] => 1, + $GLOBALS['xmlrpcDateTime'] => 1, + $GLOBALS['xmlrpcBase64'] => 1, + $GLOBALS['xmlrpcArray'] => 2, + $GLOBALS['xmlrpcStruct'] => 3 + ); + + $GLOBALS['xmlrpc_valid_parents'] = array( + 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'), + 'BOOLEAN' => array('VALUE'), + 'I4' => array('VALUE'), + 'INT' => array('VALUE'), + 'STRING' => array('VALUE'), + 'DOUBLE' => array('VALUE'), + 'DATETIME.ISO8601' => array('VALUE'), + 'BASE64' => array('VALUE'), + 'MEMBER' => array('STRUCT'), + 'NAME' => array('MEMBER'), + 'DATA' => array('ARRAY'), + 'ARRAY' => array('VALUE'), + 'STRUCT' => array('VALUE'), + 'PARAM' => array('PARAMS'), + 'METHODNAME' => array('METHODCALL'), + 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'), + 'FAULT' => array('METHODRESPONSE'), + 'NIL' => array('VALUE') // only used when extension activated + ); + + // define extra types for supporting NULL (useful for json or ) + $GLOBALS['xmlrpcNull']='null'; + $GLOBALS['xmlrpcTypes']['null']=1; + + // Not in use anymore since 2.0. Shall we remove it? + /// @deprecated + $GLOBALS['xmlEntities']=array( + 'amp' => '&', + 'quot' => '"', + 'lt' => '<', + 'gt' => '>', + 'apos' => "'" + ); + + // tables used for transcoding different charsets into us-ascii xml + + $GLOBALS['xml_iso88591_Entities']=array(); + $GLOBALS['xml_iso88591_Entities']['in'] = array(); + $GLOBALS['xml_iso88591_Entities']['out'] = array(); + for ($i = 0; $i < 32; $i++) + { + $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i); + $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';'; + } + for ($i = 160; $i < 256; $i++) + { + $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i); + $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';'; + } + + /// @todo add to iso table the characters from cp_1252 range, i.e. 128 to 159. + /// These will NOT be present in true ISO-8859-1, but will save the unwary + /// windows user from sending junk. +/* +$cp1252_to_xmlent = + array( + '\x80'=>'€', '\x81'=>'?', '\x82'=>'‚', '\x83'=>'ƒ', + '\x84'=>'„', '\x85'=>'…', '\x86'=>'†', \x87'=>'‡', + '\x88'=>'ˆ', '\x89'=>'‰', '\x8A'=>'Š', '\x8B'=>'‹', + '\x8C'=>'Œ', '\x8D'=>'?', '\x8E'=>'Ž', '\x8F'=>'?', + '\x90'=>'?', '\x91'=>'‘', '\x92'=>'’', '\x93'=>'“', + '\x94'=>'”', '\x95'=>'•', '\x96'=>'–', '\x97'=>'—', + '\x98'=>'˜', '\x99'=>'™', '\x9A'=>'š', '\x9B'=>'›', + '\x9C'=>'œ', '\x9D'=>'?', '\x9E'=>'ž', '\x9F'=>'Ÿ' + ); +*/ + + $GLOBALS['xmlrpcerr']['unknown_method']=1; + $GLOBALS['xmlrpcstr']['unknown_method']='Unknown method'; + $GLOBALS['xmlrpcerr']['invalid_return']=2; + $GLOBALS['xmlrpcstr']['invalid_return']='Invalid return payload: enable debugging to examine incoming payload'; + $GLOBALS['xmlrpcerr']['incorrect_params']=3; + $GLOBALS['xmlrpcstr']['incorrect_params']='Incorrect parameters passed to method'; + $GLOBALS['xmlrpcerr']['introspect_unknown']=4; + $GLOBALS['xmlrpcstr']['introspect_unknown']="Can't introspect: method unknown"; + $GLOBALS['xmlrpcerr']['http_error']=5; + $GLOBALS['xmlrpcstr']['http_error']="Didn't receive 200 OK from remote server."; + $GLOBALS['xmlrpcerr']['no_data']=6; + $GLOBALS['xmlrpcstr']['no_data']='No data received from server.'; + $GLOBALS['xmlrpcerr']['no_ssl']=7; + $GLOBALS['xmlrpcstr']['no_ssl']='No SSL support compiled in.'; + $GLOBALS['xmlrpcerr']['curl_fail']=8; + $GLOBALS['xmlrpcstr']['curl_fail']='CURL error'; + $GLOBALS['xmlrpcerr']['invalid_request']=15; + $GLOBALS['xmlrpcstr']['invalid_request']='Invalid request payload'; + $GLOBALS['xmlrpcerr']['no_curl']=16; + $GLOBALS['xmlrpcstr']['no_curl']='No CURL support compiled in.'; + $GLOBALS['xmlrpcerr']['server_error']=17; + $GLOBALS['xmlrpcstr']['server_error']='Internal server error'; + $GLOBALS['xmlrpcerr']['multicall_error']=18; + $GLOBALS['xmlrpcstr']['multicall_error']='Received from server invalid multicall response'; + + $GLOBALS['xmlrpcerr']['multicall_notstruct'] = 9; + $GLOBALS['xmlrpcstr']['multicall_notstruct'] = 'system.multicall expected struct'; + $GLOBALS['xmlrpcerr']['multicall_nomethod'] = 10; + $GLOBALS['xmlrpcstr']['multicall_nomethod'] = 'missing methodName'; + $GLOBALS['xmlrpcerr']['multicall_notstring'] = 11; + $GLOBALS['xmlrpcstr']['multicall_notstring'] = 'methodName is not a string'; + $GLOBALS['xmlrpcerr']['multicall_recursion'] = 12; + $GLOBALS['xmlrpcstr']['multicall_recursion'] = 'recursive system.multicall forbidden'; + $GLOBALS['xmlrpcerr']['multicall_noparams'] = 13; + $GLOBALS['xmlrpcstr']['multicall_noparams'] = 'missing params'; + $GLOBALS['xmlrpcerr']['multicall_notarray'] = 14; + $GLOBALS['xmlrpcstr']['multicall_notarray'] = 'params is not an array'; + + $GLOBALS['xmlrpcerr']['cannot_decompress']=103; + $GLOBALS['xmlrpcstr']['cannot_decompress']='Received from server compressed HTTP and cannot decompress'; + $GLOBALS['xmlrpcerr']['decompress_fail']=104; + $GLOBALS['xmlrpcstr']['decompress_fail']='Received from server invalid compressed HTTP'; + $GLOBALS['xmlrpcerr']['dechunk_fail']=105; + $GLOBALS['xmlrpcstr']['dechunk_fail']='Received from server invalid chunked HTTP'; + $GLOBALS['xmlrpcerr']['server_cannot_decompress']=106; + $GLOBALS['xmlrpcstr']['server_cannot_decompress']='Received from client compressed HTTP request and cannot decompress'; + $GLOBALS['xmlrpcerr']['server_decompress_fail']=107; + $GLOBALS['xmlrpcstr']['server_decompress_fail']='Received from client invalid compressed HTTP request'; + + // The charset encoding used by the server for received messages and + // by the client for received responses when received charset cannot be determined + // or is not supported + $GLOBALS['xmlrpc_defencoding']='UTF-8'; + + // The encoding used internally by PHP. + // String values received as xml will be converted to this, and php strings will be converted to xml + // as if having been coded with this + $GLOBALS['xmlrpc_internalencoding']='ISO-8859-1'; + + $GLOBALS['xmlrpcName']='XML-RPC for PHP'; + $GLOBALS['xmlrpcVersion']='2.2'; + + // let user errors start at 800 + $GLOBALS['xmlrpcerruser']=800; + // let XML parse errors start at 100 + $GLOBALS['xmlrpcerrxml']=100; + + // formulate backslashes for escaping regexp + // Not in use anymore since 2.0. Shall we remove it? + /// @deprecated + $GLOBALS['xmlrpc_backslash']=chr(92).chr(92); + + // set to TRUE to enable correct decoding of values + $GLOBALS['xmlrpc_null_extension']=false; + + // used to store state during parsing + // quick explanation of components: + // ac - used to accumulate values + // isf - used to indicate a parsing fault (2) or xmlrpcresp fault (1) + // isf_reason - used for storing xmlrpcresp fault string + // lv - used to indicate "looking for a value": implements + // the logic to allow values with no types to be strings + // params - used to store parameters in method calls + // method - used to store method name + // stack - array with genealogy of xml elements names: + // used to validate nesting of xmlrpc elements + $GLOBALS['_xh']=null; + + /** + * Convert a string to the correct XML representation in a target charset + * To help correct communication of non-ascii chars inside strings, regardless + * of the charset used when sending requests, parsing them, sending responses + * and parsing responses, an option is to convert all non-ascii chars present in the message + * into their equivalent 'charset entity'. Charset entities enumerated this way + * are independent of the charset encoding used to transmit them, and all XML + * parsers are bound to understand them. + * Note that in the std case we are not sending a charset encoding mime type + * along with http headers, so we are bound by RFC 3023 to emit strict us-ascii. + * + * @todo do a bit of basic benchmarking (strtr vs. str_replace) + * @todo make usage of iconv() or recode_string() or mb_string() where available + */ + function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='') + { + if ($src_encoding == '') + { + // lame, but we know no better... + $src_encoding = $GLOBALS['xmlrpc_internalencoding']; + } + + switch(strtoupper($src_encoding.'_'.$dest_encoding)) + { + case 'ISO-8859-1_': + case 'ISO-8859-1_US-ASCII': + $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data); + break; + case 'ISO-8859-1_UTF-8': + $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escaped_data = utf8_encode($escaped_data); + break; + case 'ISO-8859-1_ISO-8859-1': + case 'US-ASCII_US-ASCII': + case 'US-ASCII_UTF-8': + case 'US-ASCII_': + case 'US-ASCII_ISO-8859-1': + case 'UTF-8_UTF-8': + $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + break; + case 'UTF-8_': + case 'UTF-8_US-ASCII': + case 'UTF-8_ISO-8859-1': + // NB: this will choke on invalid UTF-8, going most likely beyond EOF + $escaped_data = ''; + // be kind to users creating string xmlrpcvals out of different php types + $data = (string) $data; + $ns = strlen ($data); + for ($nn = 0; $nn < $ns; $nn++) + { + $ch = $data[$nn]; + $ii = ord($ch); + //1 7 0bbbbbbb (127) + if ($ii < 128) + { + /// @todo shall we replace this with a (supposedly) faster str_replace? + switch($ii){ + case 34: + $escaped_data .= '"'; + break; + case 38: + $escaped_data .= '&'; + break; + case 39: + $escaped_data .= '''; + break; + case 60: + $escaped_data .= '<'; + break; + case 62: + $escaped_data .= '>'; + break; + default: + $escaped_data .= $ch; + } // switch + } + //2 11 110bbbbb 10bbbbbb (2047) + else if ($ii>>5 == 6) + { + $b1 = ($ii & 31); + $ii = ord($data[$nn+1]); + $b2 = ($ii & 63); + $ii = ($b1 * 64) + $b2; + $ent = sprintf ('&#%d;', $ii); + $escaped_data .= $ent; + $nn += 1; + } + //3 16 1110bbbb 10bbbbbb 10bbbbbb + else if ($ii>>4 == 14) + { + $b1 = ($ii & 31); + $ii = ord($data[$nn+1]); + $b2 = ($ii & 63); + $ii = ord($data[$nn+2]); + $b3 = ($ii & 63); + $ii = ((($b1 * 64) + $b2) * 64) + $b3; + $ent = sprintf ('&#%d;', $ii); + $escaped_data .= $ent; + $nn += 2; + } + //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb + else if ($ii>>3 == 30) + { + $b1 = ($ii & 31); + $ii = ord($data[$nn+1]); + $b2 = ($ii & 63); + $ii = ord($data[$nn+2]); + $b3 = ($ii & 63); + $ii = ord($data[$nn+3]); + $b4 = ($ii & 63); + $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4; + $ent = sprintf ('&#%d;', $ii); + $escaped_data .= $ent; + $nn += 3; + } + } + break; + default: + $escaped_data = ''; + error_log("Converting from $src_encoding to $dest_encoding: not supported..."); + } + return $escaped_data; + } + + /// xml parser handler function for opening element tags + function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false) + { + // if invalid xmlrpc already detected, skip all processing + if ($GLOBALS['_xh']['isf'] < 2) + { + // check for correct element nesting + // top level element can only be of 2 types + /// @todo optimization creep: save this check into a bool variable, instead of using count() every time: + /// there is only a single top level element in xml anyway + if (count($GLOBALS['_xh']['stack']) == 0) + { + if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && ( + $name != 'VALUE' && !$accept_single_vals)) + { + $GLOBALS['_xh']['isf'] = 2; + $GLOBALS['_xh']['isf_reason'] = 'missing top level xmlrpc element'; + return; + } + else + { + $GLOBALS['_xh']['rt'] = strtolower($name); + } + } + else + { + // not top level element: see if parent is OK + $parent = end($GLOBALS['_xh']['stack']); + if (!array_key_exists($name, $GLOBALS['xmlrpc_valid_parents']) || !in_array($parent, $GLOBALS['xmlrpc_valid_parents'][$name])) + { + $GLOBALS['_xh']['isf'] = 2; + $GLOBALS['_xh']['isf_reason'] = "xmlrpc element $name cannot be child of $parent"; + return; + } + } + + switch($name) + { + // optimize for speed switch cases: most common cases first + case 'VALUE': + /// @todo we could check for 2 VALUE elements inside a MEMBER or PARAM element + $GLOBALS['_xh']['vt']='value'; // indicator: no value found yet + $GLOBALS['_xh']['ac']=''; + $GLOBALS['_xh']['lv']=1; + $GLOBALS['_xh']['php_class']=null; + break; + case 'I4': + case 'INT': + case 'STRING': + case 'BOOLEAN': + case 'DOUBLE': + case 'DATETIME.ISO8601': + case 'BASE64': + if ($GLOBALS['_xh']['vt']!='value') + { + //two data elements inside a value: an error occurred! + $GLOBALS['_xh']['isf'] = 2; + $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value"; + return; + } + $GLOBALS['_xh']['ac']=''; // reset the accumulator + break; + case 'STRUCT': + case 'ARRAY': + if ($GLOBALS['_xh']['vt']!='value') + { + //two data elements inside a value: an error occurred! + $GLOBALS['_xh']['isf'] = 2; + $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value"; + return; + } + // create an empty array to hold child values, and push it onto appropriate stack + $cur_val = array(); + $cur_val['values'] = array(); + $cur_val['type'] = $name; + // check for out-of-band information to rebuild php objs + // and in case it is found, save it + if (@isset($attrs['PHP_CLASS'])) + { + $cur_val['php_class'] = $attrs['PHP_CLASS']; + } + $GLOBALS['_xh']['valuestack'][] = $cur_val; + $GLOBALS['_xh']['vt']='data'; // be prepared for a data element next + break; + case 'DATA': + if ($GLOBALS['_xh']['vt']!='data') + { + //two data elements inside a value: an error occurred! + $GLOBALS['_xh']['isf'] = 2; + $GLOBALS['_xh']['isf_reason'] = "found two data elements inside an array element"; + return; + } + case 'METHODCALL': + case 'METHODRESPONSE': + case 'PARAMS': + // valid elements that add little to processing + break; + case 'METHODNAME': + case 'NAME': + /// @todo we could check for 2 NAME elements inside a MEMBER element + $GLOBALS['_xh']['ac']=''; + break; + case 'FAULT': + $GLOBALS['_xh']['isf']=1; + break; + case 'MEMBER': + $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name']=''; // set member name to null, in case we do not find in the xml later on + //$GLOBALS['_xh']['ac']=''; + // Drop trough intentionally + case 'PARAM': + // clear value type, so we can check later if no value has been passed for this param/member + $GLOBALS['_xh']['vt']=null; + break; + case 'NIL': + if ($GLOBALS['xmlrpc_null_extension']) + { + if ($GLOBALS['_xh']['vt']!='value') + { + //two data elements inside a value: an error occurred! + $GLOBALS['_xh']['isf'] = 2; + $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value"; + return; + } + $GLOBALS['_xh']['ac']=''; // reset the accumulator + break; + } + // we do not support the extension, so + // drop through intentionally + default: + /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!! + $GLOBALS['_xh']['isf'] = 2; + $GLOBALS['_xh']['isf_reason'] = "found not-xmlrpc xml element $name"; + break; + } + + // Save current element name to stack, to validate nesting + $GLOBALS['_xh']['stack'][] = $name; + + /// @todo optimization creep: move this inside the big switch() above + if($name!='VALUE') + { + $GLOBALS['_xh']['lv']=0; + } + } + } + + /// Used in decoding xml chunks that might represent single xmlrpc values + function xmlrpc_se_any($parser, $name, $attrs) + { + xmlrpc_se($parser, $name, $attrs, true); + } + + /// xml parser handler function for close element tags + function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true) + { + if ($GLOBALS['_xh']['isf'] < 2) + { + // push this element name from stack + // NB: if XML validates, correct opening/closing is guaranteed and + // we do not have to check for $name == $curr_elem. + // we also checked for proper nesting at start of elements... + $curr_elem = array_pop($GLOBALS['_xh']['stack']); + + switch($name) + { + case 'VALUE': + // This if() detects if no scalar was inside + if ($GLOBALS['_xh']['vt']=='value') + { + $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac']; + $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcString']; + } + + if ($rebuild_xmlrpcvals) + { + // build the xmlrpc val out of the data received, and substitute it + $temp =& new xmlrpcval($GLOBALS['_xh']['value'], $GLOBALS['_xh']['vt']); + // in case we got info about underlying php class, save it + // in the object we're rebuilding + if (isset($GLOBALS['_xh']['php_class'])) + $temp->_php_class = $GLOBALS['_xh']['php_class']; + // check if we are inside an array or struct: + // if value just built is inside an array, let's move it into array on the stack + $vscount = count($GLOBALS['_xh']['valuestack']); + if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY') + { + $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $temp; + } + else + { + $GLOBALS['_xh']['value'] = $temp; + } + } + else + { + /// @todo this needs to treat correctly php-serialized objects, + /// since std deserializing is done by php_xmlrpc_decode, + /// which we will not be calling... + if (isset($GLOBALS['_xh']['php_class'])) + { + } + + // check if we are inside an array or struct: + // if value just built is inside an array, let's move it into array on the stack + $vscount = count($GLOBALS['_xh']['valuestack']); + if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY') + { + $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $GLOBALS['_xh']['value']; + } + } + break; + case 'BOOLEAN': + case 'I4': + case 'INT': + case 'STRING': + case 'DOUBLE': + case 'DATETIME.ISO8601': + case 'BASE64': + $GLOBALS['_xh']['vt']=strtolower($name); + /// @todo: optimization creep - remove the if/elseif cycle below + /// since the case() in which we are already did that + if ($name=='STRING') + { + $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac']; + } + elseif ($name=='DATETIME.ISO8601') + { + if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $GLOBALS['_xh']['ac'])) + { + error_log('XML-RPC: invalid value received in DATETIME: '.$GLOBALS['_xh']['ac']); + } + $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcDateTime']; + $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac']; + } + elseif ($name=='BASE64') + { + /// @todo check for failure of base64 decoding / catch warnings + $GLOBALS['_xh']['value']=base64_decode($GLOBALS['_xh']['ac']); + } + elseif ($name=='BOOLEAN') + { + // special case here: we translate boolean 1 or 0 into PHP + // constants true or false. + // Strings 'true' and 'false' are accepted, even though the + // spec never mentions them (see eg. Blogger api docs) + // NB: this simple checks helps a lot sanitizing input, ie no + // security problems around here + if ($GLOBALS['_xh']['ac']=='1' || strcasecmp($GLOBALS['_xh']['ac'], 'true') == 0) + { + $GLOBALS['_xh']['value']=true; + } + else + { + // log if receiveing something strange, even though we set the value to false anyway + if ($GLOBALS['_xh']['ac']!='0' && strcasecmp($_xh[$parser]['ac'], 'false') != 0) + error_log('XML-RPC: invalid value received in BOOLEAN: '.$GLOBALS['_xh']['ac']); + $GLOBALS['_xh']['value']=false; + } + } + elseif ($name=='DOUBLE') + { + // we have a DOUBLE + // we must check that only 0123456789-. are characters here + if (!preg_match('/^[+-]?[eE0123456789 \t.]+$/', $GLOBALS['_xh']['ac'])) + { + /// @todo: find a better way of throwing an error + // than this! + error_log('XML-RPC: non numeric value received in DOUBLE: '.$GLOBALS['_xh']['ac']); + $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND'; + } + else + { + // it's ok, add it on + $GLOBALS['_xh']['value']=(double)$GLOBALS['_xh']['ac']; + } + } + else + { + // we have an I4/INT + // we must check that only 0123456789- are characters here + if (!preg_match('/^[+-]?[0123456789 \t]+$/', $GLOBALS['_xh']['ac'])) + { + /// @todo find a better way of throwing an error + // than this! + error_log('XML-RPC: non numeric value received in INT: '.$GLOBALS['_xh']['ac']); + $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND'; + } + else + { + // it's ok, add it on + $GLOBALS['_xh']['value']=(int)$GLOBALS['_xh']['ac']; + } + } + //$GLOBALS['_xh']['ac']=''; // is this necessary? + $GLOBALS['_xh']['lv']=3; // indicate we've found a value + break; + case 'NAME': + $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name'] = $GLOBALS['_xh']['ac']; + break; + case 'MEMBER': + //$GLOBALS['_xh']['ac']=''; // is this necessary? + // add to array in the stack the last element built, + // unless no VALUE was found + if ($GLOBALS['_xh']['vt']) + { + $vscount = count($GLOBALS['_xh']['valuestack']); + $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][$GLOBALS['_xh']['valuestack'][$vscount-1]['name']] = $GLOBALS['_xh']['value']; + } else + error_log('XML-RPC: missing VALUE inside STRUCT in received xml'); + break; + case 'DATA': + //$GLOBALS['_xh']['ac']=''; // is this necessary? + $GLOBALS['_xh']['vt']=null; // reset this to check for 2 data elements in a row - even if they're empty + break; + case 'STRUCT': + case 'ARRAY': + // fetch out of stack array of values, and promote it to current value + $curr_val = array_pop($GLOBALS['_xh']['valuestack']); + $GLOBALS['_xh']['value'] = $curr_val['values']; + $GLOBALS['_xh']['vt']=strtolower($name); + if (isset($curr_val['php_class'])) + { + $GLOBALS['_xh']['php_class'] = $curr_val['php_class']; + } + break; + case 'PARAM': + // add to array of params the current value, + // unless no VALUE was found + if ($GLOBALS['_xh']['vt']) + { + $GLOBALS['_xh']['params'][]=$GLOBALS['_xh']['value']; + $GLOBALS['_xh']['pt'][]=$GLOBALS['_xh']['vt']; + } + else + error_log('XML-RPC: missing VALUE inside PARAM in received xml'); + break; + case 'METHODNAME': + $GLOBALS['_xh']['method']=preg_replace('/^[\n\r\t ]+/', '', $GLOBALS['_xh']['ac']); + break; + case 'NIL': + if ($GLOBALS['xmlrpc_null_extension']) + { + $GLOBALS['_xh']['vt']='null'; + $GLOBALS['_xh']['value']=null; + $GLOBALS['_xh']['lv']=3; + break; + } + // drop through intentionally if nil extension not enabled + case 'PARAMS': + case 'FAULT': + case 'METHODCALL': + case 'METHORESPONSE': + break; + default: + // End of INVALID ELEMENT! + // shall we add an assert here for unreachable code??? + break; + } + } + } + + /// Used in decoding xmlrpc requests/responses without rebuilding xmlrpc values + function xmlrpc_ee_fast($parser, $name) + { + xmlrpc_ee($parser, $name, false); + } + + /// xml parser handler function for character data + function xmlrpc_cd($parser, $data) + { + // skip processing if xml fault already detected + if ($GLOBALS['_xh']['isf'] < 2) + { + // "lookforvalue==3" means that we've found an entire value + // and should discard any further character data + if($GLOBALS['_xh']['lv']!=3) + { + // G. Giunta 2006-08-23: useless change of 'lv' from 1 to 2 + //if($GLOBALS['_xh']['lv']==1) + //{ + // if we've found text and we're just in a then + // say we've found a value + //$GLOBALS['_xh']['lv']=2; + //} + // we always initialize the accumulator before starting parsing, anyway... + //if(!@isset($GLOBALS['_xh']['ac'])) + //{ + // $GLOBALS['_xh']['ac'] = ''; + //} + $GLOBALS['_xh']['ac'].=$data; + } + } + } + + /// xml parser handler function for 'other stuff', ie. not char data or + /// element start/end tag. In fact it only gets called on unknown entities... + function xmlrpc_dh($parser, $data) + { + // skip processing if xml fault already detected + if ($GLOBALS['_xh']['isf'] < 2) + { + if(substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';') + { + // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2 + //if($GLOBALS['_xh']['lv']==1) + //{ + // $GLOBALS['_xh']['lv']=2; + //} + $GLOBALS['_xh']['ac'].=$data; + } + } + return true; + } + + class xmlrpc_client + { + var $path; + var $server; + var $port=0; + var $method='http'; + var $errno; + var $errstr; + var $debug=0; + var $username=''; + var $password=''; + var $authtype=1; + var $cert=''; + var $certpass=''; + var $cacert=''; + var $cacertdir=''; + var $key=''; + var $keypass=''; + var $verifypeer=true; + var $verifyhost=1; + var $no_multicall=false; + var $proxy=''; + var $proxyport=0; + var $proxy_user=''; + var $proxy_pass=''; + var $proxy_authtype=1; + var $cookies=array(); + /** + * List of http compression methods accepted by the client for responses. + * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib + * + * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since + * in those cases it will be up to CURL to decide the compression methods + * it supports. You might check for the presence of 'zlib' in the output of + * curl_version() to determine wheter compression is supported or not + */ + var $accepted_compression = array(); + /** + * Name of compression scheme to be used for sending requests. + * Either null, gzip or deflate + */ + var $request_compression = ''; + /** + * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see: + * http://curl.haxx.se/docs/faq.html#7.3) + */ + var $xmlrpc_curl_handle = null; + /// Wheter to use persistent connections for http 1.1 and https + var $keepalive = false; + /// Charset encodings that can be decoded without problems by the client + var $accepted_charset_encodings = array(); + /// Charset encoding to be used in serializing request. NULL = use ASCII + var $request_charset_encoding = ''; + /** + * Decides the content of xmlrpcresp objects returned by calls to send() + * valid strings are 'xmlrpcvals', 'phpvals' or 'xml' + */ + var $return_type = 'xmlrpcvals'; + + /** + * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php + * @param string $server the server name / ip address + * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used + * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed + */ + function xmlrpc_client($path, $server='', $port='', $method='') + { + // allow user to specify all params in $path + if($server == '' and $port == '' and $method == '') + { + $parts = parse_url($path); + $server = $parts['host']; + $path = $parts['path']; + if(isset($parts['query'])) + { + $path .= '?'.$parts['query']; + } + if(isset($parts['fragment'])) + { + $path .= '#'.$parts['fragment']; + } + if(isset($parts['port'])) + { + $port = $parts['port']; + } + if(isset($parts['scheme'])) + { + $method = $parts['scheme']; + } + if(isset($parts['user'])) + { + $this->username = $parts['user']; + } + if(isset($parts['pass'])) + { + $this->password = $parts['pass']; + } + } + if($path == '' || $path[0] != '/') + { + $this->path='/'.$path; + } + else + { + $this->path=$path; + } + $this->server=$server; + if($port != '') + { + $this->port=$port; + } + if($method != '') + { + $this->method=$method; + } + + // if ZLIB is enabled, let the client by default accept compressed responses + if(function_exists('gzinflate') || ( + function_exists('curl_init') && (($info = curl_version()) && + ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version']))) + )) + { + $this->accepted_compression = array('gzip', 'deflate'); + } + + // keepalives: enabled by default ONLY for PHP >= 4.3.8 + // (see http://curl.haxx.se/docs/faq.html#7.3) + if(version_compare(phpversion(), '4.3.8') >= 0) + { + $this->keepalive = true; + } + + // by default the xml parser can support these 3 charset encodings + $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII'); + } + + /** + * Enables/disables the echoing to screen of the xmlrpc responses received + * @param integer $debug values 0, 1 and 2 are supported (2 = echo sent msg too, before received response) + * @access public + */ + function setDebug($in) + { + $this->debug=$in; + } + + /** + * Add some http BASIC AUTH credentials, used by the client to authenticate + * @param string $u username + * @param string $p password + * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth) + * @access public + */ + function setCredentials($u, $p, $t=1) + { + $this->username=$u; + $this->password=$p; + $this->authtype=$t; + } + + /** + * Add a client-side https certificate + * @param string $cert + * @param string $certpass + * @access public + */ + function setCertificate($cert, $certpass) + { + $this->cert = $cert; + $this->certpass = $certpass; + } + + /** + * Add a CA certificate to verify server with (see man page about + * CURLOPT_CAINFO for more details + * @param string $cacert certificate file name (or dir holding certificates) + * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false + * @access public + */ + function setCaCertificate($cacert, $is_dir=false) + { + if ($is_dir) + { + $this->cacert = $cacert; + } + else + { + $this->cacertdir = $cacert; + } + } + + /** + * Set attributes for SSL communication: private SSL key + * @param string $key The name of a file containing a private SSL key + * @param string $keypass The secret password needed to use the private SSL key + * @access public + * NB: does not work in older php/curl installs + * Thanks to Daniel Convissor + */ + function setKey($key, $keypass) + { + $this->key = $key; + $this->keypass = $keypass; + } + + /** + * Set attributes for SSL communication: verify server certificate + * @param bool $i enable/disable verification of peer certificate + * @access public + */ + function setSSLVerifyPeer($i) + { + $this->verifypeer = $i; + } + + /** + * Set attributes for SSL communication: verify match of server cert w. hostname + * @param int $i + * @access public + */ + function setSSLVerifyHost($i) + { + $this->verifyhost = $i; + } + + /** + * Set proxy info + * @param string $proxyhost + * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS + * @param string $proxyusername Leave blank if proxy has public access + * @param string $proxypassword Leave blank if proxy has public access + * @param int $proxyauthtype set to constant CURLAUTH_NTLM to use NTLM auth with proxy + * @access public + */ + function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1) + { + $this->proxy = $proxyhost; + $this->proxyport = $proxyport; + $this->proxy_user = $proxyusername; + $this->proxy_pass = $proxypassword; + $this->proxy_authtype = $proxyauthtype; + } + + /** + * Enables/disables reception of compressed xmlrpc responses. + * Note that enabling reception of compressed responses merely adds some standard + * http headers to xmlrpc requests. It is up to the xmlrpc server to return + * compressed responses when receiving such requests. + * @param string $compmethod either 'gzip', 'deflate', 'any' or '' + * @access public + */ + function setAcceptedCompression($compmethod) + { + if ($compmethod == 'any') + $this->accepted_compression = array('gzip', 'deflate'); + else + $this->accepted_compression = array($compmethod); + } + + /** + * Enables/disables http compression of xmlrpc request. + * Take care when sending compressed requests: servers might not support them + * (and automatic fallback to uncompressed requests is not yet implemented) + * @param string $compmethod either 'gzip', 'deflate' or '' + * @access public + */ + function setRequestCompression($compmethod) + { + $this->request_compression = $compmethod; + } + + /** + * Adds a cookie to list of cookies that will be sent to server. + * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie: + * do not do it unless you know what you are doing + * @param string $name + * @param string $value + * @param string $path + * @param string $domain + * @param int $port + * @access public + * + * @todo check correctness of urlencoding cookie value (copied from php way of doing it...) + */ + function setCookie($name, $value='', $path='', $domain='', $port=null) + { + $this->cookies[$name]['value'] = urlencode($value); + if ($path || $domain || $port) + { + $this->cookies[$name]['path'] = $path; + $this->cookies[$name]['domain'] = $domain; + $this->cookies[$name]['port'] = $port; + $this->cookies[$name]['version'] = 1; + } + else + { + $this->cookies[$name]['version'] = 0; + } + } + + /** + * Send an xmlrpc request + * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request + * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply + * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used + * @return xmlrpcresp + * @access public + */ + function& send($msg, $timeout=0, $method='') + { + // if user deos not specify http protocol, use native method of this client + // (i.e. method set during call to constructor) + if($method == '') + { + $method = $this->method; + } + + if(is_array($msg)) + { + // $msg is an array of xmlrpcmsg's + $r = $this->multicall($msg, $timeout, $method); + return $r; + } + elseif(is_string($msg)) + { + $n =& new xmlrpcmsg(''); + $n->payload = $msg; + $msg = $n; + } + + // where msg is an xmlrpcmsg + $msg->debug=$this->debug; + + if($method == 'https') + { + $r =& $this->sendPayloadHTTPS( + $msg, + $this->server, + $this->port, + $timeout, + $this->username, + $this->password, + $this->authtype, + $this->cert, + $this->certpass, + $this->cacert, + $this->cacertdir, + $this->proxy, + $this->proxyport, + $this->proxy_user, + $this->proxy_pass, + $this->proxy_authtype, + $this->keepalive, + $this->key, + $this->keypass + ); + } + elseif($method == 'http11') + { + $r =& $this->sendPayloadCURL( + $msg, + $this->server, + $this->port, + $timeout, + $this->username, + $this->password, + $this->authtype, + null, + null, + null, + null, + $this->proxy, + $this->proxyport, + $this->proxy_user, + $this->proxy_pass, + $this->proxy_authtype, + 'http', + $this->keepalive + ); + } + else + { + $r =& $this->sendPayloadHTTP10( + $msg, + $this->server, + $this->port, + $timeout, + $this->username, + $this->password, + $this->authtype, + $this->proxy, + $this->proxyport, + $this->proxy_user, + $this->proxy_pass, + $this->proxy_authtype + ); + } + + return $r; + } + + /** + * @access private + */ + function &sendPayloadHTTP10($msg, $server, $port, $timeout=0, + $username='', $password='', $authtype=1, $proxyhost='', + $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1) + { + if($port==0) + { + $port=80; + } + + // Only create the payload if it was not created previously + if(empty($msg->payload)) + { + $msg->createPayload($this->request_charset_encoding); + } + + $payload = $msg->payload; + // Deflate request body and set appropriate request headers + if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) + { + if($this->request_compression == 'gzip') + { + $a = @gzencode($payload); + if($a) + { + $payload = $a; + $encoding_hdr = "Content-Encoding: gzip\r\n"; + } + } + else + { + $a = @gzcompress($payload); + if($a) + { + $payload = $a; + $encoding_hdr = "Content-Encoding: deflate\r\n"; + } + } + } + else + { + $encoding_hdr = ''; + } + + // thanks to Grant Rauscher for this + $credentials=''; + if($username!='') + { + $credentials='Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n"; + if ($authtype != 1) + { + error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth is supported with HTTP 1.0'); + } + } + + $accepted_encoding = ''; + if(is_array($this->accepted_compression) && count($this->accepted_compression)) + { + $accepted_encoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n"; + } + + $proxy_credentials = ''; + if($proxyhost) + { + if($proxyport == 0) + { + $proxyport = 8080; + } + $connectserver = $proxyhost; + $connectport = $proxyport; + $uri = 'http://'.$server.':'.$port.$this->path; + if($proxyusername != '') + { + if ($proxyauthtype != 1) + { + error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth to proxy is supported with HTTP 1.0'); + } + $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername.':'.$proxypassword) . "\r\n"; + } + } + else + { + $connectserver = $server; + $connectport = $port; + $uri = $this->path; + } + + // Cookie generation, as per rfc2965 (version 1 cookies) or + // netscape's rules (version 0 cookies) + $cookieheader=''; + foreach ($this->cookies as $name => $cookie) + { + if ($cookie['version']) + { + $cookieheader .= 'Cookie: $Version="' . $cookie['version'] . '"; '; + $cookieheader .= $name . '="' . $cookie['value'] . '";'; + if ($cookie['path']) + $cookieheader .= ' $Path="' . $cookie['path'] . '";'; + if ($cookie['domain']) + $cookieheader .= ' $Domain="' . $cookie['domain'] . '";'; + if ($cookie['port']) + $cookieheader .= ' $Port="' . $cookie['domain'] . '";'; + $cookieheader = substr($cookieheader, 0, -1) . "\r\n"; + } + else + { + $cookieheader .= 'Cookie: ' . $name . '=' . $cookie['value'] . "\r\n"; + } + } + + $op= 'POST ' . $uri. " HTTP/1.0\r\n" . + 'User-Agent: ' . $GLOBALS['xmlrpcName'] . ' ' . $GLOBALS['xmlrpcVersion'] . "\r\n" . + 'Host: '. $server . ':' . $port . "\r\n" . + $credentials . + $proxy_credentials . + $accepted_encoding . + $encoding_hdr . + 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" . + $cookieheader . + 'Content-Type: ' . $msg->content_type . "\r\nContent-Length: " . + strlen($payload) . "\r\n\r\n" . + $payload; + + if($this->debug > 1) + { + print "
    \n---SENDING---\n" . htmlentities($op) . "\n---END---\n
    "; + // let the client see this now in case http times out... + flush(); + } + + if($timeout>0) + { + $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr, $timeout); + } + else + { + $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr); + } + if($fp) + { + if($timeout>0 && function_exists('stream_set_timeout')) + { + stream_set_timeout($fp, $timeout); + } + } + else + { + $this->errstr='Connect error: '.$this->errstr; + $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr . ' (' . $this->errno . ')'); + return $r; + } + + if(!fputs($fp, $op, strlen($op))) + { + $this->errstr='Write error'; + $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr); + return $r; + } + else + { + // reset errno and errstr on succesful socket connection + $this->errstr = ''; + } + // G. Giunta 2005/10/24: close socket before parsing. + // should yeld slightly better execution times, and make easier recursive calls (e.g. to follow http redirects) + $ipd=''; + while($data=fread($fp, 32768)) + { + // shall we check for $data === FALSE? + // as per the manual, it signals an error + $ipd.=$data; + } + fclose($fp); + $r =& $msg->parseResponse($ipd, false, $this->return_type); + return $r; + + } + + /** + * @access private + */ + function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='', + $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='', + $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, + $keepalive=false, $key='', $keypass='') + { + $r =& $this->sendPayloadCURL($msg, $server, $port, $timeout, $username, + $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport, + $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass); + return $r; + } + + /** + * Contributed by Justin Miller + * Requires curl to be built into PHP + * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers! + * @access private + */ + function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', + $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='', + $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https', + $keepalive=false, $key='', $keypass='') + { + if(!function_exists('curl_init')) + { + $this->errstr='CURL unavailable on this install'; + $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_curl'], $GLOBALS['xmlrpcstr']['no_curl']); + return $r; + } + if($method == 'https') + { + if(($info = curl_version()) && + ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))) + { + $this->errstr='SSL unavailable on this install'; + $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_ssl'], $GLOBALS['xmlrpcstr']['no_ssl']); + return $r; + } + } + + if($port == 0) + { + if($method == 'http') + { + $port = 80; + } + else + { + $port = 443; + } + } + + // Only create the payload if it was not created previously + if(empty($msg->payload)) + { + $msg->createPayload($this->request_charset_encoding); + } + + // Deflate request body and set appropriate request headers + $payload = $msg->payload; + if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) + { + if($this->request_compression == 'gzip') + { + $a = @gzencode($payload); + if($a) + { + $payload = $a; + $encoding_hdr = 'Content-Encoding: gzip'; + } + } + else + { + $a = @gzcompress($payload); + if($a) + { + $payload = $a; + $encoding_hdr = 'Content-Encoding: deflate'; + } + } + } + else + { + $encoding_hdr = ''; + } + + if($this->debug > 1) + { + print "
    \n---SENDING---\n" . htmlentities($payload) . "\n---END---\n
    "; + // let the client see this now in case http times out... + flush(); + } + + if(!$keepalive || !$this->xmlrpc_curl_handle) + { + $curl = curl_init($method . '://' . $server . ':' . $port . $this->path); + if($keepalive) + { + $this->xmlrpc_curl_handle = $curl; + } + } + else + { + $curl = $this->xmlrpc_curl_handle; + } + + // results into variable + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + + if($this->debug) + { + curl_setopt($curl, CURLOPT_VERBOSE, 1); + } + curl_setopt($curl, CURLOPT_USERAGENT, $GLOBALS['xmlrpcName'].' '.$GLOBALS['xmlrpcVersion']); + // required for XMLRPC: post the data + curl_setopt($curl, CURLOPT_POST, 1); + // the data + curl_setopt($curl, CURLOPT_POSTFIELDS, $payload); + + // return the header too + curl_setopt($curl, CURLOPT_HEADER, 1); + + // will only work with PHP >= 5.0 + // NB: if we set an empty string, CURL will add http header indicating + // ALL methods it is supporting. This is possibly a better option than + // letting the user tell what curl can / cannot do... + if(is_array($this->accepted_compression) && count($this->accepted_compression)) + { + //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression)); + // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?) + if (count($this->accepted_compression) == 1) + { + curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]); + } + else + curl_setopt($curl, CURLOPT_ENCODING, ''); + } + // extra headers + $headers = array('Content-Type: ' . $msg->content_type , 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings)); + // if no keepalive is wanted, let the server know it in advance + if(!$keepalive) + { + $headers[] = 'Connection: close'; + } + // request compression header + if($encoding_hdr) + { + $headers[] = $encoding_hdr; + } + + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); + // timeout is borked + if($timeout) + { + curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1); + } + + if($username && $password) + { + curl_setopt($curl, CURLOPT_USERPWD, $username.':'.$password); + if (defined('CURLOPT_HTTPAUTH')) + { + curl_setopt($curl, CURLOPT_HTTPAUTH, $authtype); + } + else if ($authtype != 1) + { + error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth is supported by the current PHP/curl install'); + } + } + + if($method == 'https') + { + // set cert file + if($cert) + { + curl_setopt($curl, CURLOPT_SSLCERT, $cert); + } + // set cert password + if($certpass) + { + curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certpass); + } + // whether to verify remote host's cert + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer); + // set ca certificates file/dir + if($cacert) + { + curl_setopt($curl, CURLOPT_CAINFO, $cacert); + } + if($cacertdir) + { + curl_setopt($curl, CURLOPT_CAPATH, $cacertdir); + } + // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?) + if($key) + { + curl_setopt($curl, CURLOPT_SSLKEY, $key); + } + // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?) + if($keypass) + { + curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass); + } + // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost); + } + + // proxy info + if($proxyhost) + { + if($proxyport == 0) + { + $proxyport = 8080; // NB: even for HTTPS, local connection is on port 8080 + } + curl_setopt($curl, CURLOPT_PROXY,$proxyhost.':'.$proxyport); + //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport); + if($proxyusername) + { + curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername.':'.$proxypassword); + if (defined('CURLOPT_PROXYAUTH')) + { + curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyauthtype); + } + else if ($proxyauthtype != 1) + { + error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth to proxy is supported by the current PHP/curl install'); + } + } + } + + // NB: should we build cookie http headers by hand rather than let CURL do it? + // the following code does not honour 'expires', 'path' and 'domain' cookie attributes + // set to clint obj the the user... + if (count($this->cookies)) + { + $cookieheader = ''; + foreach ($this->cookies as $name => $cookie) + { + $cookieheader .= $name . '=' . $cookie['value'] . ', '; + } + curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2)); + } + + $result = curl_exec($curl); + + if(!$result) + { + $this->errstr='no response'; + $resp=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['curl_fail'], $GLOBALS['xmlrpcstr']['curl_fail']. ': '. curl_error($curl)); + if(!$keepalive) + { + curl_close($curl); + } + } + else + { + if(!$keepalive) + { + curl_close($curl); + } + $resp =& $msg->parseResponse($result, true, $this->return_type); + } + return $resp; + } + + /** + * Send an array of request messages and return an array of responses. + * Unless $this->no_multicall has been set to true, it will try first + * to use one single xmlrpc call to server method system.multicall, and + * revert to sending many successive calls in case of failure. + * This failure is also stored in $this->no_multicall for subsequent calls. + * Unfortunately, there is no server error code universally used to denote + * the fact that multicall is unsupported, so there is no way to reliably + * distinguish between that and a temporary failure. + * If you are sure that server supports multicall and do not want to + * fallback to using many single calls, set the fourth parameter to FALSE. + * + * NB: trying to shoehorn extra functionality into existing syntax has resulted + * in pretty much convoluted code... + * + * @param array $msgs an array of xmlrpcmsg objects + * @param integer $timeout connection timeout (in seconds) + * @param string $method the http protocol variant to be used + * @param boolean fallback When true, upon receiveing an error during multicall, multiple single calls will be attempted + * @return array + * @access public + */ + function multicall($msgs, $timeout=0, $method='', $fallback=true) + { + if ($method == '') + { + $method = $this->method; + } + if(!$this->no_multicall) + { + $results = $this->_try_multicall($msgs, $timeout, $method); + if(is_array($results)) + { + // System.multicall succeeded + return $results; + } + else + { + // either system.multicall is unsupported by server, + // or call failed for some other reason. + if ($fallback) + { + // Don't try it next time... + $this->no_multicall = true; + } + else + { + if (is_a($results, 'xmlrpcresp')) + { + $result = $results; + } + else + { + $result =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['multicall_error'], $GLOBALS['xmlrpcstr']['multicall_error']); + } + } + } + } + else + { + // override fallback, in case careless user tries to do two + // opposite things at the same time + $fallback = true; + } + + $results = array(); + if ($fallback) + { + // system.multicall is (probably) unsupported by server: + // emulate multicall via multiple requests + foreach($msgs as $msg) + { + $results[] =& $this->send($msg, $timeout, $method); + } + } + else + { + // user does NOT want to fallback on many single calls: + // since we should always return an array of responses, + // return an array with the same error repeated n times + foreach($msgs as $msg) + { + $results[] = $result; + } + } + return $results; + } + + /** + * Attempt to boxcar $msgs via system.multicall. + * Returns either an array of xmlrpcreponses, an xmlrpc error response + * or false (when received response does not respect valid multicall syntax) + * @access private + */ + function _try_multicall($msgs, $timeout, $method) + { + // Construct multicall message + $calls = array(); + foreach($msgs as $msg) + { + $call['methodName'] =& new xmlrpcval($msg->method(),'string'); + $numParams = $msg->getNumParams(); + $params = array(); + for($i = 0; $i < $numParams; $i++) + { + $params[$i] = $msg->getParam($i); + } + $call['params'] =& new xmlrpcval($params, 'array'); + $calls[] =& new xmlrpcval($call, 'struct'); + } + $multicall =& new xmlrpcmsg('system.multicall'); + $multicall->addParam(new xmlrpcval($calls, 'array')); + + // Attempt RPC call + $result =& $this->send($multicall, $timeout, $method); + + if($result->faultCode() != 0) + { + // call to system.multicall failed + return $result; + } + + // Unpack responses. + $rets = $result->value(); + + if ($this->return_type == 'xml') + { + return $rets; + } + else if ($this->return_type == 'phpvals') + { + ///@todo test this code branch... + $rets = $result->value(); + if(!is_array($rets)) + { + return false; // bad return type from system.multicall + } + $numRets = count($rets); + if($numRets != count($msgs)) + { + return false; // wrong number of return values. + } + + $response = array(); + for($i = 0; $i < $numRets; $i++) + { + $val = $rets[$i]; + if (!is_array($val)) { + return false; + } + switch(count($val)) + { + case 1: + if(!isset($val[0])) + { + return false; // Bad value + } + // Normal return value + $response[$i] =& new xmlrpcresp($val[0], 0, '', 'phpvals'); + break; + case 2: + /// @todo remove usage of @: it is apparently quite slow + $code = @$val['faultCode']; + if(!is_int($code)) + { + return false; + } + $str = @$val['faultString']; + if(!is_string($str)) + { + return false; + } + $response[$i] =& new xmlrpcresp(0, $code, $str); + break; + default: + return false; + } + } + return $response; + } + else // return type == 'xmlrpcvals' + { + $rets = $result->value(); + if($rets->kindOf() != 'array') + { + return false; // bad return type from system.multicall + } + $numRets = $rets->arraysize(); + if($numRets != count($msgs)) + { + return false; // wrong number of return values. + } + + $response = array(); + for($i = 0; $i < $numRets; $i++) + { + $val = $rets->arraymem($i); + switch($val->kindOf()) + { + case 'array': + if($val->arraysize() != 1) + { + return false; // Bad value + } + // Normal return value + $response[$i] =& new xmlrpcresp($val->arraymem(0)); + break; + case 'struct': + $code = $val->structmem('faultCode'); + if($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') + { + return false; + } + $str = $val->structmem('faultString'); + if($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') + { + return false; + } + $response[$i] =& new xmlrpcresp(0, $code->scalarval(), $str->scalarval()); + break; + default: + return false; + } + } + return $response; + } + } + } // end class xmlrpc_client + + class xmlrpcresp + { + var $val = 0; + var $valtyp; + var $errno = 0; + var $errstr = ''; + var $payload; + var $hdrs = array(); + var $_cookies = array(); + var $content_type = 'text/xml'; + var $raw_data = ''; + + /** + * @param mixed $val either an xmlrpcval obj, a php value or the xml serialization of an xmlrpcval (a string) + * @param integer $fcode set it to anything but 0 to create an error response + * @param string $fstr the error string, in case of an error response + * @param string $valtyp either 'xmlrpcvals', 'phpvals' or 'xml' + * + * @todo add check that $val / $fcode / $fstr is of correct type??? + * NB: as of now we do not do it, since it might be either an xmlrpcval or a plain + * php val, or a complete xml chunk, depending on usage of xmlrpc_client::send() inside which creator is called... + */ + function xmlrpcresp($val, $fcode = 0, $fstr = '', $valtyp='') + { + if($fcode != 0) + { + // error response + $this->errno = $fcode; + $this->errstr = $fstr; + //$this->errstr = htmlspecialchars($fstr); // XXX: encoding probably shouldn't be done here; fix later. + } + else + { + // successful response + $this->val = $val; + if ($valtyp == '') + { + // user did not declare type of response value: try to guess it + if (is_object($this->val) && is_a($this->val, 'xmlrpcval')) + { + $this->valtyp = 'xmlrpcvals'; + } + else if (is_string($this->val)) + { + $this->valtyp = 'xml'; + + } + else + { + $this->valtyp = 'phpvals'; + } + } + else + { + // user declares type of resp value: believe him + $this->valtyp = $valtyp; + } + } + } + + /** + * Returns the error code of the response. + * @return integer the error code of this response (0 for not-error responses) + * @access public + */ + function faultCode() + { + return $this->errno; + } + + /** + * Returns the error code of the response. + * @return string the error string of this response ('' for not-error responses) + * @access public + */ + function faultString() + { + return $this->errstr; + } + + /** + * Returns the value received by the server. + * @return mixed the xmlrpcval object returned by the server. Might be an xml string or php value if the response has been created by specially configured xmlrpc_client objects + * @access public + */ + function value() + { + return $this->val; + } + + /** + * Returns an array with the cookies received from the server. + * Array has the form: $cookiename => array ('value' => $val, $attr1 => $val1, $attr2 = $val2, ...) + * with attributes being e.g. 'expires', 'path', domain'. + * NB: cookies sent as 'expired' by the server (i.e. with an expiry date in the past) + * are still present in the array. It is up to the user-defined code to decide + * how to use the received cookies, and wheter they have to be sent back with the next + * request to the server (using xmlrpc_client::setCookie) or not + * @return array array of cookies received from the server + * @access public + */ + function cookies() + { + return $this->_cookies; + } + + /** + * Returns xml representation of the response. XML prologue not included + * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed + * @return string the xml representation of the response + * @access public + */ + function serialize($charset_encoding='') + { + if ($charset_encoding != '') + $this->content_type = 'text/xml; charset=' . $charset_encoding; + else + $this->content_type = 'text/xml'; + $result = "\n"; + if($this->errno) + { + // G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients + // by xml-encoding non ascii chars + $result .= "\n" . +"\nfaultCode\n" . $this->errno . +"\n\n\nfaultString\n" . +xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "\n\n" . +"\n\n"; + } + else + { + if(!is_object($this->val) || !is_a($this->val, 'xmlrpcval')) + { + if (is_string($this->val) && $this->valtyp == 'xml') + { + $result .= "\n\n" . + $this->val . + "\n"; + } + else + { + /// @todo try to build something serializable? + die('cannot serialize xmlrpcresp objects whose content is native php values'); + } + } + else + { + $result .= "\n\n" . + $this->val->serialize($charset_encoding) . + "\n"; + } + } + $result .= "\n"; + $this->payload = $result; + return $result; + } + } + + class xmlrpcmsg + { + var $payload; + var $methodname; + var $params=array(); + var $debug=0; + var $content_type = 'text/xml'; + + /** + * @param string $meth the name of the method to invoke + * @param array $pars array of parameters to be paased to the method (xmlrpcval objects) + */ + function xmlrpcmsg($meth, $pars=0) + { + $this->methodname=$meth; + if(is_array($pars) && count($pars)>0) + { + for($i=0; $iaddParam($pars[$i]); + } + } + } + + /** + * @access private + */ + function xml_header($charset_encoding='') + { + if ($charset_encoding != '') + { + return "\n\n"; + } + else + { + return "\n\n"; + } + } + + /** + * @access private + */ + function xml_footer() + { + return ''; + } + + /** + * @access private + */ + function kindOf() + { + return 'msg'; + } + + /** + * @access private + */ + function createPayload($charset_encoding='') + { + if ($charset_encoding != '') + $this->content_type = 'text/xml; charset=' . $charset_encoding; + else + $this->content_type = 'text/xml'; + $this->payload=$this->xml_header($charset_encoding); + $this->payload.='' . $this->methodname . "\n"; + $this->payload.="\n"; + for($i=0; $iparams); $i++) + { + $p=$this->params[$i]; + $this->payload.="\n" . $p->serialize($charset_encoding) . + "\n"; + } + $this->payload.="\n"; + $this->payload.=$this->xml_footer(); + } + + /** + * Gets/sets the xmlrpc method to be invoked + * @param string $meth the method to be set (leave empty not to set it) + * @return string the method that will be invoked + * @access public + */ + function method($meth='') + { + if($meth!='') + { + $this->methodname=$meth; + } + return $this->methodname; + } + + /** + * Returns xml representation of the message. XML prologue included + * @return string the xml representation of the message, xml prologue included + * @access public + */ + function serialize($charset_encoding='') + { + $this->createPayload($charset_encoding); + return $this->payload; + } + + /** + * Add a parameter to the list of parameters to be used upon method invocation + * @param xmlrpcval $par + * @return boolean false on failure + * @access public + */ + function addParam($par) + { + // add check: do not add to self params which are not xmlrpcvals + if(is_object($par) && is_a($par, 'xmlrpcval')) + { + $this->params[]=$par; + return true; + } + else + { + return false; + } + } + + /** + * Returns the nth parameter in the message. The index zero-based. + * @param integer $i the index of the parameter to fetch (zero based) + * @return xmlrpcval the i-th parameter + * @access public + */ + function getParam($i) { return $this->params[$i]; } + + /** + * Returns the number of parameters in the messge. + * @return integer the number of parameters currently set + * @access public + */ + function getNumParams() { return count($this->params); } + + /** + * Given an open file handle, read all data available and parse it as axmlrpc response. + * NB: the file handle is not closed by this function. + * @access public + * @return xmlrpcresp + * @todo add 2nd & 3rd param to be passed to ParseResponse() ??? + */ + function &parseResponseFile($fp) + { + $ipd=''; + while($data=fread($fp, 32768)) + { + $ipd.=$data; + } + //fclose($fp); + $r =& $this->parseResponse($ipd); + return $r; + } + + /** + * Parses HTTP headers and separates them from data. + * @access private + */ + function &parseResponseHeaders(&$data, $headers_processed=false) + { + // Support "web-proxy-tunelling" connections for https through proxies + if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data)) + { + // Look for CR/LF or simple LF as line separator, + // (even though it is not valid http) + $pos = strpos($data,"\r\n\r\n"); + if($pos || is_int($pos)) + { + $bd = $pos+4; + } + else + { + $pos = strpos($data,"\n\n"); + if($pos || is_int($pos)) + { + $bd = $pos+2; + } + else + { + // No separation between response headers and body: fault? + $bd = 0; + } + } + if ($bd) + { + // this filters out all http headers from proxy. + // maybe we could take them into account, too? + $data = substr($data, $bd); + } + else + { + error_log('XML-RPC: xmlrpcmsg::parseResponse: HTTPS via proxy error, tunnel connection possibly failed'); + $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)'); + return $r; + } + } + + // Strip HTTP 1.1 100 Continue header if present + while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data)) + { + $pos = strpos($data, 'HTTP', 12); + // server sent a Continue header without any (valid) content following... + // give the client a chance to know it + if(!$pos && !is_int($pos)) // works fine in php 3, 4 and 5 + { + break; + } + $data = substr($data, $pos); + } + if(!preg_match('/^HTTP\/[0-9.]+ 200 /', $data)) + { + $errstr= substr($data, 0, strpos($data, "\n")-1); + error_log('XML-RPC: xmlrpcmsg::parseResponse: HTTP error, got response: ' .$errstr); + $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (' . $errstr . ')'); + return $r; + } + + $GLOBALS['_xh']['headers'] = array(); + $GLOBALS['_xh']['cookies'] = array(); + + // be tolerant to usage of \n instead of \r\n to separate headers and data + // (even though it is not valid http) + $pos = strpos($data,"\r\n\r\n"); + if($pos || is_int($pos)) + { + $bd = $pos+4; + } + else + { + $pos = strpos($data,"\n\n"); + if($pos || is_int($pos)) + { + $bd = $pos+2; + } + else + { + // No separation between response headers and body: fault? + // we could take some action here instead of going on... + $bd = 0; + } + } + // be tolerant to line endings, and extra empty lines + $ar = split("\r?\n", trim(substr($data, 0, $pos))); + while(list(,$line) = @each($ar)) + { + // take care of multi-line headers and cookies + $arr = explode(':',$line,2); + if(count($arr) > 1) + { + $header_name = strtolower(trim($arr[0])); + /// @todo some other headers (the ones that allow a CSV list of values) + /// do allow many values to be passed using multiple header lines. + /// We should add content to $GLOBALS['_xh']['headers'][$header_name] + /// instead of replacing it for those... + if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') + { + if ($header_name == 'set-cookie2') + { + // version 2 cookies: + // there could be many cookies on one line, comma separated + $cookies = explode(',', $arr[1]); + } + else + { + $cookies = array($arr[1]); + } + foreach ($cookies as $cookie) + { + // glue together all received cookies, using a comma to separate them + // (same as php does with getallheaders()) + if (isset($GLOBALS['_xh']['headers'][$header_name])) + $GLOBALS['_xh']['headers'][$header_name] .= ', ' . trim($cookie); + else + $GLOBALS['_xh']['headers'][$header_name] = trim($cookie); + // parse cookie attributes, in case user wants to correctly honour them + // feature creep: only allow rfc-compliant cookie attributes? + $cookie = explode(';', $cookie); + foreach ($cookie as $pos => $val) + { + $val = explode('=', $val, 2); + $tag = trim($val[0]); + $val = trim(@$val[1]); + /// @todo with version 1 cookies, we should strip leading and trailing " chars + if ($pos == 0) + { + $cookiename = $tag; + $GLOBALS['_xh']['cookies'][$tag] = array(); + $GLOBALS['_xh']['cookies'][$cookiename]['value'] = urldecode($val); + } + else + { + $GLOBALS['_xh']['cookies'][$cookiename][$tag] = $val; + } + } + } + } + else + { + $GLOBALS['_xh']['headers'][$header_name] = trim($arr[1]); + } + } + elseif(isset($header_name)) + { + /// @todo version1 cookies might span multiple lines, thus breaking the parsing above + $GLOBALS['_xh']['headers'][$header_name] .= ' ' . trim($line); + } + } + + $data = substr($data, $bd); + + if($this->debug && count($GLOBALS['_xh']['headers'])) + { + print '
    ';
    +					foreach($GLOBALS['_xh']['headers'] as $header => $value)
    +					{
    +						print htmlentities("HEADER: $header: $value\n");
    +					}
    +					foreach($GLOBALS['_xh']['cookies'] as $header => $value)
    +					{
    +						print htmlentities("COOKIE: $header={$value['value']}\n");
    +					}
    +					print "
    \n"; + } + + // if CURL was used for the call, http headers have been processed, + // and dechunking + reinflating have been carried out + if(!$headers_processed) + { + // Decode chunked encoding sent by http 1.1 servers + if(isset($GLOBALS['_xh']['headers']['transfer-encoding']) && $GLOBALS['_xh']['headers']['transfer-encoding'] == 'chunked') + { + if(!$data = decode_chunked($data)) + { + error_log('XML-RPC: xmlrpcmsg::parseResponse: errors occurred when trying to rebuild the chunked data received from server'); + $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['dechunk_fail'], $GLOBALS['xmlrpcstr']['dechunk_fail']); + return $r; + } + } + + // Decode gzip-compressed stuff + // code shamelessly inspired from nusoap library by Dietrich Ayala + if(isset($GLOBALS['_xh']['headers']['content-encoding'])) + { + $GLOBALS['_xh']['headers']['content-encoding'] = str_replace('x-', '', $GLOBALS['_xh']['headers']['content-encoding']); + if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' || $GLOBALS['_xh']['headers']['content-encoding'] == 'gzip') + { + // if decoding works, use it. else assume data wasn't gzencoded + if(function_exists('gzinflate')) + { + if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) + { + $data = $degzdata; + if($this->debug) + print "
    ---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
    "; + } + elseif($GLOBALS['_xh']['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) + { + $data = $degzdata; + if($this->debug) + print "
    ---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
    "; + } + else + { + error_log('XML-RPC: xmlrpcmsg::parseResponse: errors occurred when trying to decode the deflated data received from server'); + $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['decompress_fail'], $GLOBALS['xmlrpcstr']['decompress_fail']); + return $r; + } + } + else + { + error_log('XML-RPC: xmlrpcmsg::parseResponse: the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); + $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['cannot_decompress'], $GLOBALS['xmlrpcstr']['cannot_decompress']); + return $r; + } + } + } + } // end of 'if needed, de-chunk, re-inflate response' + + // real stupid hack to avoid PHP 4 complaining about returning NULL by ref + $r = null; + $r =& $r; + return $r; + } + + /** + * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object. + * @param string $data the xmlrpc response, eventually including http headers + * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding + * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals' + * @return xmlrpcresp + * @access public + */ + function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals') + { + if($this->debug) + { + //by maHo, replaced htmlspecialchars with htmlentities + print "
    ---GOT---\n" . htmlentities($data) . "\n---END---\n
    "; + } + + if($data == '') + { + error_log('XML-RPC: xmlrpcmsg::parseResponse: no response received from server.'); + $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_data'], $GLOBALS['xmlrpcstr']['no_data']); + return $r; + } + + $GLOBALS['_xh']=array(); + + $raw_data = $data; + // parse the HTTP headers of the response, if present, and separate them from data + if(substr($data, 0, 4) == 'HTTP') + { + $r =& $this->parseResponseHeaders($data, $headers_processed); + if ($r) + { + // failed processing of HTTP response headers + // save into response obj the full payload received, for debugging + $r->raw_data = $data; + return $r; + } + } + else + { + $GLOBALS['_xh']['headers'] = array(); + $GLOBALS['_xh']['cookies'] = array(); + } + + if($this->debug) + { + $start = strpos($data, '', $start); + $comments = substr($data, $start, $end-$start); + print "
    ---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n
    "; + } + } + + // be tolerant of extra whitespace in response body + $data = trim($data); + + /// @todo return an error msg if $data=='' ? + + // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts) + // idea from Luca Mariano originally in PEARified version of the lib + $bd = false; + // Poor man's version of strrpos for php 4... + $pos = strpos($data, '
    '); + while($pos || is_int($pos)) + { + $bd = $pos+17; + $pos = strpos($data, '', $bd); + } + if($bd) + { + $data = substr($data, 0, $bd); + } + + // if user wants back raw xml, give it to him + if ($return_type == 'xml') + { + $r =& new xmlrpcresp($data, 0, '', 'xml'); + $r->hdrs = $GLOBALS['_xh']['headers']; + $r->_cookies = $GLOBALS['_xh']['cookies']; + $r->raw_data = $raw_data; + return $r; + } + + // try to 'guestimate' the character encoding of the received response + $resp_encoding = guess_encoding(@$GLOBALS['_xh']['headers']['content-type'], $data); + + $GLOBALS['_xh']['ac']=''; + //$GLOBALS['_xh']['qt']=''; //unused... + $GLOBALS['_xh']['stack'] = array(); + $GLOBALS['_xh']['valuestack'] = array(); + $GLOBALS['_xh']['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc + $GLOBALS['_xh']['isf_reason']=''; + $GLOBALS['_xh']['rt']=''; // 'methodcall or 'methodresponse' + + // if response charset encoding is not known / supported, try to use + // the default encoding and parse the xml anyway, but log a warning... + if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + // the following code might be better for mb_string enabled installs, but + // makes the lib about 200% slower... + //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + { + error_log('XML-RPC: xmlrpcmsg::parseResponse: invalid charset encoding of received response: '.$resp_encoding); + $resp_encoding = $GLOBALS['xmlrpc_defencoding']; + } + $parser = xml_parser_create($resp_encoding); + xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true); + // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell + // the xml parser to give us back data in the expected charset + xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']); + + if ($return_type == 'phpvals') + { + xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast'); + } + else + { + xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee'); + } + + xml_set_character_data_handler($parser, 'xmlrpc_cd'); + xml_set_default_handler($parser, 'xmlrpc_dh'); + + // first error check: xml not well formed + if(!xml_parse($parser, $data, count($data))) + { + // thanks to Peter Kocks + if((xml_get_current_line_number($parser)) == 1) + { + $errstr = 'XML error at line 1, check URL'; + } + else + { + $errstr = sprintf('XML error: %s at line %d, column %d', + xml_error_string(xml_get_error_code($parser)), + xml_get_current_line_number($parser), xml_get_current_column_number($parser)); + } + error_log($errstr); + $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'], $GLOBALS['xmlrpcstr']['invalid_return'].' ('.$errstr.')'); + xml_parser_free($parser); + if($this->debug) + { + print $errstr; + } + $r->hdrs = $GLOBALS['_xh']['headers']; + $r->_cookies = $GLOBALS['_xh']['cookies']; + $r->raw_data = $raw_data; + return $r; + } + xml_parser_free($parser); + // second error check: xml well formed but not xml-rpc compliant + if ($GLOBALS['_xh']['isf'] > 1) + { + if ($this->debug) + { + /// @todo echo something for user? + } + + $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'], + $GLOBALS['xmlrpcstr']['invalid_return'] . ' ' . $GLOBALS['_xh']['isf_reason']); + } + // third error check: parsing of the response has somehow gone boink. + // NB: shall we omit this check, since we trust the parsing code? + elseif ($return_type == 'xmlrpcvals' && !is_object($GLOBALS['_xh']['value'])) + { + // something odd has happened + // and it's time to generate a client side error + // indicating something odd went on + $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'], + $GLOBALS['xmlrpcstr']['invalid_return']); + } + else + { + if ($this->debug) + { + print "
    ---PARSED---\n";
    +					// somehow htmlentities chokes on var_export, and some full html string...
    +					//print htmlentitites(var_export($GLOBALS['_xh']['value'], true));
    +					print htmlspecialchars(var_export($GLOBALS['_xh']['value'], true));
    +					print "\n---END---
    "; + } + + // note that using =& will raise an error if $GLOBALS['_xh']['st'] does not generate an object. + $v =& $GLOBALS['_xh']['value']; + + if($GLOBALS['_xh']['isf']) + { + /// @todo we should test here if server sent an int and a string, + /// and/or coerce them into such... + if ($return_type == 'xmlrpcvals') + { + $errno_v = $v->structmem('faultCode'); + $errstr_v = $v->structmem('faultString'); + $errno = $errno_v->scalarval(); + $errstr = $errstr_v->scalarval(); + } + else + { + $errno = $v['faultCode']; + $errstr = $v['faultString']; + } + + if($errno == 0) + { + // FAULT returned, errno needs to reflect that + $errno = -1; + } + + $r =& new xmlrpcresp(0, $errno, $errstr); + } + else + { + $r=&new xmlrpcresp($v, 0, '', $return_type); + } + } + + $r->hdrs = $GLOBALS['_xh']['headers']; + $r->_cookies = $GLOBALS['_xh']['cookies']; + $r->raw_data = $raw_data; + return $r; + } + } + + class xmlrpcval + { + var $me=array(); + var $mytype=0; + var $_php_class=null; + + /** + * @param mixed $val + * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed + */ + function xmlrpcval($val=-1, $type='') + { + /// @todo: optimization creep - do not call addXX, do it all inline. + /// downside: booleans will not be coerced anymore + if($val!==-1 || $type!='') + { + // optimization creep: inlined all work done by constructor + switch($type) + { + case '': + $this->mytype=1; + $this->me['string']=$val; + break; + case 'i4': + case 'int': + case 'double': + case 'string': + case 'boolean': + case 'dateTime.iso8601': + case 'base64': + case 'null': + $this->mytype=1; + $this->me[$type]=$val; + break; + case 'array': + $this->mytype=2; + $this->me['array']=$val; + break; + case 'struct': + $this->mytype=3; + $this->me['struct']=$val; + break; + default: + error_log("XML-RPC: xmlrpcval::xmlrpcval: not a known type ($type)"); + } + /*if($type=='') + { + $type='string'; + } + if($GLOBALS['xmlrpcTypes'][$type]==1) + { + $this->addScalar($val,$type); + } + elseif($GLOBALS['xmlrpcTypes'][$type]==2) + { + $this->addArray($val); + } + elseif($GLOBALS['xmlrpcTypes'][$type]==3) + { + $this->addStruct($val); + }*/ + } + } + + /** + * Add a single php value to an (unitialized) xmlrpcval + * @param mixed $val + * @param string $type + * @return int 1 or 0 on failure + */ + function addScalar($val, $type='string') + { + $typeof=@$GLOBALS['xmlrpcTypes'][$type]; + if($typeof!=1) + { + error_log("XML-RPC: xmlrpcval::addScalar: not a scalar type ($type)"); + return 0; + } + + // coerce booleans into correct values + // NB: we should iether do it for datetimes, integers and doubles, too, + // or just plain remove this check, implemnted on booleans only... + if($type==$GLOBALS['xmlrpcBoolean']) + { + if(strcasecmp($val,'true')==0 || $val==1 || ($val==true && strcasecmp($val,'false'))) + { + $val=true; + } + else + { + $val=false; + } + } + + switch($this->mytype) + { + case 1: + error_log('XML-RPC: xmlrpcval::addScalar: scalar xmlrpcval can have only one value'); + return 0; + case 3: + error_log('XML-RPC: xmlrpcval::addScalar: cannot add anonymous scalar to struct xmlrpcval'); + return 0; + case 2: + // we're adding a scalar value to an array here + //$ar=$this->me['array']; + //$ar[]=&new xmlrpcval($val, $type); + //$this->me['array']=$ar; + // Faster (?) avoid all the costly array-copy-by-val done here... + $this->me['array'][]=&new xmlrpcval($val, $type); + return 1; + default: + // a scalar, so set the value and remember we're scalar + $this->me[$type]=$val; + $this->mytype=$typeof; + return 1; + } + } + + /** + * Add an array of xmlrpcval objects to an xmlrpcval + * @param array $vals + * @return int 1 or 0 on failure + * @access public + * + * @todo add some checking for $vals to be an array of xmlrpcvals? + */ + function addArray($vals) + { + if($this->mytype==0) + { + $this->mytype=$GLOBALS['xmlrpcTypes']['array']; + $this->me['array']=$vals; + return 1; + } + elseif($this->mytype==2) + { + // we're adding to an array here + $this->me['array'] = array_merge($this->me['array'], $vals); + return 1; + } + else + { + error_log('XML-RPC: xmlrpcval::addArray: already initialized as a [' . $this->kindOf() . ']'); + return 0; + } + } + + /** + * Add an array of named xmlrpcval objects to an xmlrpcval + * @param array $vals + * @return int 1 or 0 on failure + * @access public + * + * @todo add some checking for $vals to be an array? + */ + function addStruct($vals) + { + if($this->mytype==0) + { + $this->mytype=$GLOBALS['xmlrpcTypes']['struct']; + $this->me['struct']=$vals; + return 1; + } + elseif($this->mytype==3) + { + // we're adding to a struct here + $this->me['struct'] = array_merge($this->me['struct'], $vals); + return 1; + } + else + { + error_log('XML-RPC: xmlrpcval::addStruct: already initialized as a [' . $this->kindOf() . ']'); + return 0; + } + } + + // poor man's version of print_r ??? + // DEPRECATED! + function dump($ar) + { + foreach($ar as $key => $val) + { + echo "$key => $val
    "; + if($key == 'array') + { + while(list($key2, $val2) = each($val)) + { + echo "-- $key2 => $val2
    "; + } + } + } + } + + /** + * Returns a string containing "struct", "array" or "scalar" describing the base type of the value + * @return string + * @access public + */ + function kindOf() + { + switch($this->mytype) + { + case 3: + return 'struct'; + break; + case 2: + return 'array'; + break; + case 1: + return 'scalar'; + break; + default: + return 'undef'; + } + } + + /** + * @access private + */ + function serializedata($typ, $val, $charset_encoding='') + { + $rs=''; + switch(@$GLOBALS['xmlrpcTypes'][$typ]) + { + case 1: + switch($typ) + { + case $GLOBALS['xmlrpcBase64']: + $rs.="<${typ}>" . base64_encode($val) . ""; + break; + case $GLOBALS['xmlrpcBoolean']: + $rs.="<${typ}>" . ($val ? '1' : '0') . ""; + break; + case $GLOBALS['xmlrpcString']: + // G. Giunta 2005/2/13: do NOT use htmlentities, since + // it will produce named html entities, which are invalid xml + $rs.="<${typ}>" . xmlrpc_encode_entitites($val, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding). ""; + break; + case $GLOBALS['xmlrpcInt']: + case $GLOBALS['xmlrpcI4']: + $rs.="<${typ}>".(int)$val.""; + break; + case $GLOBALS['xmlrpcDouble']: + $rs.="<${typ}>".(double)$val.""; + break; + case $GLOBALS['xmlrpcNull']: + $rs.=""; + break; + default: + // no standard type value should arrive here, but provide a possibility + // for xmlrpcvals of unknown type... + $rs.="<${typ}>${val}"; + } + break; + case 3: + // struct + if ($this->_php_class) + { + $rs.='\n"; + } + else + { + $rs.="\n"; + } + foreach($val as $key2 => $val2) + { + $rs.=''.xmlrpc_encode_entitites($key2, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding)."\n"; + //$rs.=$this->serializeval($val2); + $rs.=$val2->serialize($charset_encoding); + $rs.="\n"; + } + $rs.=''; + break; + case 2: + // array + $rs.="\n\n"; + for($i=0; $iserializeval($val[$i]); + $rs.=$val[$i]->serialize($charset_encoding); + } + $rs.="\n"; + break; + default: + break; + } + return $rs; + } + + /** + * Returns xml representation of the value. XML prologue not included + * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed + * @return string + * @access public + */ + function serialize($charset_encoding='') + { + // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals... + //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval'))) + //{ + reset($this->me); + list($typ, $val) = each($this->me); + return '' . $this->serializedata($typ, $val, $charset_encoding) . "\n"; + //} + } + + // DEPRECATED + function serializeval($o) + { + // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals... + //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval'))) + //{ + $ar=$o->me; + reset($ar); + list($typ, $val) = each($ar); + return '' . $this->serializedata($typ, $val) . "\n"; + //} + } + + /** + * Checks wheter a struct member with a given name is present. + * Works only on xmlrpcvals of type struct. + * @param string $m the name of the struct member to be looked up + * @return boolean + * @access public + */ + function structmemexists($m) + { + return array_key_exists($m, $this->me['struct']); + } + + /** + * Returns the value of a given struct member (an xmlrpcval object in itself). + * Will raise a php warning if struct member of given name does not exist + * @param string $m the name of the struct member to be looked up + * @return xmlrpcval + * @access public + */ + function structmem($m) + { + return $this->me['struct'][$m]; + } + + /** + * Reset internal pointer for xmlrpcvals of type struct. + * @access public + */ + function structreset() + { + reset($this->me['struct']); + } + + /** + * Return next member element for xmlrpcvals of type struct. + * @return xmlrpcval + * @access public + */ + function structeach() + { + return each($this->me['struct']); + } + + // DEPRECATED! this code looks like it is very fragile and has not been fixed + // for a long long time. Shall we remove it for 2.0? + function getval() + { + // UNSTABLE + reset($this->me); + list($a,$b)=each($this->me); + // contributed by I Sofer, 2001-03-24 + // add support for nested arrays to scalarval + // i've created a new method here, so as to + // preserve back compatibility + + if(is_array($b)) + { + @reset($b); + while(list($id,$cont) = @each($b)) + { + $b[$id] = $cont->scalarval(); + } + } + + // add support for structures directly encoding php objects + if(is_object($b)) + { + $t = get_object_vars($b); + @reset($t); + while(list($id,$cont) = @each($t)) + { + $t[$id] = $cont->scalarval(); + } + @reset($t); + while(list($id,$cont) = @each($t)) + { + @$b->$id = $cont; + } + } + // end contrib + return $b; + } + + /** + * Returns the value of a scalar xmlrpcval + * @return mixed + * @access public + */ + function scalarval() + { + reset($this->me); + list(,$b)=each($this->me); + return $b; + } + + /** + * Returns the type of the xmlrpcval. + * For integers, 'int' is always returned in place of 'i4' + * @return string + * @access public + */ + function scalartyp() + { + reset($this->me); + list($a,)=each($this->me); + if($a==$GLOBALS['xmlrpcI4']) + { + $a=$GLOBALS['xmlrpcInt']; + } + return $a; + } + + /** + * Returns the m-th member of an xmlrpcval of struct type + * @param integer $m the index of the value to be retrieved (zero based) + * @return xmlrpcval + * @access public + */ + function arraymem($m) + { + return $this->me['array'][$m]; + } + + /** + * Returns the number of members in an xmlrpcval of array type + * @return integer + * @access public + */ + function arraysize() + { + return count($this->me['array']); + } + + /** + * Returns the number of members in an xmlrpcval of struct type + * @return integer + * @access public + */ + function structsize() + { + return count($this->me['struct']); + } + } + + + // date helpers + + /** + * Given a timestamp, return the corresponding ISO8601 encoded string. + * + * Really, timezones ought to be supported + * but the XML-RPC spec says: + * + * "Don't assume a timezone. It should be specified by the server in its + * documentation what assumptions it makes about timezones." + * + * These routines always assume localtime unless + * $utc is set to 1, in which case UTC is assumed + * and an adjustment for locale is made when encoding + * + * @param int $timet (timestamp) + * @param int $utc (0 or 1) + * @return string + */ + function iso8601_encode($timet, $utc=0) + { + if(!$utc) + { + $t=strftime("%Y%m%dT%H:%M:%S", $timet); + } + else + { + if(function_exists('gmstrftime')) + { + // gmstrftime doesn't exist in some versions + // of PHP + $t=gmstrftime("%Y%m%dT%H:%M:%S", $timet); + } + else + { + $t=strftime("%Y%m%dT%H:%M:%S", $timet-date('Z')); + } + } + return $t; + } + + /** + * Given an ISO8601 date string, return a timet in the localtime, or UTC + * @param string $idate + * @param int $utc either 0 or 1 + * @return int (datetime) + */ + function iso8601_decode($idate, $utc=0) + { + $t=0; + if(preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})/', $idate, $regs)) + { + if($utc) + { + $t=gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); + } + else + { + $t=mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); + } + } + return $t; + } + + /** + * Takes an xmlrpc value in PHP xmlrpcval object format and translates it into native PHP types. + * + * Works with xmlrpc message objects as input, too. + * + * Given proper options parameter, can rebuild generic php object instances + * (provided those have been encoded to xmlrpc format using a corresponding + * option in php_xmlrpc_encode()) + * PLEASE NOTE that rebuilding php objects involves calling their constructor function. + * This means that the remote communication end can decide which php code will + * get executed on your server, leaving the door possibly open to 'php-injection' + * style of attacks (provided you have some classes defined on your server that + * might wreak havoc if instances are built outside an appropriate context). + * Make sure you trust the remote server/client before eanbling this! + * + * @author Dan Libby (dan@libby.com) + * + * @param xmlrpcval $xmlrpc_val + * @param array $options if 'decode_php_objs' is set in the options array, xmlrpc structs can be decoded into php objects + * @return mixed + */ + function php_xmlrpc_decode($xmlrpc_val, $options=array()) + { + switch($xmlrpc_val->kindOf()) + { + case 'scalar': + if (in_array('extension_api', $options)) + { + reset($xmlrpc_val->me); + list($typ,$val) = each($xmlrpc_val->me); + switch ($typ) + { + case 'dateTime.iso8601': + $xmlrpc_val->scalar = $val; + $xmlrpc_val->xmlrpc_type = 'datetime'; + $xmlrpc_val->timestamp = iso8601_decode($val); + return $xmlrpc_val; + case 'base64': + $xmlrpc_val->scalar = $val; + $xmlrpc_val->type = $typ; + return $xmlrpc_val; + default: + return $xmlrpc_val->scalarval(); + } + } + return $xmlrpc_val->scalarval(); + case 'array': + $size = $xmlrpc_val->arraysize(); + $arr = array(); + for($i = 0; $i < $size; $i++) + { + $arr[] = php_xmlrpc_decode($xmlrpc_val->arraymem($i), $options); + } + return $arr; + case 'struct': + $xmlrpc_val->structreset(); + // If user said so, try to rebuild php objects for specific struct vals. + /// @todo should we raise a warning for class not found? + // shall we check for proper subclass of xmlrpcval instead of + // presence of _php_class to detect what we can do? + if (in_array('decode_php_objs', $options) && $xmlrpc_val->_php_class != '' + && class_exists($xmlrpc_val->_php_class)) + { + $obj = @new $xmlrpc_val->_php_class; + while(list($key,$value)=$xmlrpc_val->structeach()) + { + $obj->$key = php_xmlrpc_decode($value, $options); + } + return $obj; + } + else + { + $arr = array(); + while(list($key,$value)=$xmlrpc_val->structeach()) + { + $arr[$key] = php_xmlrpc_decode($value, $options); + } + return $arr; + } + case 'msg': + $paramcount = $xmlrpc_val->getNumParams(); + $arr = array(); + for($i = 0; $i < $paramcount; $i++) + { + $arr[] = php_xmlrpc_decode($xmlrpc_val->getParam($i)); + } + return $arr; + } + } + + // This constant left here only for historical reasons... + // it was used to decide if we have to define xmlrpc_encode on our own, but + // we do not do it anymore + if(function_exists('xmlrpc_decode')) + { + define('XMLRPC_EPI_ENABLED','1'); + } + else + { + define('XMLRPC_EPI_ENABLED','0'); + } + + /** + * Takes native php types and encodes them into xmlrpc PHP object format. + * It will not re-encode xmlrpcval objects. + * + * Feature creep -- could support more types via optional type argument + * (string => datetime support has been added, ??? => base64 not yet) + * + * If given a proper options parameter, php object instances will be encoded + * into 'special' xmlrpc values, that can later be decoded into php objects + * by calling php_xmlrpc_decode() with a corresponding option + * + * @author Dan Libby (dan@libby.com) + * + * @param mixed $php_val the value to be converted into an xmlrpcval object + * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api' + * @return xmlrpcval + */ + function &php_xmlrpc_encode($php_val, $options=array()) + { + $type = gettype($php_val); + switch($type) + { + case 'string': + if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $php_val)) + $xmlrpc_val =& new xmlrpcval($php_val, $GLOBALS['xmlrpcDateTime']); + else + $xmlrpc_val =& new xmlrpcval($php_val, $GLOBALS['xmlrpcString']); + break; + case 'integer': + $xmlrpc_val =& new xmlrpcval($php_val, $GLOBALS['xmlrpcInt']); + break; + case 'double': + $xmlrpc_val =& new xmlrpcval($php_val, $GLOBALS['xmlrpcDouble']); + break; + // + // Add support for encoding/decoding of booleans, since they are supported in PHP + case 'boolean': + $xmlrpc_val =& new xmlrpcval($php_val, $GLOBALS['xmlrpcBoolean']); + break; + // + case 'array': + // PHP arrays can be encoded to either xmlrpc structs or arrays, + // depending on wheter they are hashes or plain 0..n integer indexed + // A shorter one-liner would be + // $tmp = array_diff(array_keys($php_val), range(0, count($php_val)-1)); + // but execution time skyrockets! + $j = 0; + $arr = array(); + $ko = false; + foreach($php_val as $key => $val) + { + $arr[$key] =& php_xmlrpc_encode($val, $options); + if(!$ko && $key !== $j) + { + $ko = true; + } + $j++; + } + if($ko) + { + $xmlrpc_val =& new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']); + } + else + { + $xmlrpc_val =& new xmlrpcval($arr, $GLOBALS['xmlrpcArray']); + } + break; + case 'object': + if(is_a($php_val, 'xmlrpcval')) + { + $xmlrpc_val = $php_val; + } + else + { + $arr = array(); + while(list($k,$v) = each($php_val)) + { + $arr[$k] = php_xmlrpc_encode($v, $options); + } + $xmlrpc_val =& new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']); + if (in_array('encode_php_objs', $options)) + { + // let's save original class name into xmlrpcval: + // might be useful later on... + $xmlrpc_val->_php_class = get_class($php_val); + } + } + break; + case 'NULL': + if (in_array('extension_api', $options)) + { + $xmlrpc_val =& new xmlrpcval('', $GLOBALS['xmlrpcString']); + } + if (in_array('null_extension', $options)) + { + $xmlrpc_val =& new xmlrpcval('', $GLOBALS['xmlrpcNull']); + } + else + { + $xmlrpc_val =& new xmlrpcval(); + } + break; + case 'resource': + if (in_array('extension_api', $options)) + { + $xmlrpc_val =& new xmlrpcval((int)$php_val, $GLOBALS['xmlrpcInt']); + } + else + { + $xmlrpc_val =& new xmlrpcval(); + } + // catch "user function", "unknown type" + default: + // giancarlo pinerolo + // it has to return + // an empty object in case, not a boolean. + $xmlrpc_val =& new xmlrpcval(); + break; + } + return $xmlrpc_val; + } + + /** + * Convert the xml representation of a method response, method request or single + * xmlrpc value into the appropriate object (a.k.a. deserialize) + * @param string $xml_val + * @param array $options + * @return mixed false on error, or an instance of either xmlrpcval, xmlrpcmsg or xmlrpcresp + */ + function php_xmlrpc_decode_xml($xml_val, $options=array()) + { + $GLOBALS['_xh'] = array(); + $GLOBALS['_xh']['ac'] = ''; + $GLOBALS['_xh']['stack'] = array(); + $GLOBALS['_xh']['valuestack'] = array(); + $GLOBALS['_xh']['params'] = array(); + $GLOBALS['_xh']['pt'] = array(); + $GLOBALS['_xh']['isf'] = 0; + $GLOBALS['_xh']['isf_reason'] = ''; + $GLOBALS['_xh']['method'] = false; + $GLOBALS['_xh']['rt'] = ''; + /// @todo 'guestimate' encoding + $parser = xml_parser_create(); + xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true); + xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']); + xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee'); + xml_set_character_data_handler($parser, 'xmlrpc_cd'); + xml_set_default_handler($parser, 'xmlrpc_dh'); + if(!xml_parse($parser, $xml_val, 1)) + { + $errstr = sprintf('XML error: %s at line %d, column %d', + xml_error_string(xml_get_error_code($parser)), + xml_get_current_line_number($parser), xml_get_current_column_number($parser)); + error_log($errstr); + xml_parser_free($parser); + return false; + } + xml_parser_free($parser); + if ($GLOBALS['_xh']['isf'] > 1) // test that $GLOBALS['_xh']['value'] is an obj, too??? + { + error_log($GLOBALS['_xh']['isf_reason']); + return false; + } + switch ($GLOBALS['_xh']['rt']) + { + case 'methodresponse': + $v =& $GLOBALS['_xh']['value']; + if ($GLOBALS['_xh']['isf'] == 1) + { + $vc = $v->structmem('faultCode'); + $vs = $v->structmem('faultString'); + $r =& new xmlrpcresp(0, $vc->scalarval(), $vs->scalarval()); + } + else + { + $r =& new xmlrpcresp($v); + } + return $r; + case 'methodcall': + $m =& new xmlrpcmsg($GLOBALS['_xh']['method']); + for($i=0; $i < count($GLOBALS['_xh']['params']); $i++) + { + $m->addParam($GLOBALS['_xh']['params'][$i]); + } + return $m; + case 'value': + return $GLOBALS['_xh']['value']; + default: + return false; + } + } + + /** + * decode a string that is encoded w/ "chunked" transfer encoding + * as defined in rfc2068 par. 19.4.6 + * code shamelessly stolen from nusoap library by Dietrich Ayala + * + * @param string $buffer the string to be decoded + * @return string + */ + function decode_chunked($buffer) + { + // length := 0 + $length = 0; + $new = ''; + + // read chunk-size, chunk-extension (if any) and crlf + // get the position of the linebreak + $chunkend = strpos($buffer,"\r\n") + 2; + $temp = substr($buffer,0,$chunkend); + $chunk_size = hexdec( trim($temp) ); + $chunkstart = $chunkend; + while($chunk_size > 0) + { + $chunkend = strpos($buffer, "\r\n", $chunkstart + $chunk_size); + + // just in case we got a broken connection + if($chunkend == false) + { + $chunk = substr($buffer,$chunkstart); + // append chunk-data to entity-body + $new .= $chunk; + $length += strlen($chunk); + break; + } + + // read chunk-data and crlf + $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart); + // append chunk-data to entity-body + $new .= $chunk; + // length := length + chunk-size + $length += strlen($chunk); + // read chunk-size and crlf + $chunkstart = $chunkend + 2; + + $chunkend = strpos($buffer,"\r\n",$chunkstart)+2; + if($chunkend == false) + { + break; //just in case we got a broken connection + } + $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart); + $chunk_size = hexdec( trim($temp) ); + $chunkstart = $chunkend; + } + return $new; + } + + /** + * xml charset encoding guessing helper function. + * Tries to determine the charset encoding of an XML chunk + * received over HTTP. + * NB: according to the spec (RFC 3023, if text/xml content-type is received over HTTP without a content-type, + * we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of unconforming (legacy?) clients/servers, + * which will be most probably using UTF-8 anyway... + * + * @param string $httpheaders the http Content-type header + * @param string $xmlchunk xml content buffer + * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled) + * + * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!! + */ + function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=null) + { + // discussion: see http://www.yale.edu/pclt/encoding/ + // 1 - test if encoding is specified in HTTP HEADERS + + //Details: + // LWS: (\13\10)?( |\t)+ + // token: (any char but excluded stuff)+ + // header: Content-type = ...; charset=value(; ...)* + // where value is of type token, no LWS allowed between 'charset' and value + // Note: we do not check for invalid chars in VALUE: + // this had better be done using pure ereg as below + + /// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it? + $matches = array(); + if(preg_match('/;\s*charset=([^;]+)/i', $httpheader, $matches)) + { + return strtoupper(trim($matches[1])); + } + + // 2 - scan the first bytes of the data for a UTF-16 (or other) BOM pattern + // (source: http://www.w3.org/TR/2000/REC-xml-20001006) + // NOTE: actually, according to the spec, even if we find the BOM and determine + // an encoding, we should check if there is an encoding specified + // in the xml declaration, and verify if they match. + /// @todo implement check as described above? + /// @todo implement check for first bytes of string even without a BOM? (It sure looks harder than for cases WITH a BOM) + if(preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlchunk)) + { + return 'UCS-4'; + } + elseif(preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlchunk)) + { + return 'UTF-16'; + } + elseif(preg_match('/^(\xEF\xBB\xBF)/', $xmlchunk)) + { + return 'UTF-8'; + } + + // 3 - test if encoding is specified in the xml declaration + // Details: + // SPACE: (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+ + // EQ: SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]* + if (preg_match('/^<\?xml\s+version\s*=\s*'. "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))". + '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/", + $xmlchunk, $matches)) + { + return strtoupper(substr($matches[2], 1, -1)); + } + + // 4 - if mbstring is available, let it do the guesswork + // NB: we favour finding an encoding that is compatible with what we can process + if(extension_loaded('mbstring')) + { + if($encoding_prefs) + { + $enc = mb_detect_encoding($xmlchunk, $encoding_prefs); + } + else + { + $enc = mb_detect_encoding($xmlchunk); + } + // NB: mb_detect likes to call it ascii, xml parser likes to call it US_ASCII... + // IANA also likes better US-ASCII, so go with it + if($enc == 'ASCII') + { + $enc = 'US-'.$enc; + } + return $enc; + } + else + { + // no encoding specified: as per HTTP1.1 assume it is iso-8859-1? + // Both RFC 2616 (HTTP 1.1) and 1945(http 1.0) clearly state that for text/xxx content types + // this should be the standard. And we should be getting text/xml as request and response. + // BUT we have to be backward compatible with the lib, which always used UTF-8 as default... + return $GLOBALS['xmlrpc_defencoding']; + } + } + + /** + * Checks if a given charset encoding is present in a list of encodings or + * if it is a valid subset of any encoding in the list + * @param string $encoding charset to be tested + * @param mixed $validlist comma separated list of valid charsets (or array of charsets) + */ + function is_valid_charset($encoding, $validlist) + { + $charset_supersets = array( + 'US-ASCII' => array ('ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4', + 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', + 'ISO-8859-9', 'ISO-8859-10', 'ISO-8859-11', 'ISO-8859-12', + 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'UTF-8', + 'EUC-JP', 'EUC-', 'EUC-KR', 'EUC-CN') + ); + if (is_string($validlist)) + $validlist = explode(',', $validlist); + if (@in_array(strtoupper($encoding), $validlist)) + return true; + else + { + if (array_key_exists($encoding, $charset_supersets)) + foreach ($validlist as $allowed) + if (in_array($allowed, $charset_supersets[$encoding])) + return true; + return false; + } + } + +?> \ No newline at end of file diff --git a/lib/xmlrpc_wrappers.inc b/lib/xmlrpc_wrappers.inc new file mode 100644 index 0000000..0b6f5b2 --- /dev/null +++ b/lib/xmlrpc_wrappers.inc @@ -0,0 +1,818 @@ +isInternal()) + { + // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs + // instead of getparameters to fully reflect internal php functions ? + error_log('XML-RPC: function to be wrapped is internal: '.$funcname); + return false; + } + + // retrieve parameter names, types and description from javadoc comments + + // function description + $desc = ''; + // type of return val: by default 'any' + $returns = $GLOBALS['xmlrpcValue']; + // desc of return val + $returnsDocs = ''; + // type + name of function parameters + $paramDocs = array(); + + $docs = $func->getDocComment(); + if($docs != '') + { + $docs = explode("\n", $docs); + $i = 0; + foreach($docs as $doc) + { + $doc = trim($doc, " \r\t/*"); + if(strlen($doc) && strpos($doc, '@') !== 0 && !$i) + { + if($desc) + { + $desc .= "\n"; + } + $desc .= $doc; + } + elseif(strpos($doc, '@param') === 0) + { + // syntax: @param type [$name] desc + if(preg_match('/@param\s+(\S+)(\s+\$\S+)?\s+(.+)/', $doc, $matches)) + { + if(strpos($matches[1], '|')) + { + //$paramDocs[$i]['type'] = explode('|', $matches[1]); + $paramDocs[$i]['type'] = 'mixed'; + } + else + { + $paramDocs[$i]['type'] = $matches[1]; + } + $paramDocs[$i]['name'] = trim($matches[2]); + $paramDocs[$i]['doc'] = $matches[3]; + } + $i++; + } + elseif(strpos($doc, '@return') === 0) + { + // syntax: @return type desc + //$returns = preg_split('/\s+/', $doc); + if(preg_match('/@return\s+(\S+)\s+(.+)/', $doc, $matches)) + { + $returns = php_2_xmlrpc_type($matches[1]); + if(isset($matches[2])) + { + $returnsDocs = $matches[2]; + } + } + } + } + } + + // execute introspection of actual function prototype + $params = array(); + $i = 0; + foreach($func->getParameters() as $paramobj) + { + $params[$i] = array(); + $params[$i]['name'] = '$'.$paramobj->getName(); + $params[$i]['isoptional'] = $paramobj->isOptional(); + $i++; + } + + + // start building of PHP code to be eval'd + $innercode = ''; + $i = 0; + $parsvariations = array(); + $pars = array(); + $pnum = count($params); + foreach($params as $param) + { + if (isset($paramDocs[$i]['name']) && $paramDocs[$i]['name'] && strtolower($paramDocs[$i]['name']) != strtolower($param['name'])) + { + // param name from phpdoc info does not match param definition! + $paramDocs[$i]['type'] = 'mixed'; + } + + if($param['isoptional']) + { + // this particular parameter is optional. save as valid previous list of parameters + $innercode .= "if (\$paramcount > $i) {\n"; + $parsvariations[] = $pars; + } + $innercode .= "\$p$i = \$msg->getParam($i);\n"; + if ($decode_php_objects) + { + $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i, array('decode_php_objs'));\n"; + } + else + { + $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i);\n"; + } + + $pars[] = "\$p$i"; + $i++; + if($param['isoptional']) + { + $innercode .= "}\n"; + } + if($i == $pnum) + { + // last allowed parameters combination + $parsvariations[] = $pars; + } + } + + $sigs = array(); + $psigs = array(); + if(count($parsvariations) == 0) + { + // only known good synopsis = no parameters + $parsvariations[] = array(); + $minpars = 0; + } + else + { + $minpars = count($parsvariations[0]); + } + + if($minpars) + { + // add to code the check for min params number + // NB: this check needs to be done BEFORE decoding param values + $innercode = "\$paramcount = \$msg->getNumParams();\n" . + "if (\$paramcount < $minpars) return new {$prefix}resp(0, {$GLOBALS['xmlrpcerr']['incorrect_params']}, '{$GLOBALS['xmlrpcstr']['incorrect_params']}');\n" . $innercode; + } + else + { + $innercode = "\$paramcount = \$msg->getNumParams();\n" . $innercode; + } + + $innercode .= "\$np = false;\n"; + foreach($parsvariations as $pars) + { + $innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$funcname(" . implode(',', $pars) . "); else\n"; + // build a 'generic' signature (only use an appropriate return type) + $sig = array($returns); + $psig = array($returnsDocs); + for($i=0; $i < count($pars); $i++) + { + if (isset($paramDocs[$i]['type'])) + { + $sig[] = php_2_xmlrpc_type($paramDocs[$i]['type']); + } + else + { + $sig[] = $GLOBALS['xmlrpcValue']; + } + $psig[] = isset($paramDocs[$i]['doc']) ? $paramDocs[$i]['doc'] : ''; + } + $sigs[] = $sig; + $psigs[] = $psig; + } + $innercode .= "\$np = true;\n"; + $innercode .= "if (\$np) return new {$prefix}resp(0, {$GLOBALS['xmlrpcerr']['incorrect_params']}, '{$GLOBALS['xmlrpcstr']['incorrect_params']}'); else {\n"; + //$innercode .= "if (\$_xmlrpcs_error_occurred) return new xmlrpcresp(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n"; + $innercode .= "if (is_a(\$retval, '{$prefix}resp')) return \$retval; else\n"; + if($returns == $GLOBALS['xmlrpcDateTime'] || $returns == $GLOBALS['xmlrpcBase64']) + { + $innercode .= "return new {$prefix}resp(new {$prefix}val(\$retval, '$returns'));"; + } + else + { + if ($encode_php_objects) + $innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval, array('encode_php_objs')));\n"; + else + $innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval));\n"; + } + // shall we exclude functions returning by ref? + // if($func->returnsReference()) + // return false; + $code = "function $xmlrpcfuncname(\$msg) {\n" . $innercode . "}\n}"; + //print_r($code); + if ($buildit) + { + $allOK = 0; + eval($code.'$allOK=1;'); + // alternative + //$xmlrpcfuncname = create_function('$m', $innercode); + + if(!$allOK) + { + error_log('XML-RPC: could not create function '.$xmlrpcfuncname.' to wrap php function '.$funcname); + return false; + } + } + + /// @todo examine if $paramDocs matches $parsvariations and build array for + /// usage as method signature, plus put together a nice string for docs + + $ret = array('function' => $xmlrpcfuncname, 'signature' => $sigs, 'docstring' => $desc, 'signature_docs' => $psigs, 'source' => $code); + return $ret; + } + } + + /** + * Given an xmlrpc client and a method name, register a php wrapper function + * that will call it and return results using native php types for both + * params and results. The generated php function will return an xmlrpcresp + * oject for failed xmlrpc calls + * + * Known limitations: + * - server must support system.methodsignature for the wanted xmlrpc method + * - for methods that expose many signatures, only one can be picked (we + * could in priciple check if signatures differ only by number of params + * and not by type, but it would be more complication than we can spare time) + * - nested xmlrpc params: the caller of the generated php function has to + * encode on its own the params passed to the php function if these are structs + * or arrays whose (sub)members include values of type datetime or base64 + * + * Notes: the connection properties of the given client will be copied + * and reused for the connection used during the call to the generated + * php function. + * Calling the generated php function 'might' be slow: a new xmlrpc client + * is created on every invocation and an xmlrpc-connection opened+closed. + * An extra 'debug' param is appended to param list of xmlrpc method, useful + * for debugging purposes. + * + * @param xmlrpc_client $client an xmlrpc client set up correctly to communicate with target server + * @param string $methodname the xmlrpc method to be mapped to a php function + * @param array $extra_options array of options that specify conversion details. valid ptions include + * integer signum the index of the method signature to use in mapping (if method exposes many sigs) + * integer timeout timeout (in secs) to be used when executing function/calling remote method + * string protocol 'http' (default), 'http11' or 'https' + * string new_function_name the name of php function to create. If unsepcified, lib will pick an appropriate name + * string return_source if true return php code w. function definition instead fo function name + * bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects + * bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers --- + * mixed return_on_fault a php value to be returned when the xmlrpc call fails/returns a fault response (by default the xmlrpcresp object is returned in this case). If a string is used, '%faultCode%' and '%faultString%' tokens will be substituted with actual error values + * bool debug set it to 1 or 2 to see debug results of querying server for method synopsis + * @return string the name of the generated php function (or false) - OR AN ARRAY... + */ + function wrap_xmlrpc_method($client, $methodname, $extra_options=0, $timeout=0, $protocol='', $newfuncname='') + { + // mind numbing: let caller use sane calling convention (as per javadoc, 3 params), + // OR the 2.0 calling convention (no ptions) - we really love backward compat, don't we? + if (!is_array($extra_options)) + { + $signum = $extra_options; + $extra_options = array(); + } + else + { + $signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0; + $timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0; + $protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : ''; + $newfuncname = isset($extra_options['new_function_name']) ? $extra_options['new_function_name'] : ''; + } + //$encode_php_objects = in_array('encode_php_objects', $extra_options); + //$verbatim_client_copy = in_array('simple_client_copy', $extra_options) ? 1 : + // in_array('build_class_code', $extra_options) ? 2 : 0; + + $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false; + $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false; + $simple_client_copy = isset($extra_options['simple_client_copy']) ? (int)($extra_options['simple_client_copy']) : 0; + $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true; + $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc'; + if (isset($extra_options['return_on_fault'])) + { + $decode_fault = true; + $fault_response = $extra_options['return_on_fault']; + } + else + { + $decode_fault = false; + $fault_response = ''; + } + $debug = isset($extra_options['debug']) ? ($extra_options['debug']) : 0; + + $msgclass = $prefix.'msg'; + $valclass = $prefix.'val'; + $decodefunc = 'php_'.$prefix.'_decode'; + + $msg =& new $msgclass('system.methodSignature'); + $msg->addparam(new $valclass($methodname)); + $client->setDebug($debug); + $response =& $client->send($msg, $timeout, $protocol); + if($response->faultCode()) + { + error_log('XML-RPC: could not retrieve method signature from remote server for method '.$methodname); + return false; + } + else + { + $msig = $response->value(); + if ($client->return_type != 'phpvals') + { + $msig = $decodefunc($msig); + } + if(!is_array($msig) || count($msig) <= $signum) + { + error_log('XML-RPC: could not retrieve method signature nr.'.$signum.' from remote server for method '.$methodname); + return false; + } + else + { + // pick a suitable name for the new function, avoiding collisions + if($newfuncname != '') + { + $xmlrpcfuncname = $newfuncname; + } + else + { + // take care to insure that methodname is translated to valid + // php function name + $xmlrpcfuncname = $prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'), + array('_', ''), $methodname); + } + while($buildit && function_exists($xmlrpcfuncname)) + { + $xmlrpcfuncname .= 'x'; + } + + $msig = $msig[$signum]; + $mdesc = ''; + // if in 'offline' mode, get method description too. + // in online mode, favour speed of operation + if(!$buildit) + { + $msg =& new $msgclass('system.methodHelp'); + $msg->addparam(new $valclass($methodname)); + $response =& $client->send($msg, $timeout, $protocol); + if (!$response->faultCode()) + { + $mdesc = $response->value(); + if ($client->return_type != 'phpvals') + { + $mdesc = $mdesc->scalarval(); + } + } + } + + $results = build_remote_method_wrapper_code($client, $methodname, + $xmlrpcfuncname, $msig, $mdesc, $timeout, $protocol, $simple_client_copy, + $prefix, $decode_php_objects, $encode_php_objects, $decode_fault, + $fault_response); + + //print_r($code); + if ($buildit) + { + $allOK = 0; + eval($results['source'].'$allOK=1;'); + // alternative + //$xmlrpcfuncname = create_function('$m', $innercode); + if($allOK) + { + return $xmlrpcfuncname; + } + else + { + error_log('XML-RPC: could not create function '.$xmlrpcfuncname.' to wrap remote method '.$methodname); + return false; + } + } + else + { + $results['function'] = $xmlrpcfuncname; + return $results; + } + } + } + } + + /** + * Similar to wrap_xmlrpc_method, but will generate a php class that wraps + * all xmlrpc methods exposed by the remote server as own methods. + * For more details see wrap_xmlrpc_method. + * @param xmlrpc_client $client the client obj all set to query the desired server + * @param array $extra_options list of options for wrapped code + * @return mixed false on error, the name of the created class if all ok or an array with code, class name and comments (if the appropriatevoption is set in extra_options) + */ + function wrap_xmlrpc_server($client, $extra_options=array()) + { + $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : ''; + $signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0; + $timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0; + $protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : ''; + $newclassname = isset($extra_options['new_class_name']) ? $extra_options['new_class_name'] : ''; + $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false; + $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false; + $verbatim_client_copy = isset($extra_options['simple_client_copy']) ? !($extra_options['simple_client_copy']) : true; + $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true; + $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc'; + + $msgclass = $prefix.'msg'; + //$valclass = $prefix.'val'; + $decodefunc = 'php_'.$prefix.'_decode'; + + $msg =& new $msgclass('system.listMethods'); + $response =& $client->send($msg, $timeout, $protocol); + if($response->faultCode()) + { + error_log('XML-RPC: could not retrieve method list from remote server'); + return false; + } + else + { + $mlist = $response->value(); + if ($client->return_type != 'phpvals') + { + $mlist = $decodefunc($mlist); + } + if(!is_array($mlist) || !count($mlist)) + { + error_log('XML-RPC: could not retrieve meaningful method list from remote server'); + return false; + } + else + { + // pick a suitable name for the new function, avoiding collisions + if($newclassname != '') + { + $xmlrpcclassname = $newclassname; + } + else + { + $xmlrpcclassname = $prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'), + array('_', ''), $client->server).'_client'; + } + while($buildit && class_exists($xmlrpcclassname)) + { + $xmlrpcclassname .= 'x'; + } + + /// @todo add function setdebug() to new class, to enable/disable debugging + $source = "class $xmlrpcclassname\n{\nvar \$client;\n\n"; + $source .= "function $xmlrpcclassname()\n{\n"; + $source .= build_client_wrapper_code($client, $verbatim_client_copy, $prefix); + $source .= "\$this->client =& \$client;\n}\n\n"; + $opts = array('simple_client_copy' => 2, 'return_source' => true, + 'timeout' => $timeout, 'protocol' => $protocol, + 'encode_php_objs' => $encode_php_objects, 'prefix' => $prefix, + 'decode_php_objs' => $decode_php_objects + ); + /// @todo build javadoc for class definition, too + foreach($mlist as $mname) + { + if ($methodfilter == '' || preg_match($methodfilter, $mname)) + { + $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'), + array('_', ''), $mname); + $methodwrap = wrap_xmlrpc_method($client, $mname, $opts); + if ($methodwrap) + { + if (!$buildit) + { + $source .= $methodwrap['docstring']; + } + $source .= $methodwrap['source']."\n"; + } + else + { + error_log('XML-RPC: will not create class method to wrap remote method '.$mname); + } + } + } + $source .= "}\n"; + if ($buildit) + { + $allOK = 0; + eval($source.'$allOK=1;'); + // alternative + //$xmlrpcfuncname = create_function('$m', $innercode); + if($allOK) + { + return $xmlrpcclassname; + } + else + { + error_log('XML-RPC: could not create class '.$xmlrpcclassname.' to wrap remote server '.$client->server); + return false; + } + } + else + { + return array('class' => $xmlrpcclassname, 'code' => $source, 'docstring' => ''); + } + } + } + } + + /** + * Given the necessary info, build php code that creates a new function to + * invoke a remote xmlrpc method. + * Take care that no full checking of input parameters is done to ensure that + * valid php code is emitted. + * Note: real spaghetti code follows... + * @access private + */ + function build_remote_method_wrapper_code($client, $methodname, $xmlrpcfuncname, + $msig, $mdesc='', $timeout=0, $protocol='', $client_copy_mode=0, $prefix='xmlrpc', + $decode_php_objects=false, $encode_php_objects=false, $decode_fault=false, + $fault_response='') + { + $code = "function $xmlrpcfuncname ("; + if ($client_copy_mode < 2) + { + // client copy mode 0 or 1 == partial / full client copy in emitted code + $innercode = build_client_wrapper_code($client, $client_copy_mode, $prefix); + $innercode .= "\$client->setDebug(\$debug);\n"; + $this_ = ''; + } + else + { + // client copy mode 2 == no client copy in emitted code + $innercode = ''; + $this_ = 'this->'; + } + $innercode .= "\$msg =& new {$prefix}msg('$methodname');\n"; + + if ($mdesc != '') + { + // take care that PHP comment is not terminated unwillingly by method description + $mdesc = "/**\n* ".str_replace('*/', '* /', $mdesc)."\n"; + } + else + { + $mdesc = "/**\nFunction $xmlrpcfuncname\n"; + } + + // param parsing + $plist = array(); + $pcount = count($msig); + for($i = 1; $i < $pcount; $i++) + { + $plist[] = "\$p$i"; + $ptype = $msig[$i]; + if($ptype == 'i4' || $ptype == 'int' || $ptype == 'boolean' || $ptype == 'double' || + $ptype == 'string' || $ptype == 'dateTime.iso8601' || $ptype == 'base64' || $ptype == 'null') + { + // only build directly xmlrpcvals when type is known and scalar + $innercode .= "\$p$i =& new {$prefix}val(\$p$i, '$ptype');\n"; + } + else + { + if ($encode_php_objects) + { + $innercode .= "\$p$i =& php_{$prefix}_encode(\$p$i, array('encode_php_objs'));\n"; + } + else + { + $innercode .= "\$p$i =& php_{$prefix}_encode(\$p$i);\n"; + } + } + $innercode .= "\$msg->addparam(\$p$i);\n"; + $mdesc .= '* @param '.xmlrpc_2_php_type($ptype)." \$p$i\n"; + } + if ($client_copy_mode < 2) + { + $plist[] = '$debug=0'; + $mdesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n"; + } + $plist = implode(', ', $plist); + $mdesc .= '* @return '.xmlrpc_2_php_type($msig[0])." (or an {$prefix}resp obj instance if call fails)\n*/\n"; + + $innercode .= "\$res =& \${$this_}client->send(\$msg, $timeout, '$protocol');\n"; + if ($decode_fault) + { + if (is_string($fault_response) && ((strpos($fault_response, '%faultCode%') !== false) || (strpos($fault_response, '%faultString%') !== false))) + { + $respcode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '".str_replace("'", "''", $fault_response)."')"; + } + else + { + $respcode = var_export($fault_response, true); + } + } + else + { + $respcode = '$res'; + } + if ($decode_php_objects) + { + $innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value(), array('decode_php_objs'));"; + } + else + { + $innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value());"; + } + + $code = $code . $plist. ") {\n" . $innercode . "\n}\n"; + + return array('source' => $code, 'docstring' => $mdesc); + } + + /** + * Given necessary info, generate php code that will rebuild a client object + * Take care that no full checking of input parameters is done to ensure that + * valid php code is emitted. + * @access private + */ + function build_client_wrapper_code($client, $verbatim_client_copy, $prefix='xmlrpc') + { + $code = "\$client =& new {$prefix}_client('".str_replace("'", "\'", $client->path). + "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n"; + + // copy all client fields to the client that will be generated runtime + // (this provides for future expansion or subclassing of client obj) + if ($verbatim_client_copy) + { + foreach($client as $fld => $val) + { + if($fld != 'debug' && $fld != 'return_type') + { + $val = var_export($val, true); + $code .= "\$client->$fld = $val;\n"; + } + } + } + // only make sure that client always returns the correct data type + $code .= "\$client->return_type = '{$prefix}vals';\n"; + //$code .= "\$client->setDebug(\$debug);\n"; + return $code; + } +?> \ No newline at end of file diff --git a/lib/xmlrpcs.inc b/lib/xmlrpcs.inc new file mode 100644 index 0000000..661a1b4 --- /dev/null +++ b/lib/xmlrpcs.inc @@ -0,0 +1,1172 @@ + +// $Id: xmlrpcs.inc,v 1.66 2006/09/17 21:25:06 ggiunta Exp $ + +// Copyright (c) 1999,2000,2002 Edd Dumbill. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// +// * Neither the name of the "XML-RPC for PHP" nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +// OF THE POSSIBILITY OF SUCH DAMAGE. + + // XML RPC Server class + // requires: xmlrpc.inc + + $GLOBALS['xmlrpcs_capabilities'] = array( + // xmlrpc spec: always supported + 'xmlrpc' => new xmlrpcval(array( + 'specUrl' => new xmlrpcval('http://www.xmlrpc.com/spec', 'string'), + 'specVersion' => new xmlrpcval(1, 'int') + ), 'struct'), + // if we support system.xxx functions, we always support multicall, too... + // Note that, as of 2006/09/17, the following URL does not respond anymore + 'system.multicall' => new xmlrpcval(array( + 'specUrl' => new xmlrpcval('http://www.xmlrpc.com/discuss/msgReader$1208', 'string'), + 'specVersion' => new xmlrpcval(1, 'int') + ), 'struct'), + // introspection: version 2! we support 'mixed', too + 'introspection' => new xmlrpcval(array( + 'specUrl' => new xmlrpcval('http://phpxmlrpc.sourceforge.net/doc-2/ch10.html', 'string'), + 'specVersion' => new xmlrpcval(2, 'int') + ), 'struct') + ); + + /* Functions that implement system.XXX methods of xmlrpc servers */ + $_xmlrpcs_getCapabilities_sig=array(array($GLOBALS['xmlrpcStruct'])); + $_xmlrpcs_getCapabilities_doc='This method lists all the capabilites that the XML-RPC server has: the (more or less standard) extensions to the xmlrpc spec that it adheres to'; + $_xmlrpcs_getCapabilities_sdoc=array(array('list of capabilities, described as structs with a version number and url for the spec')); + function _xmlrpcs_getCapabilities($server, $m=null) + { + $outAr = $GLOBALS['xmlrpcs_capabilities']; + // NIL extension + if ($GLOBALS['xmlrpc_null_extension']) { + $outAr['nil'] = new xmlrpcval(array( + 'specUrl' => new xmlrpcval('http://www.ontosys.com/xml-rpc/extensions.php', 'string'), + 'specVersion' => new xmlrpcval(1, 'int') + ), 'struct'); + } + return new xmlrpcresp(new xmlrpcval($outAr, 'struct')); + } + + // listMethods: signature was either a string, or nothing. + // The useless string variant has been removed + $_xmlrpcs_listMethods_sig=array(array($GLOBALS['xmlrpcArray'])); + $_xmlrpcs_listMethods_doc='This method lists all the methods that the XML-RPC server knows how to dispatch'; + $_xmlrpcs_listMethods_sdoc=array(array('list of method names')); + function _xmlrpcs_listMethods($server, $m=null) // if called in plain php values mode, second param is missing + { + + $outAr=array(); + foreach($server->dmap as $key => $val) + { + $outAr[]=&new xmlrpcval($key, 'string'); + } + if($server->allow_system_funcs) + { + foreach($GLOBALS['_xmlrpcs_dmap'] as $key => $val) + { + $outAr[]=&new xmlrpcval($key, 'string'); + } + } + return new xmlrpcresp(new xmlrpcval($outAr, 'array')); + } + + $_xmlrpcs_methodSignature_sig=array(array($GLOBALS['xmlrpcArray'], $GLOBALS['xmlrpcString'])); + $_xmlrpcs_methodSignature_doc='Returns an array of known signatures (an array of arrays) for the method name passed. If no signatures are known, returns a none-array (test for type != array to detect missing signature)'; + $_xmlrpcs_methodSignature_sdoc=array(array('list of known signatures, each sig being an array of xmlrpc type names', 'name of method to be described')); + function _xmlrpcs_methodSignature($server, $m) + { + // let accept as parameter both an xmlrpcval or string + if (is_object($m)) + { + $methName=$m->getParam(0); + $methName=$methName->scalarval(); + } + else + { + $methName=$m; + } + if(strpos($methName, "system.") === 0) + { + $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1; + } + else + { + $dmap=$server->dmap; $sysCall=0; + } + if(isset($dmap[$methName])) + { + if(isset($dmap[$methName]['signature'])) + { + $sigs=array(); + foreach($dmap[$methName]['signature'] as $inSig) + { + $cursig=array(); + foreach($inSig as $sig) + { + $cursig[]=&new xmlrpcval($sig, 'string'); + } + $sigs[]=&new xmlrpcval($cursig, 'array'); + } + $r=&new xmlrpcresp(new xmlrpcval($sigs, 'array')); + } + else + { + // NB: according to the official docs, we should be returning a + // "none-array" here, which means not-an-array + $r=&new xmlrpcresp(new xmlrpcval('undef', 'string')); + } + } + else + { + $r=&new xmlrpcresp(0,$GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']); + } + return $r; + } + + $_xmlrpcs_methodHelp_sig=array(array($GLOBALS['xmlrpcString'], $GLOBALS['xmlrpcString'])); + $_xmlrpcs_methodHelp_doc='Returns help text if defined for the method passed, otherwise returns an empty string'; + $_xmlrpcs_methodHelp_sdoc=array(array('method description', 'name of the method to be described')); + function _xmlrpcs_methodHelp($server, $m) + { + // let accept as parameter both an xmlrpcval or string + if (is_object($m)) + { + $methName=$m->getParam(0); + $methName=$methName->scalarval(); + } + else + { + $methName=$m; + } + if(strpos($methName, "system.") === 0) + { + $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1; + } + else + { + $dmap=$server->dmap; $sysCall=0; + } + if(isset($dmap[$methName])) + { + if(isset($dmap[$methName]['docstring'])) + { + $r=&new xmlrpcresp(new xmlrpcval($dmap[$methName]['docstring']), 'string'); + } + else + { + $r=&new xmlrpcresp(new xmlrpcval('', 'string')); + } + } + else + { + $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']); + } + return $r; + } + + $_xmlrpcs_multicall_sig = array(array($GLOBALS['xmlrpcArray'], $GLOBALS['xmlrpcArray'])); + $_xmlrpcs_multicall_doc = 'Boxcar multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details'; + $_xmlrpcs_multicall_sdoc = array(array('list of response structs, where each struct has the usual members', 'list of calls, with each call being represented as a struct, with members "methodname" and "params"')); + function _xmlrpcs_multicall_error($err) + { + if(is_string($err)) + { + $str = $GLOBALS['xmlrpcstr']["multicall_${err}"]; + $code = $GLOBALS['xmlrpcerr']["multicall_${err}"]; + } + else + { + $code = $err->faultCode(); + $str = $err->faultString(); + } + $struct = array(); + $struct['faultCode'] =& new xmlrpcval($code, 'int'); + $struct['faultString'] =& new xmlrpcval($str, 'string'); + return new xmlrpcval($struct, 'struct'); + } + + function _xmlrpcs_multicall_do_call($server, $call) + { + if($call->kindOf() != 'struct') + { + return _xmlrpcs_multicall_error('notstruct'); + } + $methName = @$call->structmem('methodName'); + if(!$methName) + { + return _xmlrpcs_multicall_error('nomethod'); + } + if($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string') + { + return _xmlrpcs_multicall_error('notstring'); + } + if($methName->scalarval() == 'system.multicall') + { + return _xmlrpcs_multicall_error('recursion'); + } + + $params = @$call->structmem('params'); + if(!$params) + { + return _xmlrpcs_multicall_error('noparams'); + } + if($params->kindOf() != 'array') + { + return _xmlrpcs_multicall_error('notarray'); + } + $numParams = $params->arraysize(); + + $msg =& new xmlrpcmsg($methName->scalarval()); + for($i = 0; $i < $numParams; $i++) + { + if(!$msg->addParam($params->arraymem($i))) + { + $i++; + return _xmlrpcs_multicall_error(new xmlrpcresp(0, + $GLOBALS['xmlrpcerr']['incorrect_params'], + $GLOBALS['xmlrpcstr']['incorrect_params'] . ": probable xml error in param " . $i)); + } + } + + $result = $server->execute($msg); + + if($result->faultCode() != 0) + { + return _xmlrpcs_multicall_error($result); // Method returned fault. + } + + return new xmlrpcval(array($result->value()), 'array'); + } + + function _xmlrpcs_multicall_do_call_phpvals($server, $call) + { + if(!is_array($call)) + { + return _xmlrpcs_multicall_error('notstruct'); + } + if(!array_key_exists('methodName', $call)) + { + return _xmlrpcs_multicall_error('nomethod'); + } + if (!is_string($call['methodName'])) + { + return _xmlrpcs_multicall_error('notstring'); + } + if($call['methodName'] == 'system.multicall') + { + return _xmlrpcs_multicall_error('recursion'); + } + if(!array_key_exists('params', $call)) + { + return _xmlrpcs_multicall_error('noparams'); + } + if(!is_array($call['params'])) + { + return _xmlrpcs_multicall_error('notarray'); + } + + // this is a real dirty and simplistic hack, since we might have received a + // base64 or datetime values, but they will be listed as strings here... + $numParams = count($call['params']); + $pt = array(); + foreach($call['params'] as $val) + $pt[] = php_2_xmlrpc_type(gettype($val)); + + $result = $server->execute($call['methodName'], $call['params'], $pt); + + if($result->faultCode() != 0) + { + return _xmlrpcs_multicall_error($result); // Method returned fault. + } + + return new xmlrpcval(array($result->value()), 'array'); + } + + function _xmlrpcs_multicall($server, $m) + { + $result = array(); + // let accept a plain list of php parameters, beside a single xmlrpc msg object + if (is_object($m)) + { + $calls = $m->getParam(0); + $numCalls = $calls->arraysize(); + for($i = 0; $i < $numCalls; $i++) + { + $call = $calls->arraymem($i); + $result[$i] = _xmlrpcs_multicall_do_call($server, $call); + } + } + else + { + $numCalls=count($m); + for($i = 0; $i < $numCalls; $i++) + { + $result[$i] = _xmlrpcs_multicall_do_call_phpvals($server, $m[$i]); + } + } + + return new xmlrpcresp(new xmlrpcval($result, 'array')); + } + + $GLOBALS['_xmlrpcs_dmap']=array( + 'system.listMethods' => array( + 'function' => '_xmlrpcs_listMethods', + 'signature' => $_xmlrpcs_listMethods_sig, + 'docstring' => $_xmlrpcs_listMethods_doc, + 'signature_docs' => $_xmlrpcs_listMethods_sdoc), + 'system.methodHelp' => array( + 'function' => '_xmlrpcs_methodHelp', + 'signature' => $_xmlrpcs_methodHelp_sig, + 'docstring' => $_xmlrpcs_methodHelp_doc, + 'signature_docs' => $_xmlrpcs_methodHelp_sdoc), + 'system.methodSignature' => array( + 'function' => '_xmlrpcs_methodSignature', + 'signature' => $_xmlrpcs_methodSignature_sig, + 'docstring' => $_xmlrpcs_methodSignature_doc, + 'signature_docs' => $_xmlrpcs_methodSignature_sdoc), + 'system.multicall' => array( + 'function' => '_xmlrpcs_multicall', + 'signature' => $_xmlrpcs_multicall_sig, + 'docstring' => $_xmlrpcs_multicall_doc, + 'signature_docs' => $_xmlrpcs_multicall_sdoc), + 'system.getCapabilities' => array( + 'function' => '_xmlrpcs_getCapabilities', + 'signature' => $_xmlrpcs_getCapabilities_sig, + 'docstring' => $_xmlrpcs_getCapabilities_doc, + 'signature_docs' => $_xmlrpcs_getCapabilities_sdoc) + ); + + $GLOBALS['_xmlrpcs_occurred_errors'] = ''; + $GLOBALS['_xmlrpcs_prev_ehandler'] = ''; + /** + * Error handler used to track errors that occur during server-side execution of PHP code. + * This allows to report back to the client whether an internal error has occurred or not + * using an xmlrpc response object, instead of letting the client deal with the html junk + * that a PHP execution error on the server generally entails. + * + * NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors. + * + */ + function _xmlrpcs_errorHandler($errcode, $errstring, $filename=null, $lineno=null, $context=null) + { + // obey the @ protocol + if (error_reporting() == 0) + return; + + //if($errcode != E_NOTICE && $errcode != E_WARNING && $errcode != E_USER_NOTICE && $errcode != E_USER_WARNING) + if($errcode != 2048) // do not use E_STRICT by name, since on PHP 4 it will not be defined + { + $GLOBALS['_xmlrpcs_occurred_errors'] = $GLOBALS['_xmlrpcs_occurred_errors'] . $errstring . "\n"; + } + // Try to avoid as much as possible disruption to the previous error handling + // mechanism in place + if($GLOBALS['_xmlrpcs_prev_ehandler'] == '') + { + // The previous error handler was the default: all we should do is log error + // to the default error log (if level high enough) + if(ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errcode)) + { + error_log($errstring); + } + } + else + { + // Pass control on to previous error handler, trying to avoid loops... + if($GLOBALS['_xmlrpcs_prev_ehandler'] != '_xmlrpcs_errorHandler') + { + // NB: this code will NOT work on php < 4.0.2: only 2 params were used for error handlers + if(is_array($GLOBALS['_xmlrpcs_prev_ehandler'])) + { + $GLOBALS['_xmlrpcs_prev_ehandler'][0]->$GLOBALS['_xmlrpcs_prev_ehandler'][1]($errcode, $errstring, $filename, $lineno, $context); + } + else + { + $GLOBALS['_xmlrpcs_prev_ehandler']($errcode, $errstring, $filename, $lineno, $context); + } + } + } + } + + $GLOBALS['_xmlrpc_debuginfo']=''; + + /** + * Add a string to the debug info that can be later seralized by the server + * as part of the response message. + * Note that for best compatbility, the debug string should be encoded using + * the $GLOBALS['xmlrpc_internalencoding'] character set. + * @param string $m + * @access public + */ + function xmlrpc_debugmsg($m) + { + $GLOBALS['_xmlrpc_debuginfo'] .= $m . "\n"; + } + + class xmlrpc_server + { + /// array defining php functions exposed as xmlrpc methods by this server + var $dmap=array(); + /** + * Defines how functions in dmap will be invokde: either using an xmlrpc msg object + * or plain php values. + * valid strings are 'xmlrpcvals', 'phpvals' or 'epivals' + */ + var $functions_parameters_type='xmlrpcvals'; + /// controls wether the server is going to echo debugging messages back to the client as comments in response body. valid values: 0,1,2,3 + var $debug = 1; + /** + * When set to true, it will enable HTTP compression of the response, in case + * the client has declared its support for compression in the request. + */ + var $compress_response = false; + /** + * List of http compression methods accepted by the server for requests. + * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib + */ + var $accepted_compression = array(); + /// shall we serve calls to system.* methods? + var $allow_system_funcs = true; + /// list of charset encodings natively accepted for requests + var $accepted_charset_encodings = array(); + /** + * charset encoding to be used for response. + * NB: if we can, we will convert the generated response from internal_encoding to the intended one. + * can be: a supported xml encoding (only UTF-8 and ISO-8859-1 at present, unless mbstring is enabled), + * null (leave unspecified in response, convert output stream to US_ASCII), + * 'default' (use xmlrpc library default as specified in xmlrpc.inc, convert output stream if needed), + * or 'auto' (use client-specified charset encoding or same as request if request headers do not specify it (unless request is US-ASCII: then use library default anyway). + * NB: pretty dangerous if you accept every charset and do not have mbstring enabled) + */ + var $response_charset_encoding = ''; + /// storage for internal debug info + var $debug_info = ''; + /// extra data passed at runtime to method handling functions. Used only by EPI layer + var $user_data = null; + + /** + * @param array $dispmap the dispatch map withd efinition of exposed services + * @param boolean $servicenow set to false to prevent the server from runnung upon construction + */ + function xmlrpc_server($dispMap=null, $serviceNow=true) + { + // if ZLIB is enabled, let the server by default accept compressed requests, + // and compress responses sent to clients that support them + if(function_exists('gzinflate')) + { + $this->accepted_compression = array('gzip', 'deflate'); + $this->compress_response = true; + } + + // by default the xml parser can support these 3 charset encodings + $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII'); + + // dispMap is a dispatch array of methods + // mapped to function names and signatures + // if a method + // doesn't appear in the map then an unknown + // method error is generated + /* milosch - changed to make passing dispMap optional. + * instead, you can use the class add_to_map() function + * to add functions manually (borrowed from SOAPX4) + */ + if($dispMap) + { + $this->dmap = $dispMap; + if($serviceNow) + { + $this->service(); + } + } + } + + /** + * Set debug level of server. + * @param integer $in debug lvl: determines info added to xmlrpc responses (as xml comments) + * 0 = no debug info, + * 1 = msgs set from user with debugmsg(), + * 2 = add complete xmlrpc request (headers and body), + * 3 = add also all processing warnings happened during method processing + * (NB: this involves setting a custom error handler, and might interfere + * with the standard processing of the php function exposed as method. In + * particular, triggering an USER_ERROR level error will not halt script + * execution anymore, but just end up logged in the xmlrpc response) + * Note that info added at elevel 2 and 3 will be base64 encoded + * @access public + */ + function setDebug($in) + { + $this->debug=$in; + } + + /** + * Return a string with the serialized representation of all debug info + * @param string $charset_encoding the target charset encoding for the serialization + * @return string an XML comment (or two) + */ + function serializeDebug($charset_encoding='') + { + // Tough encoding problem: which internal charset should we assume for debug info? + // It might contain a copy of raw data received from client, ie with unknown encoding, + // intermixed with php generated data and user generated data... + // so we split it: system debug is base 64 encoded, + // user debug info should be encoded by the end user using the INTERNAL_ENCODING + $out = ''; + if ($this->debug_info != '') + { + $out .= "\n"; + } + if($GLOBALS['_xmlrpc_debuginfo']!='') + { + + $out .= "\n"; + // NB: a better solution MIGHT be to use CDATA, but we need to insert it + // into return payload AFTER the beginning tag + //$out .= "', ']_]_>', $GLOBALS['_xmlrpc_debuginfo']) . "\n]]>\n"; + } + return $out; + } + + /** + * Execute the xmlrpc request, printing the response + * @param string $data the request body. If null, the http POST request will be examined + * @return xmlrpcresp the response object (usually not used by caller...) + * @access public + */ + function service($data=null, $return_payload=false) + { + if ($data === null) + { + $data = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : ''; + } + $raw_data = $data; + + // reset internal debug info + $this->debug_info = ''; + + // Echo back what we received, before parsing it + if($this->debug > 1) + { + $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++"); + } + + $r = $this->parseRequestHeaders($data, $req_charset, $resp_charset, $resp_encoding); + if (!$r) + { + $r=$this->parseRequest($data, $req_charset); + } + + // save full body of request into response, for more debugging usages + $r->raw_data = $raw_data; + + if($this->debug > 2 && $GLOBALS['_xmlrpcs_occurred_errors']) + { + $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" . + $GLOBALS['_xmlrpcs_occurred_errors'] . "+++END+++"); + } + + $payload=$this->xml_header($resp_charset); + if($this->debug > 0) + { + $payload = $payload . $this->serializeDebug($resp_charset); + } + + // G. Giunta 2006-01-27: do not create response serialization if it has + // already happened. Helps building json magic + if (empty($r->payload)) + { + $r->serialize($resp_charset); + } + $payload = $payload . $r->payload; + + if ($return_payload) + { + return $payload; + } + + // if we get a warning/error that has output some text before here, then we cannot + // add a new header. We cannot say we are sending xml, either... + if(!headers_sent()) + { + header('Content-Type: '.$r->content_type); + // we do not know if client actually told us an accepted charset, but if he did + // we have to tell him what we did + header("Vary: Accept-Charset"); + + // http compression of output: only + // if we can do it, and we want to do it, and client asked us to, + // and php ini settings do not force it already + $php_no_self_compress = ini_get('zlib.output_compression') == '' && (ini_get('output_handler') != 'ob_gzhandler'); + if($this->compress_response && function_exists('gzencode') && $resp_encoding != '' + && $php_no_self_compress) + { + if(strpos($resp_encoding, 'gzip') !== false) + { + $payload = gzencode($payload); + header("Content-Encoding: gzip"); + header("Vary: Accept-Encoding"); + } + elseif (strpos($resp_encoding, 'deflate') !== false) + { + $payload = gzcompress($payload); + header("Content-Encoding: deflate"); + header("Vary: Accept-Encoding"); + } + } + + // do not ouput content-length header if php is compressing output for us: + // it will mess up measurements + if($php_no_self_compress) + { + header('Content-Length: ' . (int)strlen($payload)); + } + } + else + { + error_log('XML-RPC: xmlrpc_server::service: http headers already sent before response is fully generated. Check for php warning or error messages'); + } + + print $payload; + + // return request, in case subclasses want it + return $r; + } + + /** + * Add a method to the dispatch map + * @param string $methodname the name with which the method will be made available + * @param string $function the php function that will get invoked + * @param array $sig the array of valid method signatures + * @param string $doc method documentation + * @access public + */ + function add_to_map($methodname,$function,$sig=null,$doc='') + { + $this->dmap[$methodname] = array( + 'function' => $function, + 'docstring' => $doc + ); + if ($sig) + { + $this->dmap[$methodname]['signature'] = $sig; + } + } + + /** + * Verify type and number of parameters received against a list of known signatures + * @param array $in array of either xmlrpcval objects or xmlrpc type definitions + * @param array $sig array of known signatures to match against + * @access private + */ + function verifySignature($in, $sig) + { + // check each possible signature in turn + if (is_object($in)) + { + $numParams = $in->getNumParams(); + } + else + { + $numParams = count($in); + } + foreach($sig as $cursig) + { + if(count($cursig)==$numParams+1) + { + $itsOK=1; + for($n=0; $n<$numParams; $n++) + { + if (is_object($in)) + { + $p=$in->getParam($n); + if($p->kindOf() == 'scalar') + { + $pt=$p->scalartyp(); + } + else + { + $pt=$p->kindOf(); + } + } + else + { + $pt= $in[$n] == 'i4' ? 'int' : $in[$n]; // dispatch maps never use i4... + } + + // param index is $n+1, as first member of sig is return type + if($pt != $cursig[$n+1] && $cursig[$n+1] != $GLOBALS['xmlrpcValue']) + { + $itsOK=0; + $pno=$n+1; + $wanted=$cursig[$n+1]; + $got=$pt; + break; + } + } + if($itsOK) + { + return array(1,''); + } + } + } + if(isset($wanted)) + { + return array(0, "Wanted ${wanted}, got ${got} at param ${pno}"); + } + else + { + return array(0, "No method signature matches number of parameters"); + } + } + + /** + * Parse http headers received along with xmlrpc request. If needed, inflate request + * @return null on success or an xmlrpcresp + * @access private + */ + function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, &$resp_compression) + { + // Play nice to PHP 4.0.x: superglobals were not yet invented... + if(!isset($_SERVER)) + { + $_SERVER = $GLOBALS['HTTP_SERVER_VARS']; + } + + if($this->debug > 1) + { + if(function_exists('getallheaders')) + { + $this->debugmsg(''); // empty line + foreach(getallheaders() as $name => $val) + { + $this->debugmsg("HEADER: $name: $val"); + } + } + + } + + if(isset($_SERVER['HTTP_CONTENT_ENCODING'])) + { + $content_encoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']); + } + else + { + $content_encoding = ''; + } + + // check if request body has been compressed and decompress it + if($content_encoding != '' && strlen($data)) + { + if($content_encoding == 'deflate' || $content_encoding == 'gzip') + { + // if decoding works, use it. else assume data wasn't gzencoded + if(function_exists('gzinflate') && in_array($content_encoding, $this->accepted_compression)) + { + if($content_encoding == 'deflate' && $degzdata = @gzuncompress($data)) + { + $data = $degzdata; + if($this->debug > 1) + { + $this->debugmsg("\n+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++"); + } + } + elseif($content_encoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) + { + $data = $degzdata; + if($this->debug > 1) + $this->debugmsg("+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++"); + } + else + { + $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_decompress_fail'], $GLOBALS['xmlrpcstr']['server_decompress_fail']); + return $r; + } + } + else + { + //error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); + $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_cannot_decompress'], $GLOBALS['xmlrpcstr']['server_cannot_decompress']); + return $r; + } + } + } + + // check if client specified accepted charsets, and if we know how to fulfill + // the request + if ($this->response_charset_encoding == 'auto') + { + $resp_encoding = ''; + if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) + { + // here we should check if we can match the client-requested encoding + // with the encodings we know we can generate. + /// @todo we should parse q=0.x preferences instead of getting first charset specified... + $client_accepted_charsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET'])); + // Give preference to internal encoding + $known_charsets = array($this->internal_encoding, 'UTF-8', 'ISO-8859-1', 'US-ASCII'); + foreach ($known_charsets as $charset) + { + foreach ($client_accepted_charsets as $accepted) + if (strpos($accepted, $charset) === 0) + { + $resp_encoding = $charset; + break; + } + if ($resp_encoding) + break; + } + } + } + else + { + $resp_encoding = $this->response_charset_encoding; + } + + if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) + { + $resp_compression = $_SERVER['HTTP_ACCEPT_ENCODING']; + } + else + { + $resp_compression = ''; + } + + // 'guestimate' request encoding + /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check??? + $req_encoding = guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '', + $data); + + return null; + } + + /** + * Parse an xml chunk containing an xmlrpc request and execute the corresponding + * php function registered with the server + * @param string $data the xml request + * @param string $req_encoding (optional) the charset encoding of the xml request + * @return xmlrpcresp + * @access private + */ + function parseRequest($data, $req_encoding='') + { + // 2005/05/07 commented and moved into caller function code + //if($data=='') + //{ + // $data=$GLOBALS['HTTP_RAW_POST_DATA']; + //} + + // G. Giunta 2005/02/13: we do NOT expect to receive html entities + // so we do not try to convert them into xml character entities + //$data = xmlrpc_html_entity_xlate($data); + + $GLOBALS['_xh']=array(); + $GLOBALS['_xh']['ac']=''; + $GLOBALS['_xh']['stack']=array(); + $GLOBALS['_xh']['valuestack'] = array(); + $GLOBALS['_xh']['params']=array(); + $GLOBALS['_xh']['pt']=array(); + $GLOBALS['_xh']['isf']=0; + $GLOBALS['_xh']['isf_reason']=''; + $GLOBALS['_xh']['method']=false; // so we can check later if we got a methodname or not + $GLOBALS['_xh']['rt']=''; + + // decompose incoming XML into request structure + if ($req_encoding != '') + { + if (!in_array($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + // the following code might be better for mb_string enabled installs, but + // makes the lib about 200% slower... + //if (!is_valid_charset($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + { + error_log('XML-RPC: xmlrpc_server::parseRequest: invalid charset encoding of received request: '.$req_encoding); + $req_encoding = $GLOBALS['xmlrpc_defencoding']; + } + /// @BUG this will fail on PHP 5 if charset is not specified in the xml prologue, + // the encoding is not UTF8 and there are non-ascii chars in the text... + $parser = xml_parser_create($req_encoding); + } + else + { + $parser = xml_parser_create(); + } + + xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true); + // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell + // the xml parser to give us back data in the expected charset + xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']); + + if ($this->functions_parameters_type != 'xmlrpcvals') + xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast'); + else + xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee'); + xml_set_character_data_handler($parser, 'xmlrpc_cd'); + xml_set_default_handler($parser, 'xmlrpc_dh'); + if(!xml_parse($parser, $data, 1)) + { + // return XML error as a faultCode + $r=&new xmlrpcresp(0, + $GLOBALS['xmlrpcerrxml']+xml_get_error_code($parser), + sprintf('XML error: %s at line %d, column %d', + xml_error_string(xml_get_error_code($parser)), + xml_get_current_line_number($parser), xml_get_current_column_number($parser))); + xml_parser_free($parser); + } + elseif ($GLOBALS['_xh']['isf']) + { + xml_parser_free($parser); + $r=&new xmlrpcresp(0, + $GLOBALS['xmlrpcerr']['invalid_request'], + $GLOBALS['xmlrpcstr']['invalid_request'] . ' ' . $GLOBALS['_xh']['isf_reason']); + } + else + { + xml_parser_free($parser); + if ($this->functions_parameters_type != 'xmlrpcvals') + { + if($this->debug > 1) + { + $this->debugmsg("\n+++PARSED+++\n".var_export($GLOBALS['_xh']['params'], true)."\n+++END+++"); + } + $r = $this->execute($GLOBALS['_xh']['method'], $GLOBALS['_xh']['params'], $GLOBALS['_xh']['pt']); + } + else + { + // build an xmlrpcmsg object with data parsed from xml + $m=&new xmlrpcmsg($GLOBALS['_xh']['method']); + // now add parameters in + for($i=0; $iaddParam($GLOBALS['_xh']['params'][$i]); + } + + if($this->debug > 1) + { + $this->debugmsg("\n+++PARSED+++\n".var_export($m, true)."\n+++END+++"); + } + + $r = $this->execute($m); + } + } + return $r; + } + + /** + * Execute a method invoked by the client, checking parameters used + * @param mixed $m either an xmlrpcmsg obj or a method name + * @param array $params array with method parameters as php types (if m is method name only) + * @param array $paramtypes array with xmlrpc types of method parameters (if m is method name only) + * @return xmlrpcresp + * @access private + */ + function execute($m, $params=null, $paramtypes=null) + { + if (is_object($m)) + { + $methName = $m->method(); + } + else + { + $methName = $m; + } + $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0); + $dmap = $sysCall ? $GLOBALS['_xmlrpcs_dmap'] : $this->dmap; + + if(!isset($dmap[$methName]['function'])) + { + // No such method + return new xmlrpcresp(0, + $GLOBALS['xmlrpcerr']['unknown_method'], + $GLOBALS['xmlrpcstr']['unknown_method']); + } + + // Check signature + if(isset($dmap[$methName]['signature'])) + { + $sig = $dmap[$methName]['signature']; + if (is_object($m)) + { + list($ok, $errstr) = $this->verifySignature($m, $sig); + } + else + { + list($ok, $errstr) = $this->verifySignature($paramtypes, $sig); + } + if(!$ok) + { + // Didn't match. + return new xmlrpcresp( + 0, + $GLOBALS['xmlrpcerr']['incorrect_params'], + $GLOBALS['xmlrpcstr']['incorrect_params'] . ": ${errstr}" + ); + } + } + + $func = $dmap[$methName]['function']; + // let the 'class::function' syntax be accepted in dispatch maps + if(is_string($func) && strpos($func, '::')) + { + $func = explode('::', $func); + } + // verify that function to be invoked is in fact callable + if(!is_callable($func)) + { + error_log("XML-RPC: xmlrpc_server::execute: function $func registered as method handler is not callable"); + return new xmlrpcresp( + 0, + $GLOBALS['xmlrpcerr']['server_error'], + $GLOBALS['xmlrpcstr']['server_error'] . ": no function matches method" + ); + } + + // If debug level is 3, we should catch all errors generated during + // processing of user function, and log them as part of response + if($this->debug > 2) + { + $GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler('_xmlrpcs_errorHandler'); + } + if (is_object($m)) + { + if($sysCall) + { + $r = call_user_func($func, $this, $m); + } + else + { + $r = call_user_func($func, $m); + } + if (!is_a($r, 'xmlrpcresp')) + { + error_log("XML-RPC: xmlrpc_server::execute: function $func registered as method handler does not return an xmlrpcresp object"); + if (is_a($r, 'xmlrpcval')) + { + $r =& new xmlrpcresp($r); + } + else + { + $r =& new xmlrpcresp( + 0, + $GLOBALS['xmlrpcerr']['server_error'], + $GLOBALS['xmlrpcstr']['server_error'] . ": function does not return xmlrpcresp object" + ); + } + } + } + else + { + // call a 'plain php' function + if($sysCall) + { + array_unshift($params, $this); + $r = call_user_func_array($func, $params); + } + else + { + // 3rd API convention for method-handling functions: EPI-style + if ($this->functions_parameters_type == 'epivals') + { + $r = call_user_func_array($func, array($methName, $params, $this->user_data)); + // mimic EPI behaviour: if we get an array that looks like an error, make it + // an eror response + if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r)) + { + $r =& new xmlrpcresp(0, (integer)$r['faultCode'], (string)$r['faultString']); + } + else + { + // functions using EPI api should NOT return resp objects, + // so make sure we encode the return type correctly + $r =& new xmlrpcresp(php_xmlrpc_encode($r, array('extension_api'))); + } + } + else + { + $r = call_user_func_array($func, $params); + } + } + // the return type can be either an xmlrpcresp object or a plain php value... + if (!is_a($r, 'xmlrpcresp')) + { + // what should we assume here about automatic encoding of datetimes + // and php classes instances??? + $r =& new xmlrpcresp(php_xmlrpc_encode($r, array('auto_dates'))); + } + } + if($this->debug > 2) + { + // note: restore the error handler we found before calling the + // user func, even if it has been changed inside the func itself + if($GLOBALS['_xmlrpcs_prev_ehandler']) + { + set_error_handler($GLOBALS['_xmlrpcs_prev_ehandler']); + } + else + { + restore_error_handler(); + } + } + return $r; + } + + /** + * add a string to the 'internal debug message' (separate from 'user debug message') + * @param string $strings + * @access private + */ + function debugmsg($string) + { + $this->debug_info .= $string."\n"; + } + + /** + * @access private + */ + function xml_header($charset_encoding='') + { + if ($charset_encoding != '') + { + return "\n"; + } + else + { + return "\n"; + } + } + + /** + * A debugging routine: just echoes back the input packet as a string value + * DEPRECATED! + */ + function echoInput() + { + $r=&new xmlrpcresp(new xmlrpcval( "'Aha said I: '" . $GLOBALS['HTTP_RAW_POST_DATA'], 'string')); + print $r->serialize(); + } + } +?> \ No newline at end of file diff --git a/link.php b/link.php new file mode 100644 index 0000000..5b95e2c --- /dev/null +++ b/link.php @@ -0,0 +1,115 @@ +get_record('course', array('id'=>$id))) { + print_error('Course ID is incorrect'); + } + require_login($course); + + $PAGE->set_url('/mod/programming/link.php', array('id' => $id)); + + //权限控制 + // 只允许管理员,该课程 教师 才能有权限 操作 + check_is_teacher($course); + + $strprogrammings = '引用编程插件管理'; + + $PAGE->set_title($strprogrammings); + $PAGE->set_heading($strprogrammings); + $PAGE->set_pagelayout('incourse'); + $PAGE->set_context(context_course::instance($id)); + $PAGE->navbar->add($strprogrammings); + + $PAGE->requires->css('/mod/programming/styles.css'); + $PAGE->requires->js('/mod/programming/js/jquery-1.3.1.js'); + $PAGE->requires->js('/mod/programming/js/link.js'); + + echo $OUTPUT->header(); + + +?> + + + + + + + + + + + + + + +
    + 课程列表: + +
    +

    章节

    +



    +
    +

    引用的编程练习

    + +
    + ..下 +

    +
    +    +

    +
    + + +
    +
    + +
    +

    所有编程练习

    + +
    + ..下 + + +
    + +
    + +    + +
    +
    + **    按照课程搜索会显示该课程下所有编程练习。
    + **    关键字搜索会显示所有编程练习中符合条件的编程练习。
    + **    添加编程插件引用后,需更新课程缓存。
    +
    + +footer(); + ?> diff --git a/link_lib.php b/link_lib.php new file mode 100644 index 0000000..8a1987a --- /dev/null +++ b/link_lib.php @@ -0,0 +1,523 @@ +get_records_sql($sql,array($section)); + + $remove_sequence = ''; + + foreach($rs as $k=>$v){ + $obj = new object(); + $obj = $v; + $remove_sequence .= $obj->id.','; + } + + $remove_sequence = rtrim($remove_sequence, ','); + + // 2.删除 mdl_course_modules 上的记录 + $ids_arr = explode(',', $ids); + foreach($ids_arr as $k=>$v){ + $DB->delete_records("course_modules",array("course"=>$course,'instance'=>$v)); + } + + $rs = $DB->get_field("course_sections",'sequence',array('id'=>$section)); + $section_src = ''; + $section_new = ''; + $section_src = $rs; + + $arr1 = explode(',', $remove_sequence); //mdl_course_section + $arr2 = explode(',', $section_src); + $arr3 = array_diff($arr2, $arr1); + $section_new = implode(',', $arr3); + + $DB->update_record("course_sections",array("id"=>$section,'sequence'=>$section_new)); + + } else if (isset($_REQUEST['do']) && $_REQUEST['do'] == "add") { +// do=add§ion=278&pids=7,&course=33 + // 添加编程实例引用 + //编程实例id + $ids = required_param('pids', PARAM_RAW); + $section = required_param('section', PARAM_INT); + $ids = rtrim($ids, ','); + $idArr = explode(',', $ids); + //课程id + $course = required_param('course', PARAM_INT); + + //查找programming module 的 插件编号 + $module = 0; + + $module = $DB->get_field("modules",'id',array('name'=>'programming')); + + if(empty($module)){ + echo ''; + exit(); + } + foreach ($idArr as $key => $val) { + + //添加的时候·先检查该section中是否有此 programming instance + + $instance = $DB->get_field("course_modules",'instance',array('instance'=>$val,'section'=>$section)); + + if( $instance ){ + continue 1; //如果 mdl_course_modules 该 section中,已经存在 该 instance 则跳出循环。进行下一次循环。 + } + + $now = time();//update time + + $param = array( + 'course' => $course , + 'module' =>$module, + 'instance'=>$val, + 'section'=>$section, + 'idnumber'=> '', + 'added'=> $now, + 'score'=> 0, + 'indent'=> 0, + 'visible'=> 1, + 'visibleold'=> 1, + 'groupmode'=> 0, + 'groupingid'=> 0, + 'groupmembersonly'=> 0, + 'completion'=> 0, + 'completiongradeitemnumber'=> NULL, + 'completionview'=> 0, + 'completionexpected'=> 0, + 'availablefrom'=> 0, + 'availableuntil'=> 0, + 'showavailability' => 0, + 'showdescription' => 0 + ); + $cmid = $DB->insert_record('course_modules',$param); + //修改course_sections 上的sequence + //1.查询现有的sequence + $sequence = ''; + $sequence_new = ''; + + $sequence = $DB->get_field('course_sections','sequence',array('course'=>$course,'id'=>$section)); + + if (!empty($sequence)) { + $sequence_new = $sequence . ',' . $cmid; + } else { + $sequence_new = $cmid; + } + + $DB->update_record('course_sections',array('id'=>$section,'sequence'=>$sequence_new)); + } + + } else if (isset($_REQUEST['do']) && $_REQUEST['do'] == "get_link_p") { + //根据课程章节,显示 章节上已经引用的 编程练习 + + //章节id + $section = $_REQUEST['section']; + //课程id + $course = required_param('course', PARAM_INT); + + if (!empty($section)) { + + //选中了章节 + $sequences = $DB->get_field('course_sections','sequence',array('id'=>$section)); + + if (!empty($sequences)) { + + //此处有一些小bug + //当sequences 上的实例 非programming 会显示出没有记录--已解决 + + $total_records = $DB->count_records_sql("SELECT count(id) from {programming} where id in +( select instance from {course_modules} cm,{modules} m where m.id=cm.module and m.`name`='programming' and cm.id in ($sequences))"); + // $total_records = count($total_records); + //总页数 + $total_page = ceil($total_records / $pageSize); + + if ($page > $total_page) { + if($total_page>=1){ + echo ''; + } + exit(); + } + + $sql = " + SELECT id,name from {programming} where id in +( select instance from {course_modules} cm,{modules} m where m.id=cm.module and m.`name`='programming' and cm.id in ($sequences))"; + // echo $sql; + $rs = array(); + $rs = $DB->get_records_sql($sql,null,($page - 1) * $pageSize,$pageSize); + foreach ($rs as $k=>$v){ + $obj = new object(); + $obj = $v; + echo ""; + } + } + } else { + //选中章节 + link_get_detail($course); + } + } else if (isset($_REQUEST['do']) && $_REQUEST['do'] == "get_link_r") { +// do=get_link_r§ion=0&page=1&course="+$courseid + //根据课程章节,显示 章节上未引用的 编程练习 + //章节id + $section = $_REQUEST['section']; + //课程id + $course = required_param('course', PARAM_INT); + $scourse = optional_param('scourse',0,PARAM_INT); + if (!empty($section)) { + + $sequences = ''; + $sequences = $DB->get_field('course_sections','sequence',array('id'=>$section)); + if (!empty($sequences)) { + //有一种可能性,section里面有sequence值,但sequence上的引用,不属于编程插件的。 + if($scourse>0){ + //按照课程搜索 + // $wheres = ' and cm.instance='.$scourse; + $pagesql = "SELECT count(id) from {programming} where id in +( select cm.instance from {course_modules} cm,{modules} m where m.id=cm.module and m.`name`='programming' and cm.course=$scourse ) "; + $sql = "SELECT distinct(id),name from {programming} where id in +( select cm.instance from {course_modules} cm,{modules} m where m.id=cm.module and m.`name`='programming' and cm.course=$scourse ) "; + + }else{ + $pagesql = "SELECT count(id) from {programming} where id not in +( select instance from {course_modules} cm,{modules} m where m.id=cm.module and m.`name`='programming' and cm.id in ($sequences)) "; + $sql = "SELECT id,name from {programming} where id not in +( select instance from {course_modules} cm,{modules} m where m.id=cm.module and m.`name`='programming' and cm.id in ($sequences)) "; + } + + //1.先取出 属于 编程插件的引用实例 + //计算总行数 + + $total_records = $DB->count_records_sql($pagesql); + //总页数 + $total_page = ceil($total_records / $pageSize); + + if ($page > $total_page && $scourse <=0 ) { + echo ''; + exit(); + } + + + $rs = array(); + $rs = $DB->get_records_sql($sql,null,($page - 1) * $pageSize,$pageSize); + + foreach($rs as $k=>$v){ + $obj = new object(); + $obj = $v; + echo ""; + } + } else { + //编程引用为空,显示全部的编程引用 + if( $scourse > 0 ){ + //按照课程搜索 + $pagesql = "select count(id) from {programming} where id in + ( select cm.instance from {course_modules} cm,{modules} m where m.id=cm.module and m.`name`='programming' and cm.course=$scourse ) "; + } else { + $pagesql = "select count(id) from {programming}"; + } + //计算总行数 + $total_records = $DB->count_records_sql($pagesql); + //总页数 + $total_page = ceil($total_records / $pageSize); + + if ($page > $total_page && $scourse<=0) { + echo ''; + exit(); + } + + $rs = array(); + if( $scourse > 0){ + //按照课程搜索 + $sql = "SELECT distinct(id),name from {programming} where id in +( select cm.instance from {course_modules} cm,{modules} m where m.id=cm.module and m.`name`='programming' and cm.course=$scourse ) "; + $rs = $DB->get_records_sql($sql,null,($page - 1) * $pageSize,$pageSize); + } else { + $rs = $DB->get_records('programming',null,'','id,name',($page - 1) * $pageSize,$pageSize); + } + foreach($rs as $k=>$v){ + $obj = new object(); + $obj = $v; + echo ""; + } + } + + } else { + //未选中章节 + + $page = $_REQUEST['page'] <= 0 ? 1 : $_REQUEST['page']; + + link_get_not_in_detail($course, $page,$scourse); + } + } else if (isset($_REQUEST['do']) && $_REQUEST['do'] == "rebuild") { + //清除课程的缓存 + + //课程id + $course = required_param('course', PARAM_INT); + + rebuild_course_cache($course); + } + // +} else if (isset($_REQUEST['do']) && $_REQUEST['do'] == "search") { + //关键字搜索 + $search = $_REQUEST['key']; + + if (!empty($search)) { + + $pagesql = "select count(id) from {programming} where name like '%$search%' "; + //计算总行数 + $total_records = $DB->count_records_sql($pagesql); + //总页数 + $total_page = ceil($total_records / $pageSize); + + if ($total_records <=0) { + echo ''; + exit(); + } + if ($page > $total_page) { + echo ''; + exit(); + } + + //选中了章节 + //$sql = "select id,name from {programming} where name like '%$search%' limit " . ($page - 1) * $pageSize . ",$pageSize "; + $rs = array(); + $rs = $DB->get_records_sql("select id,name from {programming} where name like '%$search%' ",null,($page - 1) * $pageSize,$pageSize); + foreach($rs as $k=>$v){ + $obj = new object(); + $obj = $v; + echo ""; + } + + } else { + + } +} + +//判断权限 +function check_is_teacher($courseorid){ + global $DB,$USER,$SITE; + if (!empty($courseorid)) { + if (is_object($courseorid)) { + $course = $courseorid; + } else if ($courseorid == SITEID) { + $course = clone($SITE); + } else { + $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST); + } + } + $access = false; + + $access = link_is_admin(); + + //判断是否为该课程教师 + $sql = "select u.id,c.fullname,u.lastname,u.firstname FROM + {user} u, + {course} c, + {role_assignments} ra, + {context} mc + WHERE + u.id=ra.userid and ra.roleid in (1,2,3) and c.id=mc.instanceid and ra.contextid=mc.id and c.id=? "; + $rs = array(); + $rs = $DB->get_records_sql($sql,array($course->id)); + foreach($rs as $k=>$v){ + $obj = new object(); + $obj = $v; + if($obj->id==$USER->id){ + $access = true; + } + } + + if(!$access){ + //权限不足,需要登录 + throw new require_login_exception('Invalid course login-as access'); + redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id); + } + + // return $access; +} +function link_is_admin(){ + global $DB,$USER,$SITE,$CFG; + $access = false; + //判断是否为网站管理员 + $rawsql = " +SELECT id,firstname,lastname,username,email FROM {user} + WHERE id <> '1' AND deleted = 0 AND confirmed = 1 AND id IN ($CFG->siteadmins) ORDER BY lastname, firstname, id"; + $rs = array(); + $rs = $DB->get_records_sql($rawsql); + foreach($rs as $k=>$v){ + $obj = new object(); + $obj = $v; + if($obj->id==$USER->id){ + $access = true; + } + } + return $access; +} + +//数据库遍历 + //遍历课程列表 + + function link_course($id) { + + global $CFG,$DB,$USER; + //需要根据用户的权限,显示不同的课程 + //教师只有编辑自己的课程权限 + //管理员可以编辑全部的课程权限 + $admins = $CFG->siteadmins; + $siteadmins = explode(',', $admins); + array_unshift($siteadmins, "tr"); + $flag = false; + + if(array_search($USER->id, $siteadmins)){ + $flag = true; //管理员权限 + } + + if(!$flag){ + $sql= "select c.id,c.shortname FROM + {user} u, + {course} c, + {role_assignments} ra, + {context} mc + WHERE + c.id != 1 and u.id=ra.userid and ra.roleid in (1,2,3) and c.id=mc.instanceid and ra.contextid=mc.id and u.id=$USER->id"; + }else{ + $sql = "select id,shortname from {course} where id != 1 order by id"; + } + + $rs = array(); + $rs = $DB->get_records_sql($sql); + foreach($rs as $k=>$v){ + $obj = new object(); + $obj = $v; + if ($id == $obj->id) { + echo ""; + } else { + echo ""; + } + } + } + + /** + * 按照课程搜索 + */ + function search_link_course($id) { + + global $DB; + + $sql = "select id,shortname from {course} where id != 1 order by id"; + + $rs = array(); + $rs = $DB->get_records_sql($sql); + foreach($rs as $k=>$v){ + $obj = new object(); + $obj = $v; + echo ""; + } + } + + //打印课程列表引用的编程插件 + // $id -- course id + function link_get_detail($id) { + + global $DB,$pageSize,$page; + + $total_records = $DB->count_records_sql("select count(p.id) from {programming} p,{course_modules} cm,{modules} m + where cm.course = $id and cm.instance=p.id and m.id=cm.module and m.`name`= 'programming' "); + //总页数 + $total_page = ceil($total_records / $pageSize); + if ($page > $total_page && $total_records > $pageSize) { + echo ''; + exit(); + } + //没有记录 + if($total_records <=0){ + return false; + } + + $rs = array(); + $sql = "select p.id,p.name from {programming} p,{course_modules} cm,{modules} m + where cm.course = $id and cm.instance=p.id and m.id=cm.module and m.`name`= 'programming' order by p.id asc"; + $rs = $DB->get_records_sql($sql,null,($page - 1) * $pageSize,$pageSize); + foreach($rs as $k=>$v){ + $obj = new object(); + $obj = $v; + echo ""; + } + + } + + //打印课程列表,没有引用到的编程插件 + // $id -- course id + function link_get_not_in_detail($id, $page = 1,$scourse=0) { + + global $pageSize,$DB; + if($scourse>0){ + $totalsql = "select count(p.id) from {programming} p where p.id in + (select cm.instance from {programming} p,{course_modules} cm,{modules} m + where cm.course = $scourse and cm.instance=p.id and m.id=cm.module and m.`name`= 'programming')"; + } else { + $totalsql = "select count(p.id) from {programming} p where p.id not in + (select cm.instance from {programming} p,{course_modules} cm,{modules} m + where cm.course = $id and cm.instance=p.id and m.id=cm.module and m.`name`= 'programming')"; + } + $total_records = $DB->count_records_sql($totalsql); + //总页数 + $total_page = ceil($total_records / $pageSize); + if ($page > $total_page&&$scourse<=0) { + echo ''; + exit(); + } + if($scourse>0){ + $sql = "select p.id,p.name from {programming} p where p.id in + (select cm.instance from {programming} p,{course_modules} cm,{modules} m + where cm.course = $scourse and cm.instance=p.id and m.id=cm.module and m.`name`= 'programming') "; + } else { + $sql = "select p.id,p.name from {programming} p where p.id not in + (select cm.instance from {programming} p,{course_modules} cm,{modules} m + where cm.course = $id and cm.instance=p.id and m.id=cm.module and m.`name`= 'programming') "; + } + $rs = array(); + $rs = $DB->get_records_sql($sql,null,($page - 1) * $pageSize,$pageSize); + foreach($rs as $k=>$v){ + $obj = new object(); + $obj = $v; + echo ""; + } + + } + + //打印课程里面的章节列表 + // $id -- course id + function link_get_course_section($id) { + global $DB; + $sql = "select id,course,section,name from {course_sections} s where s.course=$id and section != 0 "; + $rs = array(); + $rs = $DB->get_records_sql($sql); + foreach($rs as $k=>$v){ + $obj = new object(); + $obj = $v; + if (!empty($obj->name)) { + echo ""; + } else { + echo ""; + } + } + } + +?> \ No newline at end of file diff --git a/mod_form.php b/mod_form.php new file mode 100644 index 0000000..4e0c946 --- /dev/null +++ b/mod_form.php @@ -0,0 +1,150 @@ +dirroot.'/course/moodleform_mod.php'); + +class mod_programming_mod_form extends moodleform_mod { + + function definition() { + + global $CFG, $COURSE; + $mform =& $this->_form; + +//------------------------------------------------------------------------------- + $mform->addElement('header', 'general', get_string('general', 'form')); + + $mform->addElement('text', 'globalid', get_string('globalid', 'programming')); + $mform->setType('globalid', PARAM_TEXT); + + $mform->addElement('text', 'name', get_string('name'), array('size'=>'30')); + if (!empty($CFG->formatstringstriptags)) { + $mform->setType('name', PARAM_TEXT); + } else { + $mform->setType('name', PARAM_CLEAN); + } + $mform->addRule('name', null, 'required', null, 'client'); + $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'client'); + $this->standard_intro_elements(get_string('programmingintro', 'programming')); + + $mform->addElement('header', '', get_string('grade', 'mod_programming')); + + $options = array(); + $options[0] = get_string('nograde', 'programming'); + for ($i = 5; $i <= 100; $i += 5) { + $options[$i] = $i; + } + $mform->addElement('select', 'grade', get_string('grade', 'mod_programming'), $options); + + $options = array(); + for ($i = 10; $i > 0; $i -= 1) { + $options[$i] = $i / 10.0; + } + $mform->addElement('select', 'discount', get_string('discount', 'programming'), $options); + + $mform->addElement('date_time_selector', 'timeopen', get_string('timeopen', 'programming')); + $mform->addElement('date_time_selector', 'timediscount', get_string('timediscount', 'programming')); + $mform->addElement('date_time_selector', 'timeclose', get_string('timeclose', 'programming')); + + $mform->addElement('selectyesno', 'allowlate', get_string('allowlate', 'programming')); + +//------------------------------------------------------------------------------- + $mform->addElement('header', '', get_string('program', 'programming')); + + $langs = programming_get_language_options(); + $select = $mform->addElement('select', 'langlimit', get_string('langlimit', 'programming'), $langs); + $select->setMultiple(true); + $cats = programming_get_category_options(); + $select1 = $mform->addElement('select', 'category', get_string('category', 'programming'), $cats); + $select1->setMultiple(true); + $options = programming_get_difficulty_options(); + $mform->addElement('select', 'diffculty', get_string('difficulty', 'programming'), $options); + $inputs = array(); + $inputs[] = $mform->createElement('radio', 'inputs', null, get_string('stdin', 'programming'), 0); + $inputs[] = $mform->createElement('radio', 'inputs', null, get_string('inputfromfile', 'programming'), 1); + $inputs[] = $mform->createElement('text', 'inputfile'); + $mform->setType('inputfile', PARAM_TEXT); + $mform->addGroup($inputs, 'inputs', get_string('inputfile', 'programming'), ' ', false); + $mform->disabledIf('inputfile', 'inputs', 'eq', 0); + + $outputs = array(); + $outputs[] = $mform->createElement('radio', 'outputs', null, get_string('stdout', 'programming'), 0); + $outputs[] = $mform->createElement('radio', 'outputs', null, get_string('outputtofile', 'programming'), 1); + $outputs[] = $mform->createElement('text', 'outputfile'); + $mform->setType('outputfile', PARAM_TEXT); + $mform->addGroup($outputs, 'outputs', get_string('outputfile', 'programming'), ' ', false); + $mform->disabledIf('outputfile', 'outputs', 'eq', 0); + + $options = programming_get_timelimit_options(); + $mform->addElement('select', 'timelimit', get_string('timelimit', 'programming'), $options); + + $options = programming_get_memlimit_options(); + $mform->addElement('select', 'memlimit', get_string('memlimit', 'programming'), $options); + + $options = programming_get_nproc_options(); + $mform->addElement('select', 'nproc', get_string('extraproc', 'programming'), $options); + + $options = array(); + $options[0] = get_string('attemptsunlimited', 'programming'); + $options[1] = get_string("oneattempt", 'programming'); + for ($i = 2; $i <= PROGRAMMING_MAX_ATTEMPTS; $i++) { + $options[$i] = get_string('nattempts', 'programming', $i); + } + $mform->addElement('select', 'attempts', get_string('attempts', 'programming'), $options); + + $mform->addElement('selectyesno', 'keeplatestonly', get_string('keeplatestonly', 'programming')); + + $options = programming_get_showmode_options(); + $mform->addElement('select', 'showmode', get_string('showmode', 'programming'), $options); + +//------------------------------------------------------------------------------- + $features = new stdClass; + $features->groups = true; + $features->groupings = true; + $features->groupmembersonly = true; + $this->standard_coursemodule_elements($features); +//------------------------------------------------------------------------------- +// buttons + $this->add_action_buttons(); + } + + function data_preprocessing(&$default_values) { + if (empty($default_values['discount'])) { + $default_values['discount'] = 8; + } + if (empty($default_values['allowlate'])) { + $default_values['allowlate'] = 1; + } + if (empty($default_values['timelimit'])) { + $default_values['timelimit'] = 1; + } +// + if (empty($default_values['inputs'])) { + $default_values['inputs'] = (isset($default_values['inputfile']) && $default_values['inputfile']) ? 1 : 0; + } + + if (empty($default_values['outputs'])) { + $default_values['outputs'] = (isset($default_values['outputfile']) && $default_values['outputfile']) ? 1 : 0; + } + + if (empty($default_values['langlimit']) && !empty($default_values['id'])) { + $default_values['langlimit'] = array(); + global $DB; + $rows = $DB->get_records('programming_langlimit',array('programmingid'=>$default_values['id'])); + if (is_array($rows)) { + foreach ($rows as $row) { + $default_values['langlimit'][] = $row->languageid; + } + } + } + if (empty($default_values['category']) && !empty($default_values['id'])) { + $default_values['category'] = array(); + global $DB; + $rows1 = $DB->get_records('programming_catproblemmap',array('pid'=>$default_values['id'])); + if (is_array($rows1)) { + foreach ($rows1 as $row1) { + $default_values['category'][] = $row1->catid; + } + } + } + + } +} +?> diff --git a/mod_form.phpold b/mod_form.phpold new file mode 100644 index 0000000..895de15 --- /dev/null +++ b/mod_form.phpold @@ -0,0 +1,147 @@ +dirroot.'/course/moodleform_mod.php'); + +class mod_programming_mod_form extends moodleform_mod { + + function definition() { + + global $CFG, $COURSE; + $mform =& $this->_form; + +//------------------------------------------------------------------------------- + $mform->addElement('header', 'general', get_string('general', 'form')); + + $mform->addElement('text', 'globalid', get_string('globalid', 'programming')); + + $mform->addElement('text', 'name', get_string('name'), array('size'=>'30')); + if (!empty($CFG->formatstringstriptags)) { + $mform->setType('name', PARAM_TEXT); + } else { + $mform->setType('name', PARAM_CLEAN); + } + $mform->addRule('name', null, 'required', null, 'client'); + $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'client'); + $this->add_intro_editor(true, get_string('programmingintro', 'programming')); + + $mform->addElement('header', '', get_string('grade')); + + $options = array(); + $options[0] = get_string('nograde', 'programming'); + for ($i = 5; $i <= 100; $i += 5) { + $options[$i] = $i; + } + $mform->addElement('select', 'grade', get_string('grade'), $options); + + $options = array(); + for ($i = 10; $i > 0; $i -= 1) { + $options[$i] = $i / 10.0; + } + $mform->addElement('select', 'discount', get_string('discount', 'programming'), $options); + + $mform->addElement('date_time_selector', 'timeopen', get_string('timeopen', 'programming')); + $mform->addElement('date_time_selector', 'timediscount', get_string('timediscount', 'programming')); + $mform->addElement('date_time_selector', 'timeclose', get_string('timeclose', 'programming')); + + $mform->addElement('selectyesno', 'allowlate', get_string('allowlate', 'programming')); + +//------------------------------------------------------------------------------- + $mform->addElement('header', '', get_string('program', 'programming')); + + $langs = programming_get_language_options(); + $select = $mform->addElement('select', 'langlimit', get_string('langlimit', 'programming'), $langs); + $select->setMultiple(true); + $cats = programming_get_category_options(); + $select1 = $mform->addElement('select', 'category', get_string('category', 'programming'), $cats); + $select1->setMultiple(true); + $options = programming_get_difficulty_options(); + $mform->addElement('select', 'diffculty', get_string('difficulty', 'programming'), $options); + $inputs = array(); + $inputs[] = $mform->createElement('radio', 'inputs', null, get_string('stdin', 'programming'), 0); + $inputs[] = $mform->createElement('radio', 'inputs', null, get_string('inputfromfile', 'programming'), 1); + $inputs[] = $mform->createElement('text', 'inputfile'); + $mform->addGroup($inputs, 'inputs', get_string('inputfile', 'programming'), ' ', false); + $mform->disabledIf('inputfile', 'inputs', 'eq', 0); + + $outputs = array(); + $outputs[] = $mform->createElement('radio', 'outputs', null, get_string('stdout', 'programming'), 0); + $outputs[] = $mform->createElement('radio', 'outputs', null, get_string('outputtofile', 'programming'), 1); + $outputs[] = $mform->createElement('text', 'outputfile'); + $mform->addGroup($outputs, 'outputs', get_string('outputfile', 'programming'), ' ', false); + $mform->disabledIf('outputfile', 'outputs', 'eq', 0); + + $options = programming_get_timelimit_options(); + $mform->addElement('select', 'timelimit', get_string('timelimit', 'programming'), $options); + + $options = programming_get_memlimit_options(); + $mform->addElement('select', 'memlimit', get_string('memlimit', 'programming'), $options); + + $options = programming_get_nproc_options(); + $mform->addElement('select', 'nproc', get_string('extraproc', 'programming'), $options); + + $options = array(); + $options[0] = get_string('attemptsunlimited', 'programming'); + $options[1] = get_string("oneattempt", 'programming'); + for ($i = 2; $i <= PROGRAMMING_MAX_ATTEMPTS; $i++) { + $options[$i] = get_string('nattempts', 'programming', $i); + } + $mform->addElement('select', 'attempts', get_string('attempts', 'programming'), $options); + + $mform->addElement('selectyesno', 'keeplatestonly', get_string('keeplatestonly', 'programming')); + + $options = programming_get_showmode_options(); + $mform->addElement('select', 'showmode', get_string('showmode', 'programming'), $options); + +//------------------------------------------------------------------------------- + $features = new stdClass; + $features->groups = true; + $features->groupings = true; + $features->groupmembersonly = true; + $this->standard_coursemodule_elements($features); +//------------------------------------------------------------------------------- +// buttons + $this->add_action_buttons(); + } + + function data_preprocessing(&$default_values) { + if (empty($default_values['discount'])) { + $default_values['discount'] = 8; + } + if (empty($default_values['allowlate'])) { + $default_values['allowlate'] = 1; + } + if (empty($default_values['timelimit'])) { + $default_values['timelimit'] = 1; + } +// + if (empty($default_values['inputs'])) { + $default_values['inputs'] = (isset($default_values['inputfile']) && $default_values['inputfile']) ? 1 : 0; + } + + if (empty($default_values['outputs'])) { + $default_values['outputs'] = (isset($default_values['outputfile']) && $default_values['outputfile']) ? 1 : 0; + } + + if (empty($default_values['langlimit']) && !empty($default_values['id'])) { + $default_values['langlimit'] = array(); + global $DB; + $rows = $DB->get_records('programming_langlimit',array('programmingid'=>$default_values['id'])); + if (is_array($rows)) { + foreach ($rows as $row) { + $default_values['langlimit'][] = $row->languageid; + } + } + } + if (empty($default_values['category']) && !empty($default_values['id'])) { + $default_values['category'] = array(); + global $DB; + $rows1 = $DB->get_records('programming_catproblemmap',array('pid'=>$default_values['id'])); + if (is_array($rows1)) { + foreach ($rows1 as $row1) { + $default_values['category'][] = $row1->catid; + } + } + } + + } +} +?> diff --git a/module.js b/module.js new file mode 100644 index 0000000..d672796 --- /dev/null +++ b/module.js @@ -0,0 +1,167 @@ +M.mod_programming = {}; + +M.mod_programming.highlight_code = function(Y, name) { + dp.sh.HighlightAll(name); +}; + +M.mod_programming.init_submit = function(Y) { + Y.one('#submit').hide(); + + Y.one('#submitagain').on('click', function() { + Y.one('#submit').show(); + Y.one('#submitagainconfirm').hide(); + }); +}; + +M.mod_programming.init_fetch_code = function(Y) { + Y.all('a.submit').each(function(node) { + node.on('click', function(evt) { + evt.preventDefault(); + M.mod_programming.fetch_code(Y, node.getAttribute('submitid')); + return false; + }); + }); +}; + +M.mod_programming.fetch_code = function(Y, submitid) { + // Adjust element value of preview and print form + var preview = Y.one('#print_preview_submit_id'); + if (preview != null) preview.value = submitid; + var print = Y.one('#print_submit_id'); + if (print != null) print.value = submitid; + + Y.on('io:success', function(id, resp) { + Y.one('#code').set('text', resp.responseText); + Y.one('div.dp-highlighter').remove(); + dp.sh.HighlightAll('code'); + }); + var sUrl = 'history_fetch_code.php?submitid=' + submitid; + Y.io(sUrl); +}; + +M.mod_programming.init_history = function(Y) { + dp.sh.HighlightAll('code'); + + var r = Y.all('.diff1'); + r.item(0).hide(); + r = Y.all('.diff2'); + r.item(r.size()-1).hide(); + + var is_history_diff_form_submitable = function() { + var f1 = false, f2 = false; + Y.all('.diff1').each(function(node) { + if (node.get('checked')) + f1 = node; + }); + + Y.all('.diff2').each(function(node) { + if (node.get('checked')) + f2 = node; + }); + return f1 && f2 && f1.get('value') != f2.get('value'); + }; + + Y.one('#history-diff-form').on('submit', is_history_diff_form_submitable); + + Y.all('#history-diff-form input[type=radio]').each(function(node) { + node.on('change', function() { + var btn = Y.one('#history-diff-form input[type=submit]'); + if (is_history_diff_form_submitable()) { + btn.removeAttribute('disabled'); + } else { + btn.setAttribute('disabled', true); + } + }); + }); + + Y.one('#history-diff-form input[type=submit]').setAttribute('disabled', true); +}; + +M.mod_programming.init_reports_detail = function(Y) { + var switch_buttons_and_bar = function() { + var show = false; + Y.all('.selectsubmit').each(function(n1) { + if (n1.get('checked')) show = true; + }); + if (show) { + Y.one('#submitbuttons').show(); + Y.one('.paging').hide(); + } else { + Y.one('#submitbuttons').hide(); + Y.one('.paging').show(); + } + }; + + Y.all('.selectsubmit').each(function(node) { + node.on('click', switch_buttons_and_bar); + }); + Y.one('#rejudge').on('click', function() { + Y.one('#submitaction').setAttribute('action', '../rejudge.php'); + Y.one('#submitaction').submit(); + }); + Y.one('#delete').on('click', function() { + Y.one('#submitaction').setAttribute('action', '../deletesubmit.php'); + Y.one('#submitaction').submit(); + }); + + switch_buttons_and_bar(); + + Y.all("#mform1 select").each(function(node) { + node.on('change', function() { + Y.one("#mform1").submit(); + }); + }); + +}; + +M.mod_programming.draw_summary_percent_chart = function(Y, data) { + + var myDataValues = eval(data); + var pieGraph = new Y.Chart({ + render:"#summary-percent-chart", + categoryKey:"result", + seriesKeys:["count"], + dataProvider:myDataValues, + type:"pie", + seriesCollection:[ + { + categoryKey:"result", + valueKey:"count" + } + ] + }); +}; + +M.mod_programming.draw_summary_group_count_chart = function(Y, data) { + var myDataValues = eval(data); + var mychart = new Y.Chart({ + dataProvider:myDataValues, + render:"#summary-group-count-chart", + type:"column" + }); +}; + +M.mod_programming.draw_judgeresult_chart = function(Y, data) { + + var myDataValues = eval(data); + var pieGraph = new Y.Chart({ + render:"#judgeresult-chart", + categoryKey:"result", + seriesKeys:["count"], + dataProvider:myDataValues, + legend: { + position: "right", + styles: { + hAlign: "center", + hSpacing: 4 + } + }, + type:"pie", + seriesCollection:[ + { + categoryKey:"result", + valueKey:"count" + } + ] + }); +}; diff --git a/ojfeeder.php b/ojfeeder.php new file mode 100644 index 0000000..31e4554 --- /dev/null +++ b/ojfeeder.php @@ -0,0 +1,455 @@ +getParam(0)->scalarVal(); + $DB->set_field_select('programming_testers', 'testerid', '0', "testerid = {$judgeid}"); + + return new xmlrpcresp(new xmlrpcval(null, 'null')); +} + +function get_submits($xmlrpcmsg) { + global $CFG,$DB; + + $judgeid = $xmlrpcmsg->getParam(0)->scalarVal(); + $limit = $xmlrpcmsg->getParam(1)->scalarVal(); + + $rs = $DB->get_records('programming_languages'); + $languages = array(); + foreach ($rs as $id => $r) { + $languages[$r->id] = $r->name; + } + $DB->set_field_select('programming_testers', 'testerid',$judgeid, "state = 0 AND testerid = 0"); + + // Find marked records + $sql = "SELECT ps.*, pt.* + FROM {programming_submits} AS ps, + {programming_testers} AS pt, + {programming} AS p + WHERE ps.id = pt.submitid + AND ps.programmingid = p.id + AND pt.testerid = {$judgeid} + AND pt.state = 0 + ORDER BY pt.priority, pt.submitid"; + $rs = $DB->get_records_sql($sql); + $retval = array(); + if (!empty($rs)) { + $ids = array(); + foreach ($rs as $id => $submit) { + $code = programming_format_code($submit->programmingid, $submit, true); + $r = array( + 'id' => new xmlrpcval(sprintf('%d', $submit->id), 'string'), + 'problem_id' => new xmlrpcval( + sprintf('%d', $submit->programmingid), 'string'), + 'language' => new xmlrpcval($languages[$submit->language], + 'string'), + 'code' => new xmlrpcval($code, 'base64'), + ); + $retval[] = new xmlrpcval($r, 'struct'); + $ids[] = $submit->id; + } + + // Update state of the records and prevent them + // from judged multiple times on one judge daemon + $ids = implode(',', $ids); + $DB->set_field_select('programming_testers', 'state',"1", "submitid in ($ids)"); + } + + return new xmlrpcresp(new xmlrpcval($retval, 'array')); +} + +function update_submit_compilemessage($xmlrpcmsg) { + global $CFG,$DB; + + $id = $xmlrpcmsg->getParam(0)->scalarVal(); + $message = $xmlrpcmsg->getParam(1)->scalarVal(); + $DB->set_field_select('programming_submits', 'compilemessage',$message, "id = {$id}"); + + //if ($CFG->rcache === true) { + // rcache_unset('programming_submits', (int) $id); + //} + + return new xmlrpcresp(new xmlrpcval(null, 'null')); +} + +function update_submit_status($xmlrpcmsg) { + global $CFG,$DB; + + $id = $xmlrpcmsg->getParam(0)->scalarVal(); + $status = $xmlrpcmsg->getParam(1)->scalarVal(); + + switch ($status) { + case 'waiting': + $s = PROGRAMMING_STATUS_WAITING; + break; + case 'compiling': + $s = PROGRAMMING_STATUS_COMPILING; + break; + case 'compile_success': + $s = PROGRAMMING_STATUS_COMPILEOK; + break; + case 'compile_failed': + $s = PROGRAMMING_STATUS_COMPILEFAIL; + break; + case 'running': + $s = PROGRAMMING_STATUS_RUNNING; + break; + case 'finish': + $s = PROGRAMMING_STATUS_FINISH; + break; + default: + return new xmlrpcresp(new xmlrpcval(null, 'null')); + } + + if ($status == 'finish' || $status == 'compile_failed') { + $sel = "submitid={$id}"; + $DB->delete_records_select('programming_testers', $sel); + $DB->set_field('programming_submits', 'status', $s, array('id' => $id)); + + if ($status == 'compile_failed') { + $DB->set_field('programming_submits', 'judgeresult', 'CE', array('id' => $id)); + } + + //if ($CFG->rcache === true) { + // rcache_unset('programming_submits', (int) $id); + //} + } + + // Send events + $ue = new stdClass(); + $ue->submitid = $id; + $ue->status = $s; + + return new xmlrpcresp(new xmlrpcval(null, 'null')); +} + +function get_problem($xmlrpcmsg) +{ + global $DB; + $id = $xmlrpcmsg->getParam(0)->scalarVal(); + $p = $DB->get_record('programming', array('id'=> $id)); + + $vtypes = array(0 => 'comparetext', + 1 => 'comparetextwithpe', + 2 => 'comparefile', + 9 => 'customized'); + if (isset($vtypes[$p->validatortype])) { + $vtype = $vtypes[$p->validatortype]; + } else { + $vtype = 0; + } + if ($p->validatortype == 9) { + $vlangs = array(); + foreach ($DB->get_records('programming_languages') as $k => $r){ + $vlangs[$r->id] = $r->name; + } + $vlang = $vlangs[$p->validatorlang]; + $vcode = $p->validator; + } else { + $vlang = $vcode = ''; + } + + $ret = new xmlrpcval(array( + 'id' => new xmlrpcval(sprintf('%d', $p->id), 'string'), + 'timemodified' => new xmlrpcval($p->timemodified, 'int'), + 'input_filename' => new xmlrpcval($p->inputfile, 'string'), + 'output_filename' => new xmlrpcval($p->outputfile, 'string'), + 'validator_code' => new xmlrpcval($vcode, 'base64'), + 'validator_lang' => new xmlrpcval($vlang, 'string'), + 'validator_type' => new xmlrpcval($vtype, 'string'), + 'generator_code' => new xmlrpcval('', 'base64'), + 'generator_type' => new xmlrpcval('', 'string'), + 'standard_code' => new xmlrpcval('', 'string'), + ), 'struct'); + return new xmlrpcresp($ret); +} + +function get_tests($xmlrpcmsg) +{ + global $DB; + $id = $xmlrpcmsg->getParam(0)->scalarVal(); + $full = $xmlrpcmsg->getParam(1)->scalarVal(); + + $tests = array(); + $rs = $DB->get_records('programming_tests', array('programmingid'=> $id)); + if (!empty($rs)) { + foreach ($rs as $rid => $r) { + if ($full) { + if (!empty($r->gzinput)) $r->input = bzdecompress($r->gzinput); + if (!empty($r->gzoutput)) $r->output = bzdecompress($r->gzoutput); + } + $r = new xmlrpcval(array( + 'id' => new xmlrpcval(sprintf('%d', $r->id), 'string'), + 'problem_id' => new xmlrpcval( + sprintf('%d', $r->programmingid), 'string'), + 'timemodified' => new xmlrpcval($r->timemodified, 'int'), + 'input' => new xmlrpcval($full ? $r->input : '', 'base64'), + 'output' => new xmlrpcval($full ? $r->output : '', 'base64'), + 'timelimit' => new xmlrpcval($r->timelimit, 'int'), + 'memlimit' => new xmlrpcval($r->memlimit, 'int'), + 'nproc' => new xmlrpcval($r->nproc, 'int'), + ), 'struct'); + $tests[] = $r; + } + } + return new xmlrpcresp(new xmlrpcval($tests, 'array')); +} + +function get_datafiles($xmlrpcmsg) +{ + global $DB; + $programmingid = $xmlrpcmsg->getParam(0)->scalarVal(); + + $files = array(); + $rs = $DB->get_records('programming_datafile',array( 'programmingid'=> $programmingid), 'seq', 'id, filename, isbinary, timemodified'); + if (!empty($rs)) { + foreach ($rs as $rid => $r) { + $r = new xmlrpcval(array( + 'id' => new xmlrpcval(sprintf('%d', $r->id), 'string'), + 'problem_id' => new xmlrpcval(sprintf('%d', $programmingid), 'string'), + 'filename' => new xmlrpcval($r->filename, 'string'), + 'type' => new xmlrpcval($r->isbinary ? 'binary' : 'text', 'string'), + 'timemodified' => new xmlrpcval($r->timemodified, 'int'), + ), 'struct'); + $files[] = $r; + } + } + + return new xmlrpcresp(new xmlrpcval($files, 'array')); +} + +function get_datafile_data($xmlrpcmsg) +{ + global $DB; + $datafileid = $xmlrpcmsg->getParam(0)->scalarVal(); + + $datafile = $DB->get_record('programming_datafile', array('id'=> $datafileid)); + if (!empty($datafile)) { + if (empty($datafile->checkdata)) { + $r = new xmlrpcval($datafile->data, 'base64'); + } else { + $r = new xmlrpcval($datafile->checkdata, 'base64'); + } + } else { + $r = new xmlrpcval('', 'base64'); + } + + return $r; +} + +function get_presetcodes($xmlrpcmsg) +{ + global $DB; + $programmingid = $xmlrpcmsg->getParam(0)->scalarVal(); + $language = $xmlrpcmsg->getParam(1)->scalarVal(); + + $codes = array(); + $lang = $DB->get_record('programming_languages',array('name'=> $language) ); + $rs = $DB->get_records_select( + 'programming_presetcode', + "programmingid={$programmingid} AND languageid={$lang->id}"); + if (!empty($rs)) { + foreach ($rs as $rid => $r) { + if ($r->name == '' || $r->name == '') { + continue; + } + $code = empty($r->presetcodeforcheck) ? + $r->presetcode : $r->presetcodeforcheck; + $extname = substr($r->name, strrpos($r->name, '.')); + $isheader = in_array($extname, explode(' ', $lang->headerext)); + $r = new xmlrpcval(array( + 'id' => new xmlrpcval(sprintf('%d', $r->id), 'string'), + 'name' => new xmlrpcval($r->name, 'string'), + 'code' => new xmlrpcval($code, 'base64'), + 'isheader' => new xmlrpcval($isheader, 'boolean'), + ), 'struct'); + $codes[] = $r; + } + } + return new xmlrpcresp(new xmlrpcval($codes, 'array')); +} + +function get_test($xmlrpcmsg) +{ + global $DB; + $id = $xmlrpcmsg->getParam(0)->scalarVal(); + + $r = $DB->get_record('programming_tests', array('id'=> $id)); + if (!empty($r->gzinput)) $r->input = bzdecompress($r->gzinput); + if (!empty($r->gzoutput)) $r->output = bzdecompress($r->gzoutput); + $ret = new xmlrpcval(array( + 'id' => new xmlrpcval(sprintf('%d', $r->id), 'string'), + 'problem_id' => new xmlrpcval( + sprintf('%d', $r->programmingid), 'string'), + 'timemodified' => new xmlrpcval(0, 'int'), + 'input' => new xmlrpcval($r->input, 'base64'), + 'output' => new xmlrpcval($r->output, 'base64'), + 'timelimit' => new xmlrpcval($r->timelimit, 'int'), + 'memlimit' => new xmlrpcval($r->memlimit, 'int'), + 'nproc' => new xmlrpcval($r->nproc, 'int'), + ), 'struct'); + return new xmlrpcresp($ret); +} + +function get_gztest($xmlrpcmsg) +{ + global $DB; + $id = $xmlrpcmsg->getParam(0)->scalarVal(); + + $r = $DB->get_record('programming_tests', array('id'=> $id)); + if (empty($r->gzinput)) $r->gzinput = bzcompress($r->input); + if (empty($r->gzoutput)) $r->gzoutput = bzcompress($r->output); + $ret = new xmlrpcval(array( + 'id' => new xmlrpcval(sprintf('%d', $r->id), 'string'), + 'problem_id' => new xmlrpcval( + sprintf('%d', $r->programmingid), 'string'), + 'timemodified' => new xmlrpcval(0, 'int'), + 'input' => new xmlrpcval($r->gzinput, 'base64'), + 'output' => new xmlrpcval($r->gzoutput, 'base64'), + 'timelimit' => new xmlrpcval($r->timelimit, 'int'), + 'memlimit' => new xmlrpcval($r->memlimit, 'int'), + 'nproc' => new xmlrpcval($r->nproc, 'int'), + ), 'struct'); + return new xmlrpcresp($ret); +} + +function update_submit_test_results($xmlrpcmsg) +{ + global $CFG,$DB; + + $sid = $xmlrpcmsg->getParam(0)->scalarVal(); + $results = $xmlrpcmsg->getParam(1); + + $DB->delete_records('programming_test_results', array('submitid'=> $sid)); + $s = $DB->get_record('programming_submits', array('id'=> $sid)); + + $passed = 1; + $oo = array(); + for ($i = 0; $i < $results->arraySize(); $i++) { + $result = $results->arrayMem($i); + + $o = new stdClass; + $o->submitid = $sid; + $o->testid = $result->structMem('test_id')->scalarVal(); + $o->judgeresult= $result->structMem('judge_result')->scalarVal(); + $o->passed = $o->judgeresult == 'AC'; + $o->exitcode = $result->structMem('exitcode')->scalarVal(); + $o->exitsignal = $result->structMem('signal')->scalarVal(); + $o->output = $result->structMem('stdout')->scalarVal(); + $o->stderr = $result->structMem('stderr')->scalarVal(); + $o->timeused = $result->structMem('timeused')->scalarVal(); + $o->memused = $result->structMem('memused')->scalarVal(); + $DB->insert_record('programming_test_results', $o); + $oo[] = $o; + if (!$o->passed) $passed = 0; + } + $timeused = programming_submit_timeused($oo); + $memused = programming_submit_memused($oo); + $judgeresult = programming_submit_judgeresult($oo); + $sql = "UPDATE {programming_submits} + SET timeused = {$timeused}, + memused = {$memused}, + judgeresult = '{$judgeresult}', + passed = {$passed} + WHERE id = {$sid}"; + $DB->execute($sql); + //if ($CFG->rcache === true) { + // rcache_unset('programming_submits', (int) $sid); + //} + + # For moodle 1.9, update grade + programming_update_grade($sid); + + // Send events + $ue = new stdClass(); + $ue->submitid = $sid; + $ue->timeused = $timeused; + $ue->memused = $memused; + $ue->judgeresult = $judgeresult; + $ue->passed = $passed; + + return new xmlrpcresp(new xmlrpcval(null, 'null')); +} + +$addr = getremoteaddr(); +//if (empty($CFG->programming_ojip) || !in_array($addr, explode(' ', $CFG->programming_ojip))) { +if (false) { + header('HTTP/1.0 401 Unauthorized'); + echo '401 Unauthorized.'; + if (empty($CFG->programming_ojip)) { + echo "Please setup OJ IP."; + } + exit; +} +$s = new xmlrpc_server( + array( + 'oj.get_judge_id' => array( + 'function' => 'get_judge_id', + 'signature' => array(array($xmlrpcInt)), + ), + 'oj.reset_submits' => array( + 'function' => 'reset_submits', + 'signature' => array(array($xmlrpcNull, $xmlrpcInt)), + ), + 'oj.get_submits' => array( + 'function' => 'get_submits', + 'signature' => array(array($xmlrpcArray, $xmlrpcInt, $xmlrpcInt))), + 'oj.get_tests' => array( + 'function' => 'get_tests', + 'signature' => array(array($xmlrpcArray, $xmlrpcString, $xmlrpcBoolean)), + ), + 'oj.get_datafiles' => array( + 'function' => 'get_datafiles', + 'signature' => array(array($xmlrpcArray, $xmlrpcString)), + ), + 'oj.get_datafile_data' => array( + 'function' => 'get_datafile_data', + 'signature' => array(array($xmlrpcBase64, $xmlrpcString)), + ), + 'oj.get_presetcodes' => array( + 'function' => 'get_presetcodes', + 'signature' => array(array($xmlrpcArray, $xmlrpcString, $xmlrpcString)), + ), + 'oj.get_test' => array( + 'function' => 'get_test', + 'signature' => array(array($xmlrpcStruct, $xmlrpcString)), + ), + 'oj.get_gztest' => array( + 'function' => 'get_gztest', + 'signature' => array(array($xmlrpcStruct, $xmlrpcString)), + ), + 'oj.get_problem' => array( + 'function' => 'get_problem', + 'signature' => array(array($xmlrpcStruct, $xmlrpcString)), + ), + 'oj.update_submit_compilemessage' => array( + 'function' => 'update_submit_compilemessage', + 'signature' => array(array($xmlrpcNull, $xmlrpcString, $xmlrpcBase64)), + ), + 'oj.update_submit_status' => array( + 'function' => 'update_submit_status', + 'signature' => array(array($xmlrpcNull, $xmlrpcString, $xmlrpcString)), + ), + 'oj.update_submit_test_results' => array( + 'function' => 'update_submit_test_results', + 'signature' => array(array($xmlrpcNull, $xmlrpcString, $xmlrpcArray)), + ), + )); + +?> diff --git a/package.php b/package.php new file mode 100644 index 0000000..4288fd3 --- /dev/null +++ b/package.php @@ -0,0 +1,163 @@ + $id); +if (!empty($group)) { + $params['group'] = $group; +} +$PAGE->set_url('/mod/programming/packaing.php', $params); + +if (!$cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); +} + +if (!$course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); +} + +if (!$programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); +} + +$context = context_module::instance($cm->id); + +require_login($course->id, true, $cm); +require_capability('mod/programming:viewotherprogram', $context); + + +if ($group != 0) { + $users = get_group_users($group); +} else { + if ($usergrps = groups_get_all_groups($course->id, $USER->id)) { + foreach ($usergrps as $ug) { + $users = array_merge($users, get_group_users($ug->id)); + } + } else { + $users = False; + } +} + +$sql = "SELECT * FROM {programming_submits} WHERE programmingid={$programming->id}"; +if (is_array($users)) { + $sql .= ' AND userid IN (' . implode(',', array_keys($users)) . ')'; +} +$sql .= ' ORDER BY timemodified DESC'; +$submits = $DB->get_records_sql($sql); + +$users = array(); +$latestsubmits = array(); +if (is_array($submits)) { + foreach ($submits as $submit) { + if (in_array($submit->userid, $users)) + continue; + $users[] = $submit->userid; + $latestsubmits[] = $submit; + } +} +$sql = 'SELECT * FROM {user} WHERE id IN (' . implode(',', $users) . ')'; +$users = $DB->get_records_sql($sql); + +// create dir +$dirname = $CFG->dataroot . '/temp'; +if (!file_exists($dirname)) { + mkdir($dirname, 0777) or ('Failed to create dir'); +} +$dirname .= '/programming'; +if (!file_exists($dirname)) { + mkdir($dirname, 0777) or ('Failed to create dir'); +} +$dirname .= '/' . $programming->id; +if (file_exists($dirname)) { + if (is_dir($dirname)) { + fulldelete($dirname) or error('Failed to remove dir contents'); + //rmdir($dirname) or error('Failed to remove dir'); + } else { + unlink($dirname) or error('Failed to delete file'); + } +} +mkdir($dirname, 0700) or error('Failed to create dir'); + +$files = array(); +// write files +foreach ($latestsubmits as $submit) { + if ($submit->language == 1) + $ext = '.c'; + elseif ($submit->language == 2) + $ext = '.cpp'; + $filename = $dirname . '/' . $users[$submit->userid]->username . '-' . $submit->id . $ext; + $files[] = $filename; + $f = fopen($filename, 'w'); + fwrite($f, $submit->code); + fwrite($f, "\r\n"); + fclose($f); +} + +// zip file +// eli changed ! 2009-8-18 22:37:12 +$dest = $CFG->dataroot . '/' . $course->id; +if (!file_exists($dest)) { + mkdir($dest, 0777) or error('Failed to create dir'); +} +$dest .= '/programming-' . $programming->id; + +if ($group === 0) { + $dest .= '-all'; +} else { + $group_obj = get_current_group($course->id, True); + $dest .= '-' . $group_obj->name; +} +$dest .= '.zip'; +if (file_exists($dest)) { + unlink($dest) or error("Failed to delete dest file"); +} +zip_files($files, $dest); + +// remove temp +fulldelete($dirname); + +$g = $group === 0 ? 'all' : $group_obj->name; +$from_zip_file = $course->id . 'programming-' . $programming->id . '-' . $g . '.zip'; +$count = count($files); +$referer = $_SERVER['HTTP_REFERER']; +$fs = get_file_storage(); +$ctxid = context_user::instance($USER->id)->id; +$fileinfo = array('contextid' => $ctxid, 'component' => 'user', 'filearea' => 'private', + 'itemid' => 0, 'filepath' => '/', 'filename' => $from_zip_file, + 'timecreated' => time(), 'timemodified' => time(), 'userid' => $USER->id); + +// Get file +$file = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'], $fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename']); + +// Delete it if it exists +if ($file) { + $file->delete(); +} + +$file = $fs->create_file_from_pathname($fileinfo, $dest); +/// Print the page header +$urlbase = "$CFG->httpswwwroot/pluginfile.php"; +$filelink = $CFG->wwwroot.'/pluginfile.php'.'/' . $file->get_contextid() . '/' . $file->get_component() . '/' . $file->get_filearea() . '/' . $file->get_filename() . '?forcedownload=1'; + +$PAGE->set_title($programming->name); +$PAGE->set_heading(format_string($course->fullname)); +echo $OUTPUT->header(); + +/// Print tabs +$renderer = $PAGE->get_renderer('mod_programming'); +$tabs = programming_navtab('reports', 'reports-packaging', $course, $programming, $cm); +echo $renderer->render_navtab($tabs); + +echo html_writer::tag('h2', $programming->name); +echo html_writer::tag('h3', get_string('packagesuccess', 'programming')); + +echo html_writer::tag('p', "" . get_string('download', 'programming') . ''); +echo html_writer::tag('p', "" . get_string('return', 'programming') . ''); + +/// Finish the page +echo $OUTPUT->footer($course); diff --git a/pageheader.php b/pageheader.php new file mode 100644 index 0000000..26165dd --- /dev/null +++ b/pageheader.php @@ -0,0 +1,34 @@ +requires->css = '/mod/programming/styles.css'; + + if ($course->category) { + $navigation = "$course->shortname ->"; + } + + $strprogrammings = get_string('modulenameplural', 'programming'); + $strprogramming = get_string('modulename', 'programming'); + + $meta = ''; + foreach ($CFG->scripts as $script) { + //$meta .= ''; + //$meta .= "\n"; + $PAGE->requires->js($script); + } + + if (isset($cm)) { + $navigation = build_navigation($pagename, $cm); + } else { + $navigation = build_navigation($strprogrammings); + } + + print_header( + empty($programming) ? $strprogrammings.' '.$title : $course->shortname.': '.$programming->name, + $course->fullname, + $navigation, + '', // focus + '', + true, + !empty($cm) ? update_module_button($cm->id, $course->id, $strprogramming) : '', + !empty($cm) ? navmenu($course, $cm) : navmenu($course)); + // */ +?> diff --git a/pix/icon.gif b/pix/icon.gif new file mode 100644 index 0000000..c9e0455 Binary files /dev/null and b/pix/icon.gif differ diff --git a/presetcode/add.php b/presetcode/add.php new file mode 100644 index 0000000..34e51a4 --- /dev/null +++ b/presetcode/add.php @@ -0,0 +1,65 @@ +libdir.'/weblib.php'); + require_once('../lib.php'); + require_once('form.php'); + + $id = required_param('id', PARAM_INT); // programming ID + $params = array('id' => $id); + $PAGE->set_url('/mod/programming/presetcode/add.php', $params); + + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + require_capability('mod/programming:edittestcase', $context); + + $mform = new presetcode_form(); + if ($mform->is_cancelled()) { + redirect(new moodle_url('/mod/programming/presetcode/list.php', array('id' => $cm->id))); + + } else if ($data = $mform->get_data()) { + unset($data->id); + $data->programmingid = $programming->id; + + if ($data->choosename == '1') $data->name = ''; + if ($data->choosename == '2') $data->name = ''; + + $data->sequence = $DB->count_records('programming_presetcode', array('programmingid' => $programming->id), 'MAX(sequence)') + 1; + $DB->insert_record('programming_presetcode', $data); + programming_presetcode_adjust_sequence($programming->id); + + redirect(new moodle_url('/mod/programming/presetcode/list.php', array('id' => $cm->id)), get_string('presetcodeadded', 'programming')); + + } else { + /// Print the page header + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + + /// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('edittest', 'presetcode', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + + /// Print page content + echo html_writer::tag('h2', $programming->name); + echo html_writer::tag('h3', get_string('addpresetcode', 'programming').$OUTPUT->help_icon('presetcode', 'programming')); + + $mform->display(); + + /// Finish the page + echo $OUTPUT->footer($course); + } diff --git a/presetcode/delete.php b/presetcode/delete.php new file mode 100644 index 0000000..e5a8c74 --- /dev/null +++ b/presetcode/delete.php @@ -0,0 +1,31 @@ + $id, 'code' => $code_id); + $PAGE->set_url('/mod/programming/presetcode/delete.php', $params); + + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + require_capability('mod/programming:edittestcase', $context); + + $DB->delete_records('programming_presetcode', array('id' => $code_id)); + programming_presetcode_adjust_sequence($programming->id); + redirect(new moodle_url('/mod/programming/presetcode/list.php', array('id' => $cm->id)), get_string('presetcodedeleted', 'programming')); + +?> diff --git a/presetcode/edit.php b/presetcode/edit.php new file mode 100644 index 0000000..3af5949 --- /dev/null +++ b/presetcode/edit.php @@ -0,0 +1,67 @@ +libdir.'/weblib.php'); + require_once('../lib.php'); + require_once('form.php'); + + $id = required_param('id', PARAM_INT); // programming ID + $code_id = required_param('code', PARAM_INT); + $params = array('id' => $id, 'code' => $code_id); + $PAGE->set_url('/mod/programming/presetcode/edit.php', $params); + + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + require_capability('mod/programming:edittestcase', $context); + + $mform = new presetcode_form(); + if ($mform->is_cancelled()) { + redirect(new moodle_url('/mod/programming/presetcode/list.php', array('id' => $cm->id))); + + } else if ($data = $mform->get_data()) { + $data->id = $data->code; + + if ($data->choosename == '1') $data->name = ''; + if ($data->choosename == '2') $data->name = ''; + + $DB->update_record('programming_presetcode', $data); + + redirect(new moodle_url('/mod/programming/presetcode/list.php', array('id' => $cm->id)), get_string('presetcodemodified', 'programming')); + + } else { + $data = $DB->get_record('programming_presetcode', array('id' => $code_id)); + $data->code = $data->id; + $data->id = $cm->id; + $mform->set_data($data); + + /// Print the page header + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + + /// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('edittest', 'presetcode', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + + echo html_writer::tag('h2', $programming->name); + echo html_writer::tag('h3', get_string('editpresetcode', 'programming').$OUTPUT->help_icon('datafile', 'programming')); + + /// Print page content + $mform->display(); + + /// Finish the page + echo $OUTPUT->footer($course); + } diff --git a/presetcode/form.php b/presetcode/form.php new file mode 100644 index 0000000..4851613 --- /dev/null +++ b/presetcode/form.php @@ -0,0 +1,106 @@ +libdir.'/formslib.php'); + +class presetcode_form extends moodleform { + + function __construct() { + parent::__construct(); + } + + function definition() { + global $CFG, $COURSE, $cm, $programming; + $mform =& $this->_form; + +//------------------------------------------------------------------------------- + $mform->addElement('hidden', 'id', $cm->id); + $mform->addElement('hidden', 'code'); + + $places = array(); + $places[] = $mform->createElement('radio', 'choosename', null, get_string('prepend', 'programming'), 1); + $places[] = $mform->createElement('radio', 'choosename', null, get_string('postpend', 'programming'), 2); + $places[] = $mform->createElement('radio', 'choosename', null, get_string('customfile', 'programming'), 0); + $mform->addGroup($places, 'places', get_string('place', 'programming'), ' ', false); + + $mform->addElement('text', 'name', get_string('filename', 'programming')); + $mform->disabledIf('name', 'choosename', 'not eq', 0); + + $mform->addElement('select', 'languageid', get_string('language', 'programming'), programming_get_language_options($programming)); + + $mform->addElement('textarea', 'presetcode', get_string('codeforuser', 'programming'), 'rows="5" cols="50"'); + + $mform->addElement('checkbox', 'usepresetcodeforcheck', get_string('usepresetcodeforcheck', 'programming')); + $mform->addElement('textarea', 'presetcodeforcheck', get_string('codeforcheck', 'programming'), 'rows="5" cols="50"'); + $mform->disabledIf('presetcodeforcheck', 'usepresetcodeforcheck'); + +// buttons + $this->add_action_buttons(); + } + + function set_data($data) { + if (empty($data->name) || $data->name == '') { + $data->choosename = 1; + $data->name = ''; + } else if ($data->name == '') { + $data->choosename = 2; + $data->name = ''; + } else { + $data->choosename = 0; + } + + if (!empty($data->presetcodeforcheck)) { + $data->usepresetcodeforcheck = true; + } + + if (empty($data->presetcode)) { + $data->usepresetcodeforcheck = false; + } + parent::set_data($data); + } + + function validation($data, $files) { + global $DB; + + $errors = array(); + if ($data['choosename'] == 0) { + /// filename should not be empty + if (empty($data['name'])) { + $errors['name'] = get_string('required'); + } + + /// filename should only contain alpha, digit and underlins + if (empty($errors['name']) && !preg_match('/^[a-zA-Z0-9_\-\.]+$/', $data['name'])) { + $errors['name'] = get_string('filenamechars', 'programming'); + } + + /// file extension must be correct + $lang = $DB->get_record('programming_languages', array('id' => $data['languageid'])); + $allowedext = array_merge(explode(' ', $lang->headerext), explode(' ', $lang->sourceext)); + $ext = substr($data['name'], strrpos($data['name'], '.')); + if (empty($errors['name']) && !in_array($ext, $allowedext)) { + $errors['name'] = get_string('extmustbe', 'programming', implode(', ', $allowedext)); + } + + /// file name should not duplicate + if (empty($errors['name']) && empty($data['id']) && count_records_select('programming_presetcode', "programmingid={$data['programmingid']} AND name='{$data['name']}'")) { + $errors['name'] = get_string('filenamedupliate', 'programming'); + } + + } else if (empty($data['id']) && $data['choosename'] == 1 && count_records_select('programming_presetcode', "programmingid={$data['programmingid']} AND name=''")) { + $errors['places'] = get_string('prependcodeexists', 'programming'); + + } else if (empty($data['id']) && $data['choosename'] == 2 && count_records_select('programming_presetcode', "programmingid={$data['programmingid']} AND name=''")) { + $errors['places'] = get_string('postpendcodeexists', 'programming'); + } + + if (empty($data['presetcode'])) { + $errors['presetcode'] = get_string('required'); + } + + if (!empty($data['usepresetcodeforcheck']) && empty($data['presetcodeforcheck'])) { + $errors['presetcodeforcheck'] = get_string('required'); + } + + return $errors; + } + +} diff --git a/presetcode/list.php b/presetcode/list.php new file mode 100644 index 0000000..48bf4af --- /dev/null +++ b/presetcode/list.php @@ -0,0 +1,111 @@ + $id); + $PAGE->set_url('/mod/programming/presetcode/list.php', $params); + + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + require_capability('mod/programming:viewhiddentestcase', $context); + +/// Print the page header + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + +/// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('edittest', 'presetcode', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + +/// Print page content + echo html_writer::tag('h2', $programming->name); + echo html_writer::tag('h3', get_string('presetcode', 'programming').$OUTPUT->help_icon('presetcode', 'programming')); + print_presetcode_table(); + +/// Finish the page + echo $OUTPUT->footer($course); + +function print_presetcode_table() { + global $CFG, $DB, $OUTPUT, $cm, $page, $perpage, $programming, $course, $language, $groupid; + + $table = new html_table(); + $table->head = array( + get_string('sequence', 'programming'), + get_string('name', 'programming'), + get_string('language'), + get_string('codeforuser', 'programming'), + get_string('codeforcheck', 'programming'), + get_string('action'), + ); + $table->data = array(); + + /*$table->set_attribute('id', 'presetcode-table'); + $table->set_attribute('class', 'generaltable generalbox'); + $table->set_attribute('align', 'center'); + $table->set_attribute('cellpadding', '3'); + $table->set_attribute('cellspacing', '1'); + $table->no_sorting('code'); + $table->setup();*/ + + $codes = $DB->get_records('programming_presetcode', array('programmingid' => $programming->id), 'sequence'); + if (is_array($codes)) { + $langs = $DB->get_records('programming_languages'); + $codes_count = count($codes)-1; + $i = 0; + + $stredit = get_string('edit'); + $strdelete = get_string('delete'); + $strmoveup = get_string('moveup'); + $strmovedown = get_string('movedown'); + + foreach ($codes as $code) { + $data = array(); + $data[] = $code->sequence; + $data[] = htmlentities($code->name); + $data[] = $langs[$code->languageid]->name; + $data[] = $code->presetcode ? 'Yes' : ''; + $data[] = $code->presetcodeforcheck ? 'Yes' : ''; + $url = new moodle_url('/mod/programming/presetcode/edit.php', array('id' => $cm->id, 'code' => $code->id)); + $html = $OUTPUT->action_link($url, html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/edit'))), null, array('class' => 'icon edit', 'title' => $stredit)); + $url = new moodle_url('/mod/programming/presetcode/delete.php', array('id' => $cm->id, 'code' => $code->id)); + $act = new confirm_action(get_string('presetcodedeleted', 'programming')); + $html .= $OUTPUT->action_link($url, html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/delete'))), $act, array('class' => 'icon delete', 'title' => $strdelete)); + if ($i > 0) { + $url = new moodle_url('/mod/programming/presetcode/move.php', array('id' => $cm->id, 'code' => $code->id, 'direction' => 1)); + $html .= $OUTPUT->action_link($url, html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/up'))), null, array('class' => 'icon up', 'title' => $strmoveup)); + } + if ($i < $codes_count) { + $url = new moodle_url('/mod/programming/presetcode/move.php', array('id' => $cm->id, 'code' => $code->id, 'direction' => 2)); + $html .= $OUTPUT->action_link($url, html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/down'))), null, array('class' => 'icon down', 'title' => $strmovedown)); + } + $data[] = $html; + $table->data[] = $data; + $i++; + } + + echo html_writer::table($table); + } else { + echo html_writer::tag('p', get_string('nopresetcode', 'programming')); + } + echo html_writer::tag('p', $OUTPUT->action_link(new moodle_url('/mod/programming/presetcode/add.php', array('id' => $cm->id)), get_string('addpresetcode', 'programming'))); + +} + +?> diff --git a/presetcode/move.php b/presetcode/move.php new file mode 100644 index 0000000..7fe12d9 --- /dev/null +++ b/presetcode/move.php @@ -0,0 +1,33 @@ + $id, 'code' => $code_id, 'direction' => $direction); + $PAGE->set_url('/mod/programming/presetcode/move.php', $params); + + if ($id) { + if (! $cm = get_coursemodule_from_id('programming', $id)) { + error('Course Module ID was incorrect'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + error('Course is misconfigured'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + error('Course module is incorrect'); + } + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + require_capability('mod/programming:edittestcase', $context); + + programming_presetcode_adjust_sequence($programming->id, $code_id, $direction); + redirect(new moodle_url('/mod/programming/presetcode/list.php', array('id' => $cm->id)), get_string('presetcodemoved', 'programming'), 1); + +?> diff --git a/print.php b/print.php new file mode 100644 index 0000000..b150553 --- /dev/null +++ b/print.php @@ -0,0 +1,46 @@ +userid != $USER->id) { + exit(0); + } + + $userfullname = fullname($USER); + $d = $CFG->dataroot.'/temp/programming'; + if (!is_dir($d)) { + if (file_exists($d)) { + unlink($d); + } + mkdir($d); + } + $srcname = tempnam($d, 'pp'); + $destname = tempnam($d, 'pp'); + + $f = fopen($srcname, 'w'); + fwrite($f, $submit->code); + fclose($f); + + putenv('LC_ALL=en_US.UTF-8'); + system("/usr/bin/u2ps -o \"$destname\" -t \"$userfullname\" --gpfamily=\"Monospace\" \"$srcname\" 2>/dev/null"); + $destprt = False; + if (address_in_subnet(getremoteaddr(), '10.1.10.0/23')) { + $destprt = 'cc2'; + } + else if (address_in_subnet(getremoteaddr(), '10.1.111.0/23')) { + $destprt = 'sym1'; + } + + if ($destprt) { + //system("/usr/bin/lp -d $destprt -h 192.168.104.10:631 \"$destname\""); + echo get_string('printfinished', 'programming'); + } else { + echo get_string('printnotallow', 'programming'); + } + + unlink($srcname); + unlink($destname); + +?> diff --git a/print_preview.php b/print_preview.php new file mode 100644 index 0000000..fd4d778 --- /dev/null +++ b/print_preview.php @@ -0,0 +1,30 @@ +userid != $USER->id) { + exit(0); + } + + $userfullname = $USER->username.'-'.fullname($USER); + $d = $CFG->dataroot.'/temp/programming'; + if (!is_dir($d)) { + if (file_exists($d)) { + unlink($d); + } + mkdir($d); + } + $srcname = tempnam($d, 'pp'); + $f = fopen($srcname, 'w'); + fwrite($f, $submit->code); + fclose($f); + + putenv('LC_ALL=en_US.UTF-8'); + header('Content-Type: application/pdf'); + header('Content-Disposition: attachment; filename="source.pdf"'); + passthru("/usr/bin/u2ps -o /dev/stdout -t \"$userfullname\" --gpfamily=\"Monospace\" \"$srcname\" 2>/dev/null | /usr/bin/ps2pdf - -"); + + unlink($srcname); +?> diff --git a/rejudge.php b/rejudge.php new file mode 100644 index 0000000..62f3655 --- /dev/null +++ b/rejudge.php @@ -0,0 +1,64 @@ +set_url('/mod/programming/rejudge.php'); + + if ($id) { + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('Course Module ID was incorrect'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('Course is misconfigured'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('Course module is incorrect'); + } + } + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + require_capability('mod/programming:rejudge', $context); + +/// Print the page header + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + $PAGE->requires->css('/mod/programming/styles.css'); + echo $OUTPUT->header(); + +/// Print the main part of the page + + if (!empty($submitid) || $confirm) { + programming_rejudge($programming, $submitid, $groupid, $ac); + echo html_writer::tag('h2', get_string('rejudgestarted', 'programming')); + echo html_writer::tag('p', $OUTPUT->action_link(new moodle_url($href), get_string('continue'))); + } else { + echo html_writer::start_tag('div', array('class' => 'noticebox')); + echo html_writer::tag('h2', get_string('rejudgeprograms', 'programming', $programming)); + echo html_writer::start_tag('form', array('name' => 'form', 'method' => 'post')); + echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'id', 'value' => $id)); + echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'confirm', 'value' => 1)); + echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'href', 'value' => $_SERVER['HTTP_REFERER'])); + echo html_writer::tag('input', get_string('rejudgeac', 'programming'), array('type' => 'checkbox', 'name' => 'ac', 'value' => 1)); + echo html_writer::start_tag('div', array('class' => 'buttons')); + echo html_writer::empty_tag('input', array('type' => 'submit', 'value' => get_string('yes'))); + echo html_writer::empty_tag('input', array('type' => 'button', 'value' => get_string('no'), 'onclick' => 'javascript:history.go(-1);')); + echo html_writer::end_tag('div'); + echo html_writer::end_tag('form'); + echo html_writer::end_tag('div'); + } + +/// Finish the page + echo $OUTPUT->footer($course); + +?> diff --git a/renderer.php b/renderer.php new file mode 100644 index 0000000..127c473 --- /dev/null +++ b/renderer.php @@ -0,0 +1,36 @@ + 'filters')); + foreach ($filters as $param => $filter) { + $output .= html_writer::start_tag('dl', array('class' => $param)); + $output .= html_writer::tag('dt', $filter['title']); + $output .= html_writer::start_tag('dd'); + foreach ($filter['options'] as $key => $value) { + $nurl = new moodle_url($url); + $nurl->param($param, $key); + $attrs = array('href' => $nurl, 'title' => $value); + if ($defaults[$param] == $key) { + $attrs['class'] = 'here'; + } + + $output .= html_writer::tag('span', html_writer::tag('a', $value, $attrs)); + } + $output .= html_writer::end_tag('dd'); + $output .= html_writer::end_tag('dl'); + } + $output .= html_writer::end_tag('div'); + + return $output; + } + + function render_navtab($tab) { + return print_tabs($tab->tabs, $tab->currenttab, $tab->inactive, $tab->active, true); + } + +} + diff --git a/reports/best.php b/reports/best.php new file mode 100644 index 0000000..024392d --- /dev/null +++ b/reports/best.php @@ -0,0 +1,201 @@ +dirroot.'/lib/tablelib.php'); + + $id = required_param('id', PARAM_INT); // programming ID + $page = optional_param('page', 0, PARAM_INT); + $perpage = optional_param('perpage', 10, PARAM_INT); + $tsort = optional_param('tsort', 'timemodified', PARAM_CLEAN); + $language = optional_param('language', '', PARAM_INT); + $groupid = optional_param('group', 0, PARAM_INT); + + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + $params = array('id' => $cm->id, + 'page' => $page, + 'perpage' => $perpage, + 'tsort' => $tsort, + 'language' => $language, + 'group' => $groupid); + + $PAGE->set_url('/mod/programming/reports/best.php', $params); + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + require_capability('mod/programming:viewreport', $context); + $viewotherresult = has_capability('mod/programming:viewotherresult', $context); + $viewotherprogram = has_capability('mod/programming:viewotherprogram', $context); + + +/// Print the page header + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + +/// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('reports', 'reports-best', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + +/// Print the main part of the page + $renderer = $PAGE->get_renderer('mod_programming'); + + echo html_writer::tag('h2', get_string('allprograms', 'programming')); + echo $renderer->render_filters(build_filters(), $PAGE->url, $params); + + print_submit_table(); + +/// Finish the page + echo $OUTPUT->footer($course); + +function build_filters() { + global $OUTPUT, $DB; + global $perpage, $page, $cm, $course; + + $filters = array(); + + $groups = $DB->get_records('groups', array('courseid' => $course->id)); + if (is_array($groups)) { + $options = array('' => get_string('all')); + foreach ($groups as $group) { + $options[$group->id] = $group->name; + } + $filters['group'] = array( + 'title' => get_string('groups'), + 'options' => $options); + } + + $languages = $DB->get_records('programming_languages'); + if (is_array($languages)) { + $options = array('' => get_string('all')); + foreach ($languages as $language) { + $options[$language->id] = $language->name; + } + $filters['language'] = array( + 'title' => get_string('language', 'programming'), + 'options' => $options); + } + + $options = array(10 => 10, 20 => 20, 30 => 30, 50 => 50, 100 => 100); + $filters['perpage'] = array( + 'title' => get_string('showperpage', 'programming'), + 'options' => $options); + + return $filters; +} + +function get_submits($orderby) { + global $CFG, $DB, $page, $perpage, $programming, $course, $language, $groupid; + + $gfrom = $gwhere = ''; + if ($groupid) { + $gfrom = ", {$CFG->prefix}groups_members AS gm"; + $gwhere = " AND gm.groupid = $groupid AND gm.userid = ps.userid"; + } + + $lwhere = ''; + if ($language) { + $lwhere = " AND ps.language = $language"; + } + + $submits = 0; + $total = 0; + $crit = " FROM {$CFG->prefix}programming_submits AS ps, + {$CFG->prefix}programming_result AS pr + $gfrom + WHERE ps.programmingid = {$programming->id} + AND pr.programmingid = {$programming->id} + AND pr.latestsubmitid = ps.id + AND ps.judgeresult = 'AC' + $gwhere $lwhere + ORDER BY $orderby"; + $sql = "SELECT ps.* $crit"; + $submits = $DB->get_records_sql($sql, null, $page * $perpage, $perpage); + $sql = "SELECT COUNT(*) $crit"; + $total = $DB->count_records_sql($sql); + + return array($submits, $total); +} + +function print_submit_table() { + global $CFG, $DB, $PAGE, $OUTPUT; + global $page, $perpage, $programming, $course, $language, $groupid; + global $viewotherresult, $viewotherprogram; + + $table = new flexible_table('detail-table'); + $def = array('rank', 'ps.timemodified', 'user', 'language', 'code', 'ps.timeused', 'ps.memused'); + $table->define_columns($def); + $headers = array( + get_string('rank', 'programming'), + get_string('submittime', 'programming'), + get_string('fullname'), + get_string('language', 'programming'), + get_string('programcode', 'programming'), + get_string('timeused', 'programming'), + get_string('memused', 'programming'), + ); + $table->define_headers($headers); + + $table->baseurl = $PAGE->url; + $table->set_attribute('cellspacing', '0'); + $table->set_attribute('id', 'detail-table'); + $table->set_attribute('class', 'generaltable generalbox'); + $table->set_attribute('align', 'center'); + $table->set_attribute('cellpadding', '3'); + $table->set_attribute('cellspacing', '1'); + $table->sortable(true, 'ps.timeused'); + $table->no_sorting('rank'); + $table->no_sorting('user'); + $table->no_sorting('language'); + $table->no_sorting('code'); + $table->column_class('user', 'fullname'); + $table->setup(); + $orderby = $table->get_sql_sort(); + + list($submits, $totalcount) = get_submits($orderby); + if (is_array($submits)) { + $i = 0; + $lang = $DB->get_records('programming_languages'); + foreach ($submits as $submit) { + $data = array(); + $data[] = ++$i; + $data[] = userdate($submit->timemodified, '%Y-%m-%d %H:%M:%S'); + $user = $DB->get_record('user', array('id' => $submit->userid)); + $data[] = $OUTPUT->user_picture($user)."".fullname($user).''; + $data[] = $lang[$submit->language]->name; + if ($viewotherprogram) { + $data[] = "".get_string('sizelines', 'programming', $submit).''; + } else { + $data[] = get_string('sizelines', 'programming', $submit); + } + if ($submit->judgeresult) { + $data[] = round($submit->timeused, 3); + $data[] = get_string('memusednk', 'programming', $submit->memused); + } else { + $data[] = ''; $data[] = ''; $data[] = ''; + } + $table->add_data($data); + } + + } + + $table->print_html(); + + $pagingbar = new paging_bar($totalcount, $page, $perpage, $PAGE->url, 'page'); + echo $OUTPUT->render($pagingbar); +} + +?> diff --git a/reports/detail.php b/reports/detail.php new file mode 100644 index 0000000..49bc99a --- /dev/null +++ b/reports/detail.php @@ -0,0 +1,255 @@ +get_record('course', array('id' => $cm->course))) { + print_error('Course is misconfigured'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('Course module is incorrect'); + } + + $params = array('id' => $cm->id, + 'latestonly' => $latestonly, + 'lastinitial' => $lastinitial, + 'firstinitial' => $firstinitial, + 'group' => $groupid, + 'judgeresult' => $judgeresult, + 'page' => $page, + 'perpage' => $perpage); + + $PAGE->set_url('/mod/programming/reports/detail.php', $params); + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + require_capability('mod/programming:viewreport', $context); + + $rejudge = has_capability('mod/programming:rejudge', $context); + $deleteothersubmit = has_capability('mod/programming:deleteothersubmit', $context); + $viewotherresult = has_capability('mod/programming:viewotherresult', $context); + $viewotherprogram = has_capability('mod/programming:viewotherprogram', $context); + + + list($submits, $totalcount) = get_submits(); + +/// Print the page header + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + +/// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('reports', 'reports-detail', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + +/// Print the main part of the page + echo html_writer::tag('h2', get_string('allprograms', 'programming')); + + $renderer = $PAGE->get_renderer('mod_programming'); + echo $renderer->render_filters(build_filters(), $PAGE->url, $params); + + if (is_array($submits)) { + $table = build_result_table($submits, $totalcount); + $strrejudge = get_string('rejudge', 'programming'); + $strdelete = get_string('delete'); + echo html_writer::start_tag('form', array('id' => 'submitaction', 'method' => 'post')); + echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'id', 'value' => $cm->id)); + echo html_writer::table($table); + $pagingbar = new paging_bar($totalcount, $page, $perpage, $PAGE->url, 'page'); + echo $OUTPUT->render($pagingbar); + echo html_writer::start_tag('div', array('id' => 'submitbuttons', 'style' => 'display: none')); + echo html_writer::empty_tag('input', array('id' => 'rejudge', 'type' => 'button', 'value' => $strrejudge)); + echo html_writer::empty_tag('input', array('id' => 'delete', 'type' => 'button', 'value' => $strdelete)); + echo html_writer::end_tag('div'); + echo html_writer::end_tag('form'); + $PAGE->requires->js_init_call('M.mod_programming.init_reports_detail'); + } + +/// Finish the page + echo $OUTPUT->footer($course); + +function get_submits() { + global $CFG, $DB, $page, $perpage, $programming, $course; + global $firstinitial, $lastinitial, $latestonly, $groupid, $language; + global $judgeresult; + + $submits = 0; + $total = 0; + if ($latestonly) { + $rfrom = ", {programming_result} AS pr"; + $rwhere = " AND pr.programmingid = {$programming->id} + AND pr.latestsubmitid = ps.id"; + } else { + $rfrom = $rwhere = ''; + } + if ($firstinitial || $lastinitial) { + $ufrom = ", {user} AS u"; + $uwhere = " AND u.firstnameletter LIKE '{$firstinitial}%' + AND u.lastnameletter LIKE '{$lastinitial}%' + AND u.id = ps.userid"; + } else { + $ufrom = $uwhere = ''; + } + if ($groupid) { + $gfrom = ", {groups_members} AS gm"; + $gwhere = " AND gm.groupid = $groupid AND gm.userid = ps.userid"; + } else { + $gfrom = $gwhere = ''; + } + if ($judgeresult) { + if ($judgeresult == 'NULL') { + $jrwhere = " AND (ps.judgeresult IS NULL OR ps.judgeresult = '')"; + } else { + $jrwhere = " AND ps.judgeresult = '$judgeresult'"; + } + } else { + $jrwhere = ''; + } + + $crit = " FROM {programming_submits} AS ps + $ufrom $rfrom $gfrom + WHERE ps.programmingid = {$programming->id} + $uwhere $rwhere $gwhere $jrwhere + ORDER BY ps.timemodified DESC"; + $sql = "SELECT ps.* $crit"; + $submits = $DB->get_records_sql($sql, null, $page * $perpage, $perpage); + $sql = "SELECT COUNT(*) $crit"; + $total = $DB->count_records_sql($sql); + + return array($submits, $total); +} + +function build_result_table($submits, $total) { + global $CFG, $DB, $PAGE, $OUTPUT, $page, $perpage, $programming, $course, $cm; + global $viewotherresult, $viewotherprogram, $deleteothersubmit, $rejudge; + + $table = new html_table(); + $headers = array( + get_string('ID', 'programming'), + get_string('submittime', 'programming'), + get_string('fullname'), + get_string('language', 'programming'), + get_string('programcode', 'programming'), + get_string('result', 'programming'), + get_string('timeused', 'programming'), + get_string('memused', 'programming'), + ); + if ($deleteothersubmit || $rejudge) $headers[] = get_string('select'); + $table->head = $headers; + $table->colclasses[2] = 'fullname'; + + $table->attributes = array('id' => 'detail-table', 'class' => 'generaltable'); + $table->tablealign = 'center'; + $table->cellpadding = 3; + $table->cellspacing = 1; + + $lang = $DB->get_records('programming_languages'); + foreach ($submits as $submit) { + $data = array(); + $data[] = $submit->id; + $data[] = userdate($submit->timemodified, '%Y-%m-%d %H:%M:%S'); + $user = $DB->get_record('user', array('id' => $submit->userid)); + $data[] = $OUTPUT->user_picture($user)."".fullname($user).''; + $data[] = $lang[$submit->language]->name; + if ($viewotherprogram) { + $url = new moodle_url('../history.php', array('id' => $cm->id, 'userid' => $submit->userid, 'submitid' => $submit->id)); + $data[] = $OUTPUT->action_link($url, get_string('sizelines', 'programming', $submit)); + } else { + $data[] = get_string('sizelines', 'programming', $submit); + } + if ($submit->judgeresult) { + $strresult = get_string($submit->judgeresult, 'programming'); + if ($viewotherresult) { + $url = new moodle_url('../result.php', array('id' => $cm->id, 'submitid' => $submit->id)); + $data[] = $OUTPUT->action_link($url, $strresult); + } else { + $data[] = $strresult; + } + } else { + $data[] = ''; + } + if ($submit->timeused != null) { + $data[] = round($submit->timeused, 3); + } else { + $data[] = ''; + } + if ($submit->memused != null) { + $data[] = get_string('memusednk', 'programming', $submit->memused); + } else { + $data[] = ''; + } + if ($deleteothersubmit || $rejudge) { + $data[] = html_writer::empty_tag('input', array('class' => 'selectsubmit', 'type' => 'checkbox', 'name' => 'submitid[]', 'value' => $submit->id)); + } + $table->data[] = $data; + } + + return $table; +} + +function build_filters() { + global $OUTPUT, $DB; + global $perpage, $page, $cm, $course; + + $filters = array(); + + // select range + $filters['latestonly'] = array( + 'title' => get_string('range', 'programming'), + 'options' => array('0' => get_string('showall', 'programming'), + '1' => get_string('showlatestonly', 'programming'))); + + $options = programming_judgeresult_options(true); + $options['NULL'] = get_string('statusshortnew', 'programming'); + $filters['judgeresult'] = array( + 'title' => get_string('judgeresult', 'programming'), + 'options' => $options); + + $groups = $DB->get_records('groups', array('courseid' => $course->id)); + if (is_array($groups)) { + $options = array('' => get_string('all')); + foreach ($groups as $group) { + $options[$group->id] = $group->name; + } + $filters['group'] = array( + 'title' => get_string('groups'), + 'options' => $options); + } + + $alphabet = explode(',', get_string('alphabet', 'langconfig')); + $options = array('' => get_string('all')); + foreach ($alphabet as $a) { + $options[$a] = $a; + } + $filters['firstinitial'] = array( + 'title' => get_string('firstname'), + 'options' => $options); + $filters['lastinitial'] = array( + 'title' => get_string('lastname'), + 'options' => $options); + + $options = array(10 => 10, 20 => 20, 30 => 30, 50 => 50, 100 => 100); + $filters['perpage'] = array( + 'title' => get_string('showperpage', 'programming'), + 'options' => $options); + + return $filters; +} + +?> diff --git a/reports/judgeresultchart.php b/reports/judgeresultchart.php new file mode 100644 index 0000000..ab68538 --- /dev/null +++ b/reports/judgeresultchart.php @@ -0,0 +1,137 @@ +get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + $params = array('id' => $cm->id, + 'range' => $range, + 'group' => $groupid); + $PAGE->set_url('/mod/programming/reports/judgeresultchart.php', $params); + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + require_capability('mod/programming:viewreport', $context); + + +/// Print the page header + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + +/// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('reports', 'reports-judgeresultchart', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + +/// Print the main part of the page + $renderer = $PAGE->get_renderer('mod_programming'); + echo $renderer->render_filters(build_filters(), $PAGE->url, $params); + print_judgeresult_chart(); + +/// Finish the page + echo $OUTPUT->footer($course); + +function count_judgeresult() { + global $DB, $programming, $range, $groupid; + + $rfrom = $rwhere = ''; + if ($range == 1) { + $rfrom = ", {programming_result} AS pr"; + $rwhere = " AND pr.programmingid = {$programming->id} + AND pr.latestsubmitid = ps.id"; + } + $gfrom = $gwhere = ''; + if ($groupid) { + $gfrom = ", {groups_members} AS gm"; + $gwhere = " AND gm.groupid = $groupid AND gm.userid = ps.userid"; + } + + $sql = "SELECT ps.judgeresult AS judgeresult, + COUNT(*) AS count + FROM {programming_submits} AS ps + $rfrom $gfrom + WHERE ps.programmingid = {$programming->id} + $rwhere $gwhere + GROUP BY ps.judgeresult"; + $rst = $DB->get_recordset_sql($sql); + $ret = array(); + foreach ($rst as $row) { + $ret[$row->judgeresult] = $row->count; + } + return $ret; +} + +function print_judgeresult_chart() { + global $PAGE; + + $values = array(); + + $c = count_judgeresult(); + $keys = array('AC', 'PE', 'WA', 'RE', 'FPE', 'KS', 'TLE', 'MLE', 'OLE', 'CE'); + foreach ($keys as $key) { + $name = get_string($key, 'programming'); + if (!array_key_exists($key, $c)) $c[$key] = 0; + $values[] = array('result' => $name, 'count' => $c[$key]); + $c[$key] = 0; + } + + $others = 0; foreach ($c as $key => $value) $others += $value; + $name = get_string('others', 'programming'); + $values[] = array('result' => $name, 'count' => $others); + + $strjudgeresultchart = get_string('judgeresultcountchart', 'programming'); + $strvisitgoogleneeded = get_string('visitgoogleneeded', 'programming'); + + $jsmodule = array( + 'name' => 'mod_programming', + 'fullpath' => '/mod/programming/module.js', + 'requires' => array('base', 'io', 'node', 'json', 'charts'), + 'strings' => array() + ); + + echo html_writer::tag('div', '', array('id' => 'judgeresult-chart', 'class' => 'chart')); + $PAGE->requires->js_init_call('M.mod_programming.draw_judgeresult_chart', array(json_encode($values)), false, $jsmodule); +} + +function build_filters() { + global $OUTPUT, $DB; + global $perpage, $page, $cm, $course; + + $filters = array(); + + // select range + $filters['range'] = array( + 'title' => get_string('range', 'programming'), + 'options' => array('0' => get_string('showall', 'programming'), + '1' => get_string('showlatestonly', 'programming'))); + + $groups = $DB->get_records('groups', array('courseid' => $course->id)); + if (is_array($groups)) { + $options = array('' => get_string('all')); + foreach ($groups as $group) { + $options[$group->id] = $group->name; + } + $filters['group'] = array( + 'title' => get_string('groups'), + 'options' => $options); + } + + return $filters; +} diff --git a/reports/summary.php b/reports/summary.php new file mode 100644 index 0000000..6626c15 --- /dev/null +++ b/reports/summary.php @@ -0,0 +1,287 @@ +dirroot.'/lib/tablelib.php'); + + $id = optional_param('id', 0, PARAM_INT); // Course Module ID, or + + $params = array(); + if ($id) { + $params['id'] = $id; + } + $PAGE->set_url('/mod/programming/reports/summary.php', $params); + + if ($id) { + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('Course Module ID was incorrect'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('Course is misconfigured'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('Course module is incorrect'); + } + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + require_capability('mod/programming:viewreport', $context); + + // results is stored in a array + $stat_results = array(); + $groupnum = $DB->count_records('groups', array('courseid' => $course->id)); + $groups = $DB->get_records('groups', array('courseid' => $course->id)); + if (is_array($groups)) { + foreach($groups as $group) { + summary_stat($stat_results, $group); + } + } + summary_stat($stat_results); + +/// Print the page header + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + +/// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('reports', 'reports-summary', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + +/// Print the main part of the page + echo html_writer::tag('h2', get_string('summary', 'programming')); + print_summary_table($stat_results); + print_action_table(); + print_summary_chart($stat_results); + +/// Finish the page + echo $OUTPUT->footer($course); + +function print_summary_table($stat_results) { + global $CFG, $DB, $course, $params; + + $student_role = $DB->get_record('role', array('archetype' => 'student')); + + $table = new flexible_table('summary-stat-table'); + $def = array('range', 'studentcount', 'submitcount', 'submitpercent', 'compilecount', 'compilepercent', 'passedcount', 'passedpercent', 'intimepassedcount', 'intimepassedpercent', 'codelines'); + $table->define_columns($def); + $headers = array( + get_string('statrange', 'programming'), + get_string('statstudentcount', 'programming', $student_role->name), + get_string('statsubmitcount', 'programming'), + '%', + get_string('statcompiledcount', 'programming'), + '%', + get_string('statpassedcount', 'programming'), + '%', + get_string('statintimepassedcount', 'programming'), + '%', + get_string('stataveragelines', 'programming')); + $table->define_headers($headers); + + $table->set_attribute('id', 'summary-stat-table'); + $table->set_attribute('class', 'generaltable generalbox'); + $table->set_attribute('cellspacing', '1'); + $table->define_baseurl('/mod/programming/view.php', $params); + $table->setup(); + + foreach ($stat_results as $row) { + $data = array(); + $data[] = $row['name']; + $data[] = $row['studentcount']; + $data[] = $row['submitcount']; + $data[] = ($row['studentcount'] > 0 ? round($row['submitcount'] / $row['studentcount'] * 100, 0) : 0).'%'; + $data[] = $row['compiledcount']; + $data[] = ($row['studentcount'] > 0 ? round($row['compiledcount'] / $row['studentcount'] * 100, 0) : 0).'%'; + $data[] = $row['passedcount']; + $data[] = ($row['studentcount'] > 0 ? round($row['passedcount'] / $row['studentcount'] * 100, 0) : 0).'%'; + $data[] = $row['intimepassedcount']; + $data[] = ($row['studentcount'] > 0 ? round($row['intimepassedcount'] / $row['studentcount'] * 100, 0) : 0).'%'; + $data[] = $row['submitcount'] > 0 ? round($row['averagelines']) : 0; + $table->add_data($data); + } + + $table->print_html(); +} + +function print_summary_chart($stat_results) { + global $PAGE; + + $summary = array_pop($stat_results); + $acintime = $summary['intimepassedcount']; + $ac = $summary['passedcount'] - $summary['intimepassedcount']; + $se = $summary['compiledcount'] - $summary['passedcount']; + $ce = $summary['submitcount'] - $summary['compiledcount']; + $ns = $summary['studentcount'] - $summary['submitcount']; + $strresultcount = get_string('resultcountchart', 'programming'); + $stracintime = get_string('resultchartacintime', 'programming'); + $strac = get_string('resultchartacdiscount', 'programming'); + $strse = get_string('resultchartsomethingwrong', 'programming'); + $strce = get_string('resultchartcompileerror', 'programming'); + $strns = get_string('resultchartnosubmition', 'programming'); + $strgroupresultcount = get_string('resultgroupcountchart', 'programming'); + + $jsmodule = array( + 'name' => 'mod_programming', + 'fullpath' => '/mod/programming/module.js', + 'requires' => array('base', 'io', 'node', 'json', 'charts'), + 'strings' => array() + ); + + $groupcount = count($stat_results); + if ($groupcount) { + $data = array(); + foreach ($stat_results as $group) { + $data[] = array( + 'category' => $group['name'], + 'acintime' => $group['intimepassedcount'], + 'ac' => $group['passedcount'] - $group['intimepassedcount'], + 'se' => $group['compiledcount'] - $group['passedcount'], + 'ce' => $group['submitcount'] - $group['compiledcount'], + ); + } + + echo html_writer::tag('div', '', array('id' => 'summary-group-count-chart', 'class' => 'chart')); + $PAGE->requires->js_init_call('M.mod_programming.draw_summary_group_count_chart', array(json_encode($data)), false, $jsmodule); + } + + $percent_chart_data = array( + array('result' => $stracintime, 'count' => $acintime), + array('result' => $strac, 'count' => $ac), + array('result' => $strse, 'count' => $se), + array('result' => $strce, 'count' => $ce), + array('result' => $strns, 'count' => $ns) + ); + echo html_writer::tag('div', '', array('id' => 'summary-percent-chart', 'class' => 'chart')); + $PAGE->requires->js_init_call('M.mod_programming.draw_summary_percent_chart', array(json_encode($percent_chart_data)), false, $jsmodule); +} + +/** + * 统计各个小组完成题目的情况。 + * + * 目前此函数只处理 roleid 为 5 即学生的情况。 + * + * @param $state_results 存储统计结果 + * @param $group 要统计的小组,如果为 null 则统计全部人员的情况 + */ +function summary_stat(&$stat_results, $group = null) { + global $USER, $CFG, $DB, $course, $programming; + + $context = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $course->id)); + $roleid = 5; + + $student_role = $DB->get_record('role', array('archetype' => 'student')); + + if ($group) { + $gfrom = ", {groups_members} AS gm"; + $gwhere = " AND gm.groupid = $group->id AND ra.userid = gm.userid "; + $name = $group->name; + } else { + $gfrom = $gwhere = ''; + $name = get_string('allstudents', 'programming', $student_role->name); + } + + $studentcount = $DB->count_records_sql(" + SELECT COUNT(*) + FROM {role_assignments} AS ra + $gfrom + WHERE ra.roleid = $roleid + AND ra.contextid = $context->id + $gwhere"); + $submitcount = $DB->count_records_sql(" + SELECT COUNT(*) + FROM {role_assignments} AS ra, + {programming_result} AS pr + $gfrom + WHERE ra.roleid = $roleid + AND ra.contextid = $context->id + AND pr.programmingid = $programming->id + AND ra.userid = pr.userid + $gwhere"); + $compiledcount = $DB->count_records_sql(" + SELECT COUNT(*) + FROM {role_assignments} AS ra, + {programming_result} AS pr, + {programming_submits} AS ps + $gfrom + WHERE ps.programmingid = $programming->id + AND pr.programmingid = $programming->id + AND ra.roleid = $roleid + AND ra.contextid = $context->id + AND ps.id = pr.latestsubmitid + AND pr.userid = ra.userid + AND ps.judgeresult != 'CE' AND ps.judgeresult != '' + $gwhere"); + $passedcount = $DB->count_records_sql(" + SELECT COUNT(*) + FROM {role_assignments} AS ra, + {programming_submits} AS ps, + {programming_result} AS pr + $gfrom + WHERE ps.programmingid = {$programming->id} + AND pr.programmingid = {$programming->id} + AND ra.roleid = $roleid + AND ra.contextid = $context->id + AND pr.userid = ra.userid + AND pr.latestsubmitid = ps.id + AND ps.passed = 1 + $gwhere"); + $intimepassedcount = $DB->count_records_sql(" + SELECT COUNT(*) + FROM {role_assignments} AS ra, + {programming_submits} AS ps, + {programming_result} AS pr + $gfrom + WHERE ps.programmingid = {$programming->id} + AND pr.programmingid = {$programming->id} + AND ra.roleid = $roleid + AND ra.contextid = $context->id + AND pr.userid = ra.userid + AND pr.latestsubmitid = ps.id + AND ps.timemodified <= {$programming->timediscount} + AND ps.passed = 1 + $gwhere"); + $codeavg = $DB->get_record_sql(" + SELECT AVG(codelines) as codelines + FROM {role_assignments} AS ra, + {programming_submits} AS ps, + {programming_result} AS pr + $gfrom + WHERE ps.programmingid = {$programming->id} + AND pr.programmingid = {$programming->id} + AND pr.latestsubmitid = ps.id + AND ra.roleid = $roleid + AND ra.contextid = $context->id + AND pr.userid = ra.userid + $gwhere"); + $codeavg = intval($codeavg->codelines); + array_push($stat_results, + array('name' => $name, + 'studentcount' => $studentcount, + 'submitcount' => $submitcount, + 'compiledcount' => $compiledcount, + 'passedcount' => $passedcount, + 'intimepassedcount' => $intimepassedcount, + 'averagelines' => $codeavg)); + return; +} + +function print_action_table() { + global $CFG, $OUTPUT, $cm, $context; + + echo '
    '; + if (has_capability('mod/programming:viewotherprogram', $context)) { + echo $OUTPUT->single_button(new moodle_url('/mod/programming/package.php', array('id' => $cm->id)), get_string('package', 'programming'), 'get'); + } + echo ''; + if (has_capability('mod/programming:edittestcase', $context)) { + echo $OUTPUT->single_button(new moodle_url('/mod/programming/rejudge.php', array('id' => $cm->id)), get_string('rejudge', 'programming'), 'get'); + } + echo '
    '; +} + +?> diff --git a/reports/testcase.php b/reports/testcase.php new file mode 100644 index 0000000..d386013 --- /dev/null +++ b/reports/testcase.php @@ -0,0 +1,106 @@ +dirroot.'/lib/tablelib.php'); + + $a = optional_param('a', 0, PARAM_INT); // programming ID + + if (! $programming = get_record('programming', 'id', $a)) { + error('Course module is incorrect'); + } + if (! $course = get_record('course', 'id', $programming->course)) { + error('Course is misconfigured'); + } + if (! $cm = get_coursemodule_from_instance('programming', $programming->id, $course->id)) { + error('Course Module ID was incorrect'); + } + $context = context_module::instance($cm->id); + + require_login($course->id); + require_capability('mod/programming:viewreport', $context); + + +/// Print the page header + $pagename = get_string('reports', 'programming'); + $CFG->scripts[] = 'http://www.google.com/jsapi'; + include_once('../pageheader.php'); + +/// Print tabs + $currenttab = 'reports'; + $currenttab2 = 'summary'; + include_once('../tabs.php'); + +/// Print the main part of the page + echo '
    '; + print_testcase_chart($programming->id); + echo '
    '; + +/// Finish the page + $OUTPUT->footer($course); + +function print_testcase_chart($programmingid) { + global $CFG; + + $j = array('AC', 'WA', 'RE'); + $sql = "SELECT * FROM ( + SELECT id AS testid, seq, weight, pub + FROM {$CFG->prefix}programming_tests + WHERE programmingid = {$programmingid} + ) AS pt"; + foreach ($j as $r) { + $sql .= " LEFT JOIN \n"; + $sql .= "(SELECT testid, COUNT(*) AS $r + FROM {$CFG->prefix}programming_result AS pr, + {$CFG->prefix}programming_test_results AS ptr + WHERE pr.programmingid = {$programmingid} + AND ptr.submitid = pr.latestsubmitid + AND ptr.judgeresult='$r' + GROUP BY testid) AS SE{$r}"; + $sql .= " USING (testid)\n"; + } + $sql .= "ORDER BY seq"; + + #print "
    $sqldefine_columns(array('seq', 'weight', 'pub', 'ac', 'wa', 're'));
    +    $headers = array(
    +            get_string('testcase', 'programming'),
    +            get_string('weight', 'programming'),
    +            get_string('public', 'programming'),
    +            get_string('AC', 'programming'),
    +            get_string('WA', 'programming'),
    +            get_string('RE', 'programming'),
    +        );
    +    $table->define_headers($headers);
    +
    +    #$table->pagesize($perpage, $total);
    +    $table->set_attribute('cellspacing', '0');
    +    $table->set_attribute('id', 'detail-table');
    +    $table->set_attribute('class', 'generaltable generalbox');
    +    $table->set_attribute('align', 'center');
    +    $table->set_attribute('cellpadding', '3');
    +    $table->set_attribute('cellspacing', '1');
    +    $table->setup();
    +
    +    $rst = get_recordset_sql($sql);
    +    while ($row = $rst->FetchNextObject(false)) {
    +        $data = array();
    +        $data[] = $row->seq;
    +        $data[] = $row->weight;
    +        $data[] = programming_testcase_pub_getstring($row->pub);
    +        $data[] = $row->AC;
    +        $data[] = $row->WA;
    +        $data[] = $row->RE;
    +        $table->add_data($data);
    +    }
    +    $rst->Close();
    +
    +    $table->print_html();
    +
    +    return 0;
    +}
    +
    +?>
    diff --git a/resemble/analyze.php b/resemble/analyze.php
    new file mode 100644
    index 0000000..90826f5
    --- /dev/null
    +++ b/resemble/analyze.php
    @@ -0,0 +1,133 @@
    + $id, 'group' => $group, 'action' => $action, 'max' => $max, 'lowest' => $lowest);
    +$PAGE->set_url('/mod/programming/resemble/analyze.php', $params);
    +
    +if (!$cm = get_coursemodule_from_id('programming', $id)) {
    +    print_error('invalidcoursemodule');
    +}
    +
    +if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
    +    print_error('coursemisconf');
    +}
    +
    +if (!$programming = $DB->get_record('programming', array('id' => $cm->instance))) {
    +    print_error('invalidprogrammingid', 'programming');
    +}
    +
    +require_login($course->id, true, $cm);
    +
    +$context = context_module::instance($cm->id);
    +require_capability('mod/programming:updateresemble', $context);
    +
    +
    +/// Print the page header
    +$PAGE->set_title($programming->name);
    +$PAGE->set_heading(format_string($course->fullname));
    +echo $OUTPUT->header();
    +
    +/// Print tabs
    +$renderer = $PAGE->get_renderer('mod_programming');
    +$tabs = programming_navtab('resemble', 'resemble-analyze', $course, $programming, $cm);
    +echo $renderer->render_navtab($tabs);
    +
    +/// Print page content
    +
    +if ($action) {
    +    if ($group != 0) {
    +        $users = get_group_users($group);
    +    } else {
    +        if ($usergrps = groups_get_all_groups($course->id, $USER->id)) {
    +            foreach ($usergrps as $ug) {
    +                $users = array_merge($users, get_group_users($ug->id));
    +            }
    +        } else {
    +            $users = False;
    +        }
    +    }
    +
    +    $sql = "SELECT * FROM {programming_submits} WHERE programmingid={$programming->id}";
    +    if (is_array($users)) {
    +        $sql .= ' AND userid IN (' . implode(',', array_keys($users)) . ')';
    +    }
    +    $sql .= ' ORDER BY timemodified DESC';
    +    $submits = $DB->get_records_sql($sql);
    +
    +    $users = array();
    +    $latestsubmits = array();
    +    if (is_array($submits)) {
    +        foreach ($submits as $submit) {
    +            if (in_array($submit->userid, $users))
    +                continue;
    +            $users[] = $submit->userid;
    +            $latestsubmits[] = $submit;
    +        }
    +    }
    +    $sql = 'SELECT * FROM {user} WHERE id IN (' . implode(',', $users) . ')';
    +    $users = $DB->get_records_sql($sql);
    +
    +    // create dir
    +    $dirname = $CFG->dataroot . '/temp';
    +    if (!file_exists($dirname)) {
    +        mkdir($dirname, 0777) or ( 'Failed to create dir');
    +    }
    +    $dirname .= '/programming';
    +    if (!file_exists($dirname)) {
    +        mkdir($dirname, 0777) or ( 'Failed to create dir');
    +    }
    +    $dirname .= '/' . $programming->id;
    +    if (file_exists($dirname)) {
    +        if (is_dir($dirname)) {
    +            fulldelete($dirname) or error('Failed to remove dir contents');
    +            //rmdir($dirname) or error('Failed to remove dir');
    +        } else {
    +            unlink($dirname) or error('Failed to delete file');
    +        }
    +    }
    +    mkdir($dirname, 0700) or error('Failed to create dir');
    +
    +    $files = array();
    +    // write files
    +    $exts = array('.txt', '.c', '.cxx', '.java', '.java', '.pas', '.py', '.cs');
    +    foreach ($latestsubmits as $submit) {
    +        $ext = $exts[$submit->language];
    +        $filename = "{$dirname}/{$submit->userid}-{$submit->id}{$ext}";
    +        $files[] = $filename;
    +        $f = fopen($filename, 'w');
    +        fwrite($f, $submit->code);
    +        fwrite($f, "\r\n");
    +        fclose($f);
    +    }
    +    //echo "dir is $dirname 
    "; + + $cwd = getcwd(); + chdir($dirname); + $url = array(); + exec("perl $cwd/moss.pl -u {$CFG->programming_moss_userid} *", $url); + print_r($url); + $url = $url[count($url) - 1]; + echo "See result $url
    "; + + // remove temp + fulldelete($dirname); + + parse_result($programming->id, $url, $max, $lowest); +} else { + include_once('resemble_analyze.tpl.php'); +} + +/// Finish the page +$OUTPUT->footer($course); +?> diff --git a/resemble/compare.php b/resemble/compare.php new file mode 100644 index 0000000..00b1ec1 --- /dev/null +++ b/resemble/compare.php @@ -0,0 +1,74 @@ + $id, 'rid' => $rid, 'page' => $page, 'perpage' => $perpage); + $PAGE->set_url('/mod/programming/resemble/compare.php', $params); + + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + + $context = context_module::instance($cm->id); + + $resemble = $DB->get_record('programming_resemble', array('id' => $rid)); + $submit1 = $DB->get_record('programming_submits', array('id' => $resemble->submitid1)); + $submit2 = $DB->get_record('programming_submits', array('id' => $resemble->submitid2)); + if ($submit1->userid == $USER->id || $submit2->userid == $USER->id) { + require_capability('mod/programming:viewresemble', $context); + } else { + require_capability('mod/programming:editresemble', $context); + } + + $user1 = $DB->get_record('user', array('id' => $submit1->userid)); + $user2 = $DB->get_record('user', array('id' => $submit2->userid)); + + + // Change matched lines into array, with an matched id as first element + $lines1 = explode("\n", $submit1->code); + $lines2 = explode("\n", $submit2->code); + + $matches = explode(';', $resemble->matchedlines); + $mid = 1; + foreach($matches as $range) { + list($range1, $range2) = explode(',', $range); + + list($start, $end) = explode('-', $range1); + while ($start <= $end) { + if (array_key_exists($start, $lines1) && + !is_array($lines1[$start])) { + $lines1[$start] = array($mid, $lines1[$start]); + } + $start++; + } + list($start, $end) = explode('-', $range2); + while ($start <= $end) { + if (array_key_exists($start, $lines2) && + !is_array($lines2[$start])) { + $lines2[$start] = array($mid, $lines2[$start]); + } + $start++; + } + $mid++; + } + + + include_once('resemble_compare.tpl.php'); + +?> diff --git a/resemble/edit.php b/resemble/edit.php new file mode 100644 index 0000000..06c3619 --- /dev/null +++ b/resemble/edit.php @@ -0,0 +1,130 @@ + $id, 'action' => $action, 'page' => $page, 'perpage' => $perpage, 'format' => $format); + $PAGE->set_url('/mod/programming/resemble/edit.php', $params); + + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + + $context = context_module::instance($cm->id); + + $successurl = new moodle_url('/mod/programming/resemble/edit.php', array('id' => $cm->id, 'page' => $page, 'perpage' => $perpage)); + switch($action) { + case 'list': + require_capability('mod/programming:editresemble', $context); + $offset = $page * $perpage; + $sql = "SELECT re.*, ua.id as userid1, ub.id as userid2 + FROM {programming_resemble} AS re, + {programming_submits} AS sa, + {programming_submits} AS sb, + {user} AS ua, + {user} AS ub + WHERE re.programmingid={$programming->id} + AND re.flag>=0 + AND re.submitid1 = sa.id + AND re.submitid2 = sb.id + AND sa.userid = ua.id + AND sb.userid = ub.id + ORDER BY id + LIMIT $offset, $perpage"; + $resemble = $DB->get_records_sql($sql); + if (!is_array($resemble)) $resemble = array(); + $uids = array(); $sids = array(); + foreach($resemble as $r) { + $uids[] = $r->userid1; + $uids[] = $r->userid2; + $sids[] = $r->submitid1; + $sids[] = $r->submitid2; + } + if (!empty($uids)) { + $users = $DB->get_records_select('user', 'id IN ('.implode($uids, ',').')'); + } + if (!empty($sids)) { + $submits = $DB->get_records_select('programming_submits', 'id IN ('.implode($sids, ',').')'); + } + $totalcount = $DB->count_records_select('programming_resemble', 'programmingid='.$programming->id.' AND flag>=0'); + + /// Print page content + if ($format == 'json') { + require_once('../lib/JSON.php'); + $data = array(array_keys($resemble), array_values($resemble), array_keys($users), array_values($users)); + $json = new Services_JSON(); + echo $json->encode($data); + } else { + include_once('resemble_edit.tpl.php'); + } + + break; + + case 'confirm': + require_capability('mod/programming:editresemble', $context); + $select = 'id in ('.join(',', $rids).')'; + $sql = $DB->set_field_select('programming_resemble', 'flag', PROGRAMMING_RESEMBLE_CONFIRMED, $select); + redirect($successurl, get_string('resembleeditsucceeded', 'programming'), 2); + break; + + case 'warn': + require_capability('mod/programming:editresemble', $context); + $select = 'id in ('.join(',', $rids).')'; + $sql = $DB->set_field_select('programming_resemble', 'flag', PROGRAMMING_RESEMBLE_WARNED, $select); + redirect($successurl, get_string('resembleeditsucceeded', 'programming'), 2); + break; + + case 'reset': + require_capability('mod/programming:editresemble', $context); + $select = 'id in ('.join(',', $rids).')'; + $sql = $DB->set_field_select('programming_resemble', 'flag', PROGRAMMING_RESEMBLE_NEW, $select); + redirect($successurl, get_string('resembleeditsucceeded', 'programming'), 2); + break; + + case 'flag1': + require_capability('mod/programming:editresemble', $context); + $select = 'id in ('.join(',', $rids).')'; + $sql = $DB->set_field_select('programming_resemble', 'flag', PROGRAMMING_RESEMBLE_FLAG1, $select); + redirect($successurl, get_string('resembleeditsucceeded', 'programming'), 2); + break; + + case 'flag2': + require_capability('mod/programming:editresemble', $context); + $select = 'id in ('.join(',', $rids).')'; + $sql = $DB->set_field_select('programming_resemble', 'flag', PROGRAMMING_RESEMBLE_FLAG2, $select); + redirect($successurl, get_string('resembleeditsucceeded', 'programming'), 2); + break; + + case 'flag3': + require_capability('mod/programming:editresemble', $context); + $select = 'id in ('.join(',', $rids).')'; + $sql = $DB->set_field_select('programming_resemble', 'flag', PROGRAMMING_RESEMBLE_FLAG3, $select); + redirect($successurl, get_string('resembleeditsucceeded', 'programming'), 2); + break; + + case 'delete': + require_capability('mod/programming:editresemble', $context); + $select = 'id in ('.join(',', $rids).')'; + $sql = $DB->set_field_select('programming_resemble', 'flag', PROGRAMMING_RESEMBLE_DELETED, $select); + redirect($successurl, get_string('resembleeditsucceeded', 'programming'), 2); + break; + } + +?> diff --git a/resemble/moss.pl b/resemble/moss.pl new file mode 100644 index 0000000..460b2c0 --- /dev/null +++ b/resemble/moss.pl @@ -0,0 +1,366 @@ +#!/usr/bin/perl +# +# Please read all the comments down to the line that says "TOP". +# These comments are divided into three sections: +# +# 1. usage instructions +# 2. installation instructions +# 3. standard copyright +# +# Feel free to share this script with other instructors of programming +# classes, but please do not place the script in a publicly accessible +# place. Comments, questions, and bug reports should be sent to +# moss-request@cs.berkeley.edu. +# +# IMPORTANT: This script is known to work on Unix and on Windows using Cygwin. +# It is not known to work on other ways of using Perl under Windows. If the +# script does not work for you under Windows, you can try the email-based +# version for Windows (available on the Moss home page). +# + +# +# Section 1. Usage instructions +# +# moss [-l language] [-d] [-b basefile1] ... [-b basefilen] [-m #] [-c "string"] file1 file2 file3 ... +# +# The -l option specifies the source language of the tested programs. +# Moss supports many different languages; see the variable "languages" below for the +# full list. +# +# Example: Compare the lisp programs foo.lisp and bar.lisp: +# +# moss -l lisp foo.lisp bar.lisp +# +# +# The -d option specifies that submissions are by directory, not by file. +# That is, files in a directory are taken to be part of the same program, +# and reported matches are organized accordingly by directory. +# +# Example: Compare the programs foo and bar, which consist of .c and .h +# files in the directories foo and bar respectively. +# +# moss -d foo/*.c foo/*.h bar/*.c bar/*.h +# +# Example: Each program consists of the *.c and *.h files in a directory under +# the directory "assignment1." +# +# moss -d assignment1/*/*.h assignment1/*/*.c +# +# +# The -b option names a "base file". Moss normally reports all code +# that matches in pairs of files. When a base file is supplied, +# program code that also appears in the base file is not counted in matches. +# A typical base file will include, for example, the instructor-supplied +# code for an assignment. Multiple -b options are allowed. You should +# use a base file if it is convenient; base files improve results, but +# are not usually necessary for obtaining useful information. +# +# IMPORTANT: Unlike previous versions of moss, the -b option *always* +# takes a single filename, even if the -d option is also used. +# +# Examples: +# +# Submit all of the C++ files in the current directory, using skeleton.cc +# as the base file: +# +# moss -l cc -b skeleton.cc *.cc +# +# Submit all of the ML programs in directories asn1.96/* and asn1.97/*, where +# asn1.97/instructor/example.ml and asn1.96/instructor/example.ml contain the base files. +# +# moss -l ml -b asn1.97/instructor/example.ml -b asn1.96/instructor/example.ml -d asn1.97/*/*.ml asn1.96/*/*.ml +# +# The -m option sets the maximum number of times a given passage may appear +# before it is ignored. A passage of code that appears in many programs +# is probably legitimate sharing and not the result of plagiarism. With -m N, +# any passage appearing in more than N programs is treated as if it appeared in +# a base file (i.e., it is never reported). Option -m can be used to control +# moss' sensitivity. With -m 2, moss reports only passages that appear +# in exactly two programs. If one expects many very similar solutions +# (e.g., the short first assignments typical of introductory programming +# courses) then using -m 3 or -m 4 is a good way to eliminate all but +# truly unusual matches between programs while still being able to detect +# 3-way or 4-way plagiarism. With -m 1000000 (or any very +# large number), moss reports all matches, no matter how often they appear. +# The -m setting is most useful for large assignments where one also a base file +# expected to hold all legitimately shared code. The default for -m is 10. +# +# Examples: +# +# moss -l pascal -m 2 *.pascal +# moss -l cc -m 1000000 -b mycode.cc asn1/*.cc +# +# +# The -c option supplies a comment string that is attached to the generated +# report. This option facilitates matching queries submitted with replies +# received, especially when several queries are submitted at once. +# +# Example: +# +# moss -l scheme -c "Scheme programs" *.sch +# +# The -n option determines the number of matching files to show in the results. +# The default is 250. +# +# Example: +# moss -c java -n 200 *.java +# The -x option sends queries to the current experimental version of the server. +# The experimental server has the most recent Moss features and is also usually +# less stable (read: may have more bugs). +# +# Example: +# +# moss -x -l ml *.ml +# + + +# +# Section 2. Installation instructions. +# +# You may need to change the very first line of this script +# if perl is not in /usr/bin on your system. Just replace /usr/bin +# with the pathname of the directory where perl resides. +# + +# +# 3. Standard Copyright +# +#Copyright (c) 1997 The Regents of the University of California. +#All rights reserved. +# +#Permission to use, copy, modify, and distribute this software for any +#purpose, without fee, and without written agreement is hereby granted, +#provided that the above copyright notice and the following two +#paragraphs appear in all copies of this software. +# +#IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR +#DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT +#OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF +#CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, +#INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY +#AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS +#ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO +#PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. +# +# +# STOP. It should not be necessary to change anything below this line +# to use the script. +# +use IO::Socket; + +# +# As of the date this script was written, the following languages were supported. This script will work with +# languages added later however. Check the moss website for the full list of supported languages. +# +@languages = ("c", "cc", "java", "ml", "pascal", "ada", "lisp", "scheme", "haskell", "fortran", "ascii", "vhdl", "perl", "matlab", "python", "mips", "prolog", "spice", "vb", "csharp", "modula2", "a8086", "javascript", "plsql"); + +$server = 'moss.stanford.edu'; +$port = '7690'; +$noreq = "Request not sent."; +$usage = "usage: moss [-x] [-l language] [-d] [-b basefile1] ... [-b basefilen] [-m #] [-c \"string\"] file1 file2 file3 ..."; + +# +# The userid is used to authenticate your queries to the server; don't change it! +# +$userid=123456789; + +# +# Process the command line options. This is done in a non-standard +# way to allow multiple -b's. +# +$opt_l = "c"; # default language is c +$opt_m = 10; +$opt_d = 0; +$opt_x = 0; +$opt_c = ""; +$opt_n = 250; +$bindex = 0; # this becomes non-zero if we have any base files + +while (@ARGV && ($_ = $ARGV[0]) =~ /^-(.)(.*)/) { + ($first,$rest) = ($1,$2); + + shift(@ARGV); + if ($first eq "d") { + $opt_d = 1; + next; + } + if ($first eq "b") { + if($rest eq '') { + die "No argument for option -b.\n" unless @ARGV; + $rest = shift(@ARGV); + } + $opt_b[$bindex++] = $rest; + next; + } + if ($first eq "l") { + if ($rest eq '') { + die "No argument for option -l.\n" unless @ARGV; + $rest = shift(@ARGV); + } + $opt_l = $rest; + next; + } + if ($first eq "m") { + if($rest eq '') { + die "No argument for option -m.\n" unless @ARGV; + $rest = shift(@ARGV); + } + $opt_m = $rest; + next; + } + if ($first eq "c") { + if($rest eq '') { + die "No argument for option -c.\n" unless @ARGV; + $rest = shift(@ARGV); + } + $opt_c = $rest; + next; + } + if ($first eq "n") { + if($rest eq '') { + die "No argument for option -n.\n" unless @ARGV; + $rest = shift(@ARGV); + } + $opt_n = $rest; + next; + } + if ($first eq "x") { + $opt_x = 1; + next; + } + # + # Override the name of the server. This is used for testing this script. + # + if ($first eq "s") { + $server = shift(@ARGV); + next; + } + # + # Override the port. This is used for testing this script. + # + if ($first eq "p") { + $port = shift(@ARGV); + next; + } + # + # Override the userid. + # + if ($first eq "u") { + $userid = shift(@ARGV); + next; + } + die "Unrecognized option -$first. $usage\n"; +} + +# +# Check a bunch of things first to ensure that the +# script will be able to run to completion. +# + +# +# Make sure all the argument files exist and are readable. +# +print "Checking files . . . \n"; +$i = 0; +while($i < $bindex) +{ + die "Base file $opt_b[$i] does not exist. $noreq\n" unless -e "$opt_b[$i]"; + die "Base file $opt_b[$i] is not readable. $noreq\n" unless -r "$opt_b[$i]"; + die "Base file $opt_b is not a text file. $noreq\n" unless -T "$opt_b[$i]"; + $i++; +} +foreach $file (@ARGV) +{ + die "File $file does not exist. $noreq\n" unless -e "$file"; + die "File $file is not readable. $noreq\n" unless -r "$file"; + die "File $file is not a text file. $noreq\n" unless -T "$file"; +} + +if ("@ARGV" eq '') { + die "No files submitted.\n $usage"; +} +print "OK\n"; + +# +# Now the real processing begins. +# + + +$sock = new IO::Socket::INET ( + PeerAddr => $server, + PeerPort => $port, + Proto => 'tcp', + ); +die "Could not connect to server $server: $!\n" unless $sock; +$sock->autoflush(1); + +sub read_from_server { + $msg = <$sock>; + print $msg; +} + +sub upload_file { + local ($file, $id, $lang) = @_; +# +# The stat function does not seem to give correct filesizes on windows, so +# we compute the size here via brute force. +# + open(F,$file); + $size = 0; + while () { + $size += length($_); + } + close(F); + + print "Uploading $file ..."; + print $sock "file $id $lang $size $file\n"; + open(F,$file); + while () { + print $sock $_; + } + close(F); + print "done.\n"; +} + + +print $sock "moss $userid\n"; # authenticate user +print $sock "directory $opt_d\n"; +print $sock "X $opt_x\n"; +print $sock "maxmatches $opt_m\n"; +print $sock "show $opt_n\n"; + +# +# confirm that we have a supported languages +# +print $sock "language $opt_l\n"; +$msg = <$sock>; +chop($msg); +if ($msg eq "no") { + print $sock "end\n"; + die "Unrecognized language $opt_l."; +} + + +# upload any base files +$i = 0; +while($i < $bindex) { + &upload_file($opt_b[$i++],0,$opt_l); +} + +$setid = 1; +foreach $file (@ARGV) { + &upload_file($file,$setid++,$opt_l); +} + +print $sock "query 0 $opt_c\n"; +print "Query submitted. Waiting for the server's response.\n"; +&read_from_server(); +print $sock "end\n"; +close($sock); + + + + + diff --git a/resemble/resemble_analyze.tpl.php b/resemble/resemble_analyze.tpl.php new file mode 100644 index 0000000..57336df --- /dev/null +++ b/resemble/resemble_analyze.tpl.php @@ -0,0 +1,15 @@ +
    +
    + + + + + + + + + + + +
    + diff --git a/resemble/resemble_analyze_cmd.php b/resemble/resemble_analyze_cmd.php new file mode 100644 index 0000000..28d528f --- /dev/null +++ b/resemble/resemble_analyze_cmd.php @@ -0,0 +1,127 @@ +get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); +} + +if (!$programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); +} + +require_login($course->id, true, $cm); + +$context = context_module::instance($cm->id); +require_capability('mod/programming:updateresemble', $context); + +/// Print page content +if ($group != 0) { + $users = get_group_users($group); +} else { + if ($usergrps = groups_get_all_groups($course->id, $USER->id)) { + foreach ($usergrps as $ug) { + $users = array_merge($users, get_group_users($ug->id)); + } + } else { + $users = False; + } +} + +$sql = "SELECT * FROM {programming_submits} WHERE programmingid={$programming->id}"; +if (is_array($users)) { + $sql .= ' AND userid IN (' . implode(',', array_keys($users)) . ')'; +} +$sql .= ' ORDER BY timemodified DESC'; +$submits = $DB->get_records_sql($sql); + +$users = array(); +$latestsubmits = array(); +if (is_array($submits)) { + foreach ($submits as $submit) { + if (in_array($submit->userid, $users)) + continue; + $users[] = $submit->userid; + $latestsubmits[] = $submit; + } +} +$sql = 'SELECT * FROM {user} WHERE id IN (' . implode(',', $users) . ')'; +$users = $DB->get_records_sql($sql); + +// create dir +$dirname = $CFG->dataroot . '/temp'; +if (!file_exists($dirname)) { + mkdir($dirname, 0777) or ( 'Failed to create dir'); +} +$dirname .= '/programming'; +if (!file_exists($dirname)) { + mkdir($dirname, 0777) or ( 'Failed to create dir'); +} +$dirname .= '/' . $programming->id; +if (file_exists($dirname)) { + if (is_dir($dirname)) { + fulldelete($dirname) or error('Failed to remove dir contents'); + //rmdir($dirname) or error('Failed to remove dir'); + } else { + unlink($dirname) or error('Failed to delete file'); + } +} +mkdir($dirname, 0700) or error('Failed to create dir'); + +$files = array(); +// write files +$exts = array('.txt', '.c', '.cxx', '.java', '.java', '.pas', '.py', '.cs'); +foreach ($latestsubmits as $submit) { + $ext = $exts[$submit->language]; + $filename = "{$dirname}/{$submit->userid}-{$submit->id}{$ext}"; + $files[] = $filename; + $f = fopen($filename, 'w'); + fwrite($f, $submit->code); + fwrite($f, "\r\n"); + fclose($f); +} +// echo "dir is $dirname\n"; + +$cwd = getcwd(); +$cmd = "/usr/bin/perl $cwd/moss.pl -u {$CFG->programming_moss_userid} *"; +// echo "$cmd\n"; flush(); + +chdir($dirname); +$ofile = popen($cmd, 'r'); +chdir($cwd); + +$contents = ''; +if ($ofile) { + while (!feof($ofile)) { + $read = fread($ofile, 1024); + $contents .= $read; + echo $read; + } + pclose($ofile); +} +$lastline = substr($contents, strrpos($contents, "\n", -3)); + +preg_match('/(http:[\.\/a-z0-9]+)/', $lastline, $matches); +$url = $matches[1]; +echo "Result: $url\n"; + +// remove temp +fulldelete($dirname); + +parse_result($programming->id, $url, $max, $lowest); +?> diff --git a/resemble/resemble_analyze_lib.php b/resemble/resemble_analyze_lib.php new file mode 100644 index 0000000..b6a04c0 --- /dev/null +++ b/resemble/resemble_analyze_lib.php @@ -0,0 +1,118 @@ +/', $line)) { + $s = 1; + $c = 0; + } + break; + case 1: + if (preg_match('/^(\d*)?-(\d*)\.\w* \((\d*)%\)<\/A>/', $line, $m)) { + $resemble = new object; + $resemble->programmingid = $programmingid; + + $resemble->submitid1 = $m[3]; + $resemble->percent1 = $m[4]; + + $s = 2; + } + break; + case 2: + if (preg_match('/(\d*)?-(\d*)\.\w* \((\d*)%\)<\/A>/', $line, $m)) { + $resemble->submitid2 = $m[3]; + $resemble->percent2 = $m[4]; + $s = 3; + } + break; + case 3: + if (preg_match('/(\d+)/', $line, $m)) { + $resemble->matchedcount = $m[1]; + if ($resemble->percent1 > $lowest or $resemble->percent2 > $lowest) { + $resemble->matchedlines = parse_lines($index_file.'/match'.$c.'-top.html'); + if (!$DB->insert_record('programming_resemble', $resemble)) { + printf("Failed to insert record.\n"); + } + } + $c ++; + $s = 1; + } + break; + } + } +} + +function parse_lines($topfile) { + $lines = fetch_by_curl($topfile); + $s = 0; + $c = 0; + $result = ''; + + foreach($lines as $line) { + $m = array(); + switch ($s) { + case 0: + if (preg_match('/^]*>(\d+-\d+)<\/A>/', $line, $m)) { + $s = 1; + if ($result != '') $result .= ';'; + $result .= $m[1].','; + } + break; + case 1: + if (preg_match('/^]*>(\d+-\d+)<\/A>/', $line, $m)) { + $s = 0; + $result .= $m[1]; + } + break; + } + } + return $result; +} + +function parse_result($programmingid, $url, $max = 0, $lowest = 0) { + global $CFG, $DB, $moss_url; + global $curl; + + // delete old moss result + $DB->delete_records('programming_resemble', array('programmingid' => $programmingid)); + + $curl = curl_init(); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); + if (isset($CFG->proxyhost) && isset($CFG->proxyport) && ($CFG->proxyport > 0)) { + curl_setopt($curl, CURLOPT_PROXY, $CFG->proxyhost); + curl_setopt($curl, CURLOPT_PROXYPORT, $CFG->proxyport); + if (isset($CFG->proxyuser) && isset($CFG->proxypass)) { + curl_setopt($curl, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypass); + } + } + + parse_index($programmingid, $url, $max, $lowest); + + curl_close($curl); +} + +function fetch_by_curl($url) { + global $CFG; + global $curl; + + echo "Fetching $url\n"; flush(); + curl_setopt($curl, CURLOPT_URL, $url); + $ret = curl_exec($curl); + + return explode("\n", $ret); +} + +?> diff --git a/resemble/resemble_compare.tpl.php b/resemble/resemble_compare.tpl.php new file mode 100644 index 0000000..c3dab55 --- /dev/null +++ b/resemble/resemble_compare.tpl.php @@ -0,0 +1,90 @@ +set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + +/// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('resemble', 'resemble-compare', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + +/// Print page content +?> + + + + + + + + +
    + user_picture($user1, array('courseid' => $course->id)); ?> + + timemodified); ?> + user_picture($user2, array('courseid' => $course->id)); ?> + + timemodified); ?>
    + +
    +
    + '; + } else { + echo ''; + } + $line = htmlspecialchars($line); + $line = str_replace(array(' ', "\r"), array(' ', ''), $line); + echo $line; + echo '
    '."\n"; + } + ?> +
    + +
    + '; + } else { + echo ''; + } + $line = htmlspecialchars($line); + $line = str_replace(array(' ', "\r"), array(' ', ''), $line); + echo $line; + echo '
    '."\n"; + } + ?> +
    +
    + + +
    + + + + + + + + +
    + + + + +
    +
    + +footer($course); +?> diff --git a/resemble/resemble_edit.tpl.php b/resemble/resemble_edit.tpl.php new file mode 100644 index 0000000..a651f86 --- /dev/null +++ b/resemble/resemble_edit.tpl.php @@ -0,0 +1,113 @@ +set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + +/// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('resemble', 'resemble-edit', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); +?> +url, 'page'); + echo $OUTPUT->render($pagingbar); +?> +
    + + + + + + + + + + + + + + + + +flag) { + case PROGRAMMING_RESEMBLE_WARNED: + $styleclass = $styleclass1 = $styleclass2 = 'warned cell'; + break; + case PROGRAMMING_RESEMBLE_CONFIRMED: + $styleclass = $styleclass1 = $styleclass2 = 'confirmed cell'; + break; + case PROGRAMMING_RESEMBLE_FLAG1: + $styleclass = 'confirmed cell'; + $styleclass1 = 'confirmed cell'; + $styleclass2 = 'cell'; + break; + case PROGRAMMING_RESEMBLE_FLAG2: + $styleclass = 'confirmed cell'; + $styleclass1 = 'cell'; + $styleclass2 = 'confirmed cell'; + break; + case PROGRAMMING_RESEMBLE_FLAG3: + $styleclass = $styleclass1 = $styleclass2 = 'flag3 cell'; + break; + default: + $styleclass = $styleclass1 = $styleclass2 = 'cell'; + } +?> + + + + + + + + + + + + + + + + +
    + user_picture($users[$r->userid1], array('courseid' => $course->id)); ?> + + action_link(new moodle_url('/user/view.php', array('id' => $r->userid1, 'course' => $course->id)), fullname($users[$r->userid1])); ?> + + userid1]->idnumber; ?> + + action_link(new moodle_url('/mod/programming/result.php', array('id' => $cm->id, 'submitid' => $r->submitid1)), $submits[$r->submitid1]->judgeresult); ?> + percent1; ?> + user_picture($users[$r->userid2], array('courseid' => $course->id)); ?> + + action_link(new moodle_url('/user/view.php', array('id' => $r->userid2, 'course' => $course->id)), fullname($users[$r->userid2])); ?> + + userid2]->idnumber; ?> + + action_link(new moodle_url('/mod/programming/result.php', array('id' => $cm->id, 'submitid' => $r->submitid2)), $submits[$r->submitid2]->judgeresult); ?> + percent2; ?> + action_link(new moodle_url('/mod/programming/resemble/compare.php', array('id' => $cm->id, 'rid' => $r->id, 'page' => $page, 'perpage' => $perpage)), $r->matchedcount); ?> +
    + +
    + + + + + + + +
    +
    +footer($course); diff --git a/resemble/view.php b/resemble/view.php new file mode 100644 index 0000000..7b81017 --- /dev/null +++ b/resemble/view.php @@ -0,0 +1,143 @@ + $id, 'format' => $format); + $PAGE->set_url('/mod/programming/resemble/view.php', $params); + + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + + $context = context_module::instance($cm->id); + + require_capability('mod/programming:viewresemble', $context); + + $sql = "SELECT re.*, sa.userid AS userid1, sb.userid AS userid2 + FROM {programming_resemble} AS re, + {programming_submits} AS sa, + {programming_submits} AS sb + WHERE re.programmingid={$programming->id} + AND re.flag > 0 + AND sa.programmingid={$programming->id} + AND sb.programmingid={$programming->id} + AND re.submitid1 = sa.id + AND re.submitid2 = sb.id + AND (sa.userid = $USER->id OR sb.userid = $USER->id) + ORDER BY re.id"; + $resemble = $DB->get_records_sql($sql); + if (!is_array($resemble)) $resemble = array(); + + $uids = array(); + foreach($resemble as $r) { + $uids[] = $r->userid1; + $uids[] = $r->userid2; + } + if (!empty($uids)) { + $users = $DB->get_records_select('user', 'id IN ('.implode($uids, ',').')'); + } + + /// Print page content + if ($format == 'json') { + require_once('../lib/JSON.php'); + $data = array(array_keys($resemble), array_values($resemble), array_keys($users), array_values($users)); + $json = new Services_JSON(); + echo $json->encode($data); + } else { + + /// Print the page header + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + + /// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('resemble', 'resemble-view', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + + if (is_array($resemble) && count($resemble)) { + $mediumdegree = get_string('mediumsimilitude', 'programming'); + $highdegree = get_string('highsimilitude', 'programming'); + + echo $OUTPUT->box_start('resemble-list'); + + // resemble-list + $table = new html_table(); + $table->head = array( + get_string('similitudedegree', 'programming'), + get_string('program1', 'programming'), + get_string('percent1', 'programming'), + get_string('program2', 'programming'), + get_string('percent2', 'programming'), + get_string('matchedlines', 'programming') + ); + $table->data = array(); + + foreach ($resemble as $r) { + switch($r->flag) { + case PROGRAMMING_RESEMBLE_WARNED: + $styleclass = $styleclass1 = $styleclass2 = 'warned'; + $degree = $mediumdegree; + break; + case PROGRAMMING_RESEMBLE_CONFIRMED: + $styleclass = $styleclass1 = $styleclass2 = 'confirmed'; + $degree = $highdegree; + break; + case PROGRAMMING_RESEMBLE_FLAG1: + $styleclass = 'confirmed'; + $styleclass1 = 'confirmed'; + $styleclass2 = ''; + $degree = $highdegree; + break; + case PROGRAMMING_RESEMBLE_FLAG2: + $styleclass = 'confirmed'; + $styleclass1 = ''; + $styleclass2 = 'confirmed'; + $degree = $highdegree; + break; + case PROGRAMMING_RESEMBLE_FLAG3: + $styleclass = $styleclass1 = $styleclass2 = 'flag3'; + $degree = $highdegree; + break; + default: + $styleclass = ''; + } + + $url1 = new moodle_url('/user/view.php', array('id' => $r->userid1, 'course' => $course->id)); + $fullname1 = fullname($users[$r->userid1]); + $url2 = new moodle_url('/user/view.php', array('id' => $r->userid2, 'course' => $course->id)); + $fullname2 = fullname($users[$r->userid2]); + $urlcmp = new moodle_url('/mod/programming/resemble/compare.php', array('id' => $cm->id, 'rid' => $r->id)); + $table->data[] = array( + html_writer::tag('span', $degree, array('class' => $styleclass)), + html_writer::tag('span', $OUTPUT->user_picture($users[$r->userid1]).$OUTPUT->action_link($url1, $fullname1, null, array('title' => $fullname1)), array('class' => $styleclass1)), + html_writer::tag('span', $r->percent1, array('class' => $styleclass1)), + html_writer::tag('span', $OUTPUT->user_picture($users[$r->userid2]).$OUTPUT->action_link($url2, $fullname2, null, array('title' => $fullname2)), array('class' => $styleclass2)), + html_writer::tag('span', $r->percent2, array('class' => $styleclass2)), + html_writer::tag('span', $OUTPUT->action_link($urlcmp, $r->matchedcount), array('class' => $styleclass)) ); + } + + echo html_writer::table($table); + echo $OUTPUT->box_end(); + + } else { + echo html_writer::tag('p', get_string('noresembleinfo', 'programming')); + } + + /// Finish the page + echo $OUTPUT->footer($course); + } diff --git a/result.php b/result.php new file mode 100644 index 0000000..d24e1e0 --- /dev/null +++ b/result.php @@ -0,0 +1,233 @@ + $id); + if ($submitid) { + $params['submitid'] = $submitid; + } + $PAGE->set_url('/mod/programming/result.php', $params); + + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + require_capability('mod/programming:viewdetailresult', $context); + + if (!$submitid) { + // get the latest submitid of current user + $r = $DB->get_record('programming_result', array('programmingid' => $programming->id, 'userid' => $USER->id)); + if (!empty($r)) $submitid = $r->latestsubmitid; + } + $submit = $DB->get_record('programming_submits', array('id' => $submitid)); + // Check is the user view result of others + if (!empty($submit) && $submit->userid != $USER->id) { + require_capability('mod/programming:viewotherresult', $context); + } + + $viewhiddentestcase = has_capability('mod/programming:viewhiddentestcase', $context); + + + // get title of the page + if ($submit && $submit->userid != $USER->id) { + $u = $DB->get_record('user', array('id' => $submit->userid)); + $title = get_string('viewtestresultof', 'programming', fullname($u)); + $pagename = $title; + } else { + $title = get_string('viewtestresult', 'programming'); + $pagename = get_string('result', 'programming'); + } + + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + $PAGE->requires->css('/mod/programming/styles.css'); + echo $OUTPUT->header(); + +/// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('result', null, $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + +/// Print page content + echo html_writer::tag('h2', $programming->name); + echo html_writer::tag('h3', $title); + if (empty($submit)) { + echo '

    '.get_string('cannotfindyoursubmit', 'programming').'

    '; + } else { + echo '

    '.$currentstate = get_string('currentstatus', 'programming', programming_get_submit_status_desc($submit)).'

    '; + + if (!empty($submit->compilemessage)) { + echo html_writer::tag('h3', get_string('compilemessage', 'programming')); + echo $OUTPUT->box_start('compilemessage'); + echo programming_format_compile_message($submit->compilemessage); + echo $OUTPUT->box_end(); + } + + if (!empty($submit->judgeresult)) { + echo html_writer::tag('h3', get_string('judgeresult', 'programming')); + $results = $DB->get_records('programming_test_results', array('submitid' => $submit->id), 'testid'); + + if (!empty($results)) { + if ($programming->showmode == PROGRAMMING_SHOWMODE_NORMAL || has_capability('mod/programming:viewdetailresultincontest', $context)) { + $tests = $DB->get_records('programming_tests', array('programmingid' => $programming->id), 'id'); + uasort($results, 'cmp_results_by_test_seq'); + echo html_writer::start_tag('div', array('id' => 'test-result-detail')); + echo html_writer::tag('p', get_string('testresult', 'programming', programming_get_test_results_desc($submit, $results))); + echo html_writer::tag('p', get_string('iostripped', 'programming', '1')); + print_test_result_table(); + echo html_writer::end_tag('div'); + } else { + echo html_writer::tag('p', programming_contest_get_judgeresult($results)); + } + } + } + + $strviewprogram = get_string('viewprogram', 'programming'); + $viewprogramurl = 'history.php?id='.$id; + if ($submitid) $viewprogramurl .= '&userid='.$submit->userid; + echo "

    $strviewprogram

    "; + } + +/// Finish the page + echo $OUTPUT->footer($course); + +function print_test_result_table() +{ + global $CFG, $OUTPUT, $PAGE; + global $tests, $results; + global $cm, $programming, $viewhiddentestcase, $params; + + $strsecuretestcase = get_string('securetestcase', 'programming'); + $strshowasplaintext = get_string('showasplaintext', 'programming'); + $strdownload = get_string('download', 'programming'); + + $table = new html_table(); + $headers = array( + get_string('testcasenumber', 'programming'), + get_string('weight', 'programming'), //.$OUTPUT->help_icon('weight', 'programming'), + get_string('timelimit', 'programming'), //.helpbutton('timelimit', 'timelimit', 'programming', true, false, '', true), + get_string('memlimit', 'programming'), //.helpbutton('memlimit', 'memlimit', 'programming', true, false, '', true), + get_string('input', 'programming'), //.helpbutton('input', 'input', 'programming', true, false, '', true), + get_string('expectedoutput', 'programming'), //.helpbutton('expectedoutput', 'expectedoutput', 'programming', true, false, '', true), + get_string('output', 'programming'), //.helpbutton('output', 'output', 'programming', true, false, '', true), + get_string('errormessage', 'programming'), //.helpbutton('stderr', 'stderr', 'programming', true, false, '', true), + get_string('timeused', 'programming'), //.helpbutton('timeused', 'timeused', 'programming', true, false, '', true), + get_string('memused', 'programming'), //.helpbutton('memused', 'memused', 'programming', true, false, '', true), + get_string('exitcode', 'programming'), //.helpbutton('exitcode', 'exitcode', 'programming', true, false, '', true), + get_string('passed', 'programming'), + get_string('judgeresult', 'programming')); + $table->head = $headers; + + $table->attributes = array('id' => 'test-result-detail-table', 'class' => 'generaltable generalbox'); + $table->cellpadding = 3; + $table->cellspacing = 1; + $table->tablealign = 'center'; + $table->colclasses[4] = 'programming-io'; + $table->colclasses[5] = 'programming-io'; + $table->colclasses[6] = 'programming-io'; + $table->colclasses[7] = 'programming-io'; + + if (!is_array($results)) $results = array(); + $i = 0; $id = 0; + $rowclazz = array(); + foreach ($results as $result) { + $rowclazz[] = $result->passed ? 'passed' : 'notpassed'; + $data = array(); + $data[] = $tests[$result->testid]->seq; + $data[] = $tests[$result->testid]->weight; + $data[] = programming_format_timelimit($tests[$result->testid]->timelimit); + $data[] = programming_format_memlimit($tests[$result->testid]->memlimit); + $downloadurl = new moodle_url($CFG->wwwroot.'/mod/programming/testcase/download_io.php', array('id' => $cm->id, 'test' => $result->testid)); + if (true||$viewhiddentestcase || programming_testcase_visible($tests, $result, true, $programming->timediscount <= time())) { + // input + $downloadurl->params(array('type' => 'in', 'download' => 0)); + $action = new popup_action('click', $downloadurl, '_blank', array('height' => 300, 'width' => 400)); + $html = $OUTPUT->action_link($downloadurl, $strshowasplaintext, $action); + $html.= ' '; + $downloadurl->remove_params('download'); + $html.= $OUTPUT->action_link($downloadurl, $strdownload); + $html.= programming_format_io($tests[$result->testid]->input, true); + $data[] = $html; + + // expected output + $downloadurl->params(array('type' => 'out', 'download' => 0)); + $action = new popup_action('click', $downloadurl, '_blank', array('height' => 300, 'width' => 400)); + $html = $OUTPUT->action_link($downloadurl, $strshowasplaintext, $action); + $html.= ' '; + $downloadurl->remove_params('download'); + $html.= $OUTPUT->action_link($downloadurl, $strdownload); + $html.= programming_format_io($tests[$result->testid]->output, true); + $data[] = $html; + + // output + if (!empty($result->output)) { + $downloadurl->params(array('submit' => $result->submitid, 'type' => 'out', 'download' => 0)); + $action = new popup_action('click', $downloadurl, '_blank', array('height' => 300, 'width' => 400)); + $html = $OUTPUT->action_link($downloadurl, $strshowasplaintext, $action); + + $html.= ' '; + $downloadurl->remove_params('download'); + $html.= $OUTPUT->action_link($downloadurl, $strdownload); + $html.= programming_format_io($result->output, false); + $data[] = $html; + } else { + $data[] = get_string('noresult', 'programming'); + } + + // error message + if (!empty($result->stderr)) { + $downloadurl->params(array('submit' => $result->submitid, 'type' => 'err', 'download' => 0)); + $action = new popup_action('click', $downloadurl, '_blank', array('height' => 300, 'width' => 400)); + $html = $OUTPUT->action_link($downloadurl, $strshowasplaintext, $action); + $html.= ' '; + $downloadurl->remove_params('download'); + $html.= $OUTPUT->action_link($downloadurl, $strdownload); + $html.= programming_format_io($result->stderr, false); + $data[] = $html; + } else { + $data[] = get_string('n/a', 'programming'); + } + } else { + $data[] = $strsecuretestcase; $data[] = $strsecuretestcase; + $data[] = $strsecuretestcase; $data[] = $strsecuretestcase; + } + + $data[] = round($result->timeused, 3); + $data[] = $result->memused; + + if ($viewhiddentestcase || programming_testcase_visible($tests, $results)) { + $data[] = $result->exitcode; + } else { + $data[] = $strsecuretestcase; + } + + $data[] = get_string($result->passed ? 'yes' : 'no'); + $data[] = programming_get_judgeresult($result); + $table->data[] = $data; + } + + $table->rowclasses = $rowclazz; + echo html_writer::table($table); +} + +function cmp_results_by_test_seq($a, $b) { + global $tests; + return $tests[$a->testid]->seq - $tests[$b->testid]->seq; +} + +?> diff --git a/settings.php b/settings.php new file mode 100644 index 0000000..ea26787 --- /dev/null +++ b/settings.php @@ -0,0 +1,11 @@ +fulltree) { + + $settings->add(new admin_setting_configtext('programming_ojip', get_string('programming_ojip', 'programming'), + get_string('configojip', 'programming'), '')); + $settings->add(new admin_setting_configtext('programming_moss_userid', get_string('programming_moss_userid', 'programming'), + get_string('programming_moss_useridinfo', 'programming'), '')); +} diff --git a/styles.css b/styles.css new file mode 100644 index 0000000..77d2e55 --- /dev/null +++ b/styles.css @@ -0,0 +1,506 @@ +.path-mod-programming .userpicture { + vertical-align: middle; +} + +.path-mod-programming #region-main .region-content { + font-size: 14px; +} + +.path-mod-programming #region-main .region-content h2 { + text-align: center; + padding: 4px; +} + +.path-mod-programming #region-main .region-content h3 { + text-align: center; +} + +.path-mod-programming #region-main .region-content .generaltable { + margin-left: auto; + margin-right: auto; +} + +.path-mod-programming #region-main .region-content .cell { + padding: 3px; + vertical-align: middle; +} + +.path-mod-programming #region-main .region-content .description, +.path-mod-programming #region-main .region-content form .felement { + text-align: left; +} + +.path-mod-programming .buttons { + margin: 1em; + text-align: center; +} + +.path-mod-programming .filters dl { + font-size: 12px; +} + +.path-mod-programming .filters dl { + margin: 0 0 5px; +} + +.path-mod-programming .filters dt { + float: left; + width: 80px; + font-weight: bold; + text-align: right; + line-height: 25px; +} + +.path-mod-programming .filters dd { + float: none; + height: auto; + margin: 0 0 0 80px; + padding: 0; + text-align: left; + display: block; +} + +.path-mod-programming .filters dd span { + line-height: 23px; + margin-left: 10px; +} + +.path-mod-programming .filters a { + padding: 1px 2px; + text-decoration: none; + white-space: nowrap; + overflow: hidden; +} + +.path-mod-programming .filters a.here, +.path-mod-programming .filters a:hover, +.path-mod-programming .filters a:active { + background-color: #4598D2; + color: white; +} + +#page-mod-programming-view #region-main .region-content h3 { text-align: left; } +.path-mod-programming #intro { text-align: left; padding: 0em 1em 0em 1em; } +.path-mod-programming #datafile { text-align: left; padding: 0em 1em 0em 1em; } +.path-mod-programming #presetcode { text-align: left; padding: 0em 1em 0em 1em; } +.path-mod-programming #presetcode pre { background-color: #eeeeee; padding: 0em 0.5em 0em 2.5em; } +.path-mod-programming #testcase-table { padding: 1em; } +.path-mod-programming #time-table th { text-align: right } +.path-mod-programming #time-table td { text-align: left } + +.path-mod-programming #submitagainconfirm, +.path-mod-programming #submitagainconfirm p { + text-align: center; +} + +.path-mod-programming .compilemessage { + padding: 1px; + margin: 0 auto; + font-family: "Consolas","Courier New",Courier,mono,serif; + font-weight: bold; + text-align: left; + background: #F0A0A0; +} +.path-mod-programming .compilemessage ol { + list-style-type: none; +} +.path-mod-programming .compilemessage li, .compilemessage li.warning, +.path-mod-programming .compilemessage li.normal, .compilemessage li.error { + font-family: "Consolas","Courier New",Courier,mono,serif; + font-style: normal; + font-weight: bold; +} +.path-mod-programming .compilemessage li.warning { + color: black; +} +.path-mod-programming .compilemessage li.normal { + color: blue; +} +.path-mod-programming .compilemessage li.error { + color: #800000; +} + +.path-mod-programming #test-result-detail .passed, +.path-mod-programming #test-result-detail .passed .cell { + background-color: #A0EEA0; /* light green */ +} +.path-mod-programming #test-result-detail .notpassed, +.path-mod-programming #test-result-detail .notpassed .cell { + background-color: #F0A0A0; /* light red */ +} + +#page-mod-programming-history td { vertical-align: top; } +#page-mod-programming-history #submitlist { + display: block; + width: 14em; +} +#page-mod-programming-history #submitlist table { + margin: 0.5em 0; +} +#page-mod-programming-history #submitlist table th, +#page-mod-programming-history #submitlist table td { + padding: 1px; +} + +.path-mod-programming #codeview { + display: block; + width: 46em; + height: 29em; + text-align: left; + overflow: scroll; +} + +.path-mod-programming .diff { + margin: 0 auto; + width: 52em; +} + +.path-mod-programming .diff th { + color: #666666; + font-weight: normal; + padding: 0 0.6em; + text-align: right; + width: 2em; +} + +.path-mod-programming .diff td { + font-family: "Consolas","Courier New",Courier,mono,serif; +} + +.path-mod-programming .diff .added { + background-color: #99FF99; + border-color: #33AA33; + border-style: solid; + border-width: 0 1px; +} + +.path-mod-programming .diff .deleted { + background-color: #FF8888; + border-color: #AA3333; + border-style: solid; + border-width: 0 1px; +} + +.path-mod-programming .diff .first { + border-top-width: 1px; +} + +.path-mod-programming .diff .last { + border-bottom-width: 1px; +} + +.path-mod-programming .diff .added-changed { + background-color: #DDF8CC; + border-color: #33AA33; + border-style: solid; + border-width: 0 1px; +} + +.path-mod-programming .diff .deleted-changed { + background-color: #FFD8D8; + border-color: #AA3333; + border-style: solid; + border-width: 0 1px; +} + +.path-mod-programming .resemble-compare-programs { + height: 30em; +} +.path-mod-programming .resemble-compare-programs div { + overflow: scroll; + height: 30em; + max-width: 480px; + float: left; +} + +.path-mod-programming .code { + font-family: monospace; + background-color: #e7e7e7; +} +.path-mod-programming .match1 { color: Red; } +.path-mod-programming .match2 { color: BlueViolet; } +.path-mod-programming .match3 { color: Brown; } +.path-mod-programming .match4 { color: BurlyWood; } +.path-mod-programming .match5 { color: CadetBlue; } +.path-mod-programming .match6 { color: DarkGoldenRod; } +.path-mod-programming .match7 { color: Chocolate; } +.path-mod-programming .match8 { color: DarkGreen; } + +.path-mod-programming .resemble-list .cell { text-align: center; } +.path-mod-programming .resemble-list .warned { color: orange; } +.path-mod-programming .resemble-list .confirmed { color: red; } +.path-mod-programming .resemble-list .flag3 { color: #888888; } + +.path-mod-programming-reports table { + margin: 0 auto; + text-align: center; + width: 100%; +} + +.path-mod-programming-reports table .fullname { + text-align: left; +} + +.path-mod-programming .chart { + height: 300px; + width: 400px; + margin: 10px auto; +} + +.path-mod-programming .noticebox { + margin: 0 auto; + padding: 5px; + text-align: center; + background-color: #FFAAAA; + width: 60%; +} + +.path-mod-programming td.programming-io a { + font-size: 9pt; +} + +.path-mod-programming td.programming-io div { + vertical-align: top; + padding: 0px 5px 0px 0px; + width: 10em; + height: 10em; + overflow: auto; +} + +.path-mod-programming td.programming-io ol { + text-align: left; + margin-top: 0; + margin-right: 0; + margin-bottom: 0; + padding: 0 0 0 auto; + overflow: visible; +} + +.path-mod-programming td.programming-io li { + font-family: "Consolas","Courier New",Courier,mono,serif; + margin: 0; + padding: 0; + overflow: visible; +} + +.path-mod-programming td.programming-io span { + background-color: #D3D3D3; + margin: 0; + padding: 0; + white-space: nowrap; +} + +.hl-default { + color: Black; +} +.hl-code { + color: Gray; +} +.hl-brackets { + color: Olive; +} +.hl-comment { + color: Orange; +} +.hl-quotes { + color: Darkred; +} +.hl-string { + color: Red; +} +.hl-identifier { + color: Blue; +} +.hl-builtin { + color: Teal; +} +.hl-reserved { + color: Green; +} +.hl-inlinedoc { + color: Blue; +} +.hl-var { + color: Darkblue; +} +.hl-url { + color: Blue; +} +.hl-special { + color: Navy; +} +.hl-number { + color: Maroon; +} +.hl-inlinetags { + color: Blue; +} +.hl-main { + background-color: White; +} +.hl-gutter { + background-color: #999999; + color: White +} +.hl-table { + font-family: "Consolas","Courier New",Courier,mono,serif; + font-size: 12px; + border: solid 1px Lightgrey; +} +.dp-highlighter li { + font-family: "Consolas","Courier New",Courier,mono,serif; +} + +.default_input +{ + border:1px solid #666666; + height:18px; + font-size:12px; +} +.default_input2 +{ + border:1px solid #666666; + height:18px; + font-size:12px; +} +.nowrite_input +{ + border:1px solid #849EB5; + height:18px; + font-size:12px; + background-color:#EBEAE7; + color: #9E9A9E; +} +.default_list +{ + font-size:12px; + border:1px solid #849EB5; +} +.default_textarea +{ + font-size:12px; + border:1px solid #849EB5; +} +.nowrite_textarea +{ + border:1px solid #849EB5; + font-size:12px; + background-color:#EBEAE7; + color: #9E9A9E; +} +.wordtd5 { + font-size: 12px; + text-align: center; + vertical-align:top; + padding-top: 6px; + padding-right: 5px; + padding-bottom: 3px; + padding-left: 5px; + background-color: #b8c4f4; +} +.wordtd { + font-size: 12px; + text-align: left; + vertical-align:top; + padding-top: 6px; + padding-right: 5px; + padding-bottom: 3px; + padding-left: 5px; + background-color: #b8c4f4; +} +.wordtd_1 { + font-size: 12px; + vertical-align:top; + padding-top: 6px; + padding-right: 5px; + padding-bottom: 3px; + padding-left: 5px; + background-color: #516CD6; + color:#fff; +} +.wordtd_2{ + font-size: 12px; + text-align: right; + vertical-align:top; + padding-top: 6px; + padding-right: 5px; + padding-bottom: 3px; + padding-left: 5px; + background-color: #64BDF9; +} +.wordtd_3{ + font-size: 12px; + text-align: right; + vertical-align:top; + padding-top: 6px; + padding-right: 5px; + padding-bottom: 3px; + padding-left: 5px; + background-color: #F1DD34; +} +.inputtd +{ + font-size:12px; + vertical-align:top; + padding-top: 3px; + padding-right: 3px; + padding-bottom: 3px; + padding-left: 3px; +} +.inputtd2 +{ + text-align: center; + font-size:12px; + vertical-align:top; + padding-top: 3px; + padding-right: 3px; + padding-bottom: 3px; + padding-left: 3px; +} +.tablebg +{ + font-size:12px; +} +.tb{ + border-collapse: collapse; + border: 1px outset #999999; + background-color: #FFFFFF; +} +.td2{line-height:22px; text-align:center; background-color:#F6F6F6;} +.td3{background-color:#B8D3F4; text-align:center; line-height:20px;} +.td4{background-color:#F6F6F6;line-height:20px;} +.td5{border:#000000 solid; + border-right-width:0px; + border-left-width:0px; + border-top-width:0px; + border-bottom-width:1px;} +.tb td{ +font-size: 12px; +border: 2px groove #ffffff; +} +.noborder { + border: none; +} +.button { + border: 1px ridge #ffffff; + line-height:18px; + height: 40px; + width: 45px; + padding-top: 0px; + background:#CBDAF7; + color:#000000; + font-size: 9pt; +} +.textarea { + font-family: Arial, Helvetica, sans-serif, "??"; + font-size: 9pt; + color: #000000; + border-bottom-width: 1px; + border-top-style: none; + border-right-style: none; + border-bottom-style: solid; + border-left-style: none; + border-bottom-color: #000000; + background-color:transparent; + text-align: left +} \ No newline at end of file diff --git a/submit.php b/submit.php new file mode 100644 index 0000000..64b62f0 --- /dev/null +++ b/submit.php @@ -0,0 +1,227 @@ +sessioncookie; + $default_language = 0; + if (isset($_COOKIE[$cookiename])) { + $default_language = $_COOKIE[$cookiename]; + } + if (!isset($language)) $language = $default_language; + + $params = array('id' => $id); + $PAGE->set_url('/mod/programming/submit.php', $params); + $PAGE->requires->css('/mod/programming/codemirror/lib/codemirror.css'); + // $PAGE->requires->css('/mod/programming/codemirror/doc/docs.css'); //把这个注释掉,CSS就不会错位了。 + $PAGE->requires->css('/mod/programming/codemirror/theme/eclipse.css'); +// $PAGE->requires->js('/mod/programming/codemirror/lib/codemirror.js'); +// $PAGE->requires->js('/mod/programming/codemirror/mode/clike/clike.js'); +// $PAGE->requires->js('/mod/programming/codemirror/mode/pascal/pascal.js'); +// $PAGE->requires->js('/mod/programming/codemirror/mode/python/python.js'); +// $PAGE->requires->js('/mod/programming/codemirror/mode/shell/shell.js'); +/* echo ' + + + + + +';//*/ + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + + $context = context_module::instance($cm->id); + $PAGE->set_context($context); + + require_capability('mod/programming:submitprogram', $context); + $submitatanytime = has_capability('mod/programming:submitatanytime', $context); + + $result = $DB->get_record('programming_result', array('programmingid' => $programming->id, 'userid' => $USER->id)); + $submitcount = is_object($result) ? $result->submitcount : 0; + $time = time(); + $isearly = $time < $programming->timeopen; + $islate = !$programming->allowlate && $time > $programming->timeclose; + $istoomore = $programming->attempts != 0 && $submitcount > $programming->attempts; + $allowpost = $submitatanytime || (!$isearly && !$islate && !$istoomore); + + // Check if user has passed the practice + $haspassed = false; + if ($submitcount > 0) { + $latestsubmit = $DB->get_record('programming_submits', array('id' => $result->latestsubmitid)); + $haspassed = is_object($latestsubmit) && $latestsubmit->passed; + } + + $mform = new submit_form(); + if ($mform->is_cancelled()) { + redirect(new moodle_url('view.php', array('id' => $cm->id))); + } else { + if ($allowpost && $submit = $mform->get_data()) { + $submits_count = $DB->count_records('programming_submits', array('programmingid' => $programming->id, 'userid' => $USER->id)); + if (!$submitatanytime && ($programming->attempts != 0 && $programming->attempts <= $submits_count)) { + $error = get_string('submitfailednoattempts', 'programming'); + $submit = False; + } + + if ($submit) { + $submit->userid = $USER->id; + $submit->programmingid = $programming->id; + $code = $submit->code; + if ($sourcefile = $mform->get_file_content('sourcefile')) { + $code = $sourcefile; + } + if ($programming->presetcode) { + $code = programming_submit_remove_preset($code); + } + $submit->code = trim($code); + if($submit->language==6){ + // $submit->code='import sys;import codecs;sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())'. PHP_EOL.$submit->code; + } + if ($submit->code == '') { + $error = get_string('submitfailedemptycode', 'programming'); + $submit = False; + } + + if ($submit) { + unset($submit->id); + programming_submit_add_instance($programming, $submit); + + // Send events + $ue = new stdClass(); + $ue->userid = $USER->id; + $ue->programmingid = $programming->id; + $ue->language = $submit->language; + $ue->timemodified = $submit->timemodified; + + } + } + } + } + +/// Print the page header + setcookie($cookiename, $language, time() + 3600 * 24 * 60, $CFG->sessioncookiepath); + + if (!empty($action) && is_object($submit)) { + $PAGE->requires->css('/mod/programming/js/dp/SyntaxHighlighter.css'); + $PAGE->requires->js('/mod/programming/js/dp/shCore.js'); + $PAGE->requires->js('/mod/programming/js/dp/shBrushCSharp.js'); + } + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + +/// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('submit', null, $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + +/// Print the main part of the page + echo html_writer::tag('h2', $programming->name); + echo html_writer::tag('h3', get_string('submit', 'programming').$OUTPUT->help_icon('submit', 'programming')); + + if (is_object($submit)) { + echo html_writer::tag('h1', get_string('submitsuccess', 'programming')); + echo $OUTPUT->action_link(new moodle_url('result.php', array('id' => $cm->id)), get_string('viewresults', 'programming')); + } else { + print_submit(); +//js code + echo ' + + + + + + +'; + + } + +/// Finish the page + + echo $OUTPUT->footer($course); + + +function print_submit() { + global $PAGE,$DB, $OUTPUT, $cm, $programming, $mform; + global $allowpost, $haspassed, $islate, $isearly; + if ($allowpost) { + if ($haspassed) { + echo html_writer::start_tag('div', array('id' => 'submitagainconfirm')); + echo html_writer::tag('p', get_string('youhavepassed', 'programming')); + echo html_writer::empty_tag('input', array('type' => 'button', 'id' => 'submitagain', 'name' => 'submitagain', 'value' => get_string('submitagain', 'programming'))); + $PAGE->requires->js_init_call('M.mod_programming.init_submit'); + echo html_writer::end_tag('div'); + } + + echo html_writer::start_tag('div', array('id' => 'submit')); + $mform->display(); + echo html_writer::end_tag('div'); + } + + if ($isearly) { + echo html_writer::tag('p', get_string('programmingnotopen', 'programming')); + } + + if ($islate) { + echo html_writer::tag('p', get_string('timeexceed', 'programming')); + } + +} + diff --git a/submit_form.php b/submit_form.php new file mode 100644 index 0000000..487916b --- /dev/null +++ b/submit_form.php @@ -0,0 +1,24 @@ +libdir.'/formslib.php'); + +class submit_form extends moodleform { + + function definition() { + global $CFG, $COURSE, $OUTPUT, $cm, $programming; + global $default_language, $submitfor; + $mform =& $this->_form; +//------------------------------------------------------------------------------- + $mform->addElement('hidden', 'id', $cm->id); + $mform->setType('id', PARAM_INT); + $mform->addElement('textarea', 'code', get_string('programcode', 'programming'), 'rows="20" cols="90"'); + $attributes = 'onchange ="change()"'; + + $mform->addElement('select', 'language', get_string('programminglanguage', 'programming'), programming_get_language_options($programming),$attributes); + $mform->setDefault('language', $default_language); + $mform->addElement('filepicker', 'sourcefile', get_string('sourcefile', 'programming'), null, array('maxbytes' => 65536)); + +// buttons + $this->add_action_buttons(); + } + +} diff --git a/testcase/add.php b/testcase/add.php new file mode 100644 index 0000000..1d5af87 --- /dev/null +++ b/testcase/add.php @@ -0,0 +1,81 @@ +libdir . '/weblib.php'); +require_once('../lib.php'); +require_once('form.php'); + +$id = required_param('id', PARAM_INT); // programming ID +$params = array('id' => $id); +$PAGE->set_url('/mod/programming/testcase/add.php', $params); + +if (!$cm = get_coursemodule_from_id('programming', $id,0,false,MUST_EXIST)) { + print_error('invalidcoursemodule'); +} + +if (!$course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); +} + +if (!$programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); +} + +require_login($course->id, true, $cm); +$context = context_module::instance($cm->id); +require_capability('mod/programming:edittestcase', $context); + +$mform = new testcase_form(); +if ($mform->is_cancelled()) { + redirect(new moodle_url('list.php', array('id' => $cm->id))); +} else if ($data = $mform->get_data()) { + unset($data->id); + $data->programmingid = $programming->id; + $data->seq = $DB->count_records('programming_tests', array('programmingid' => $programming->id), 'MAX(seq)') + 1; + $infile = $mform->get_file_content('inputfile'); + if (empty($infile)) { + $data->input = stripcslashes($data->input); + } else { + $data->input = $infile; + } + $outfile = $mform->get_file_content('outputfile'); + if (empty($outfile)) { + $data->output = stripcslashes($data->output); + } else { + $data->output = $outfile; + } +// $data->input = str_replace("\r\n\r\n", "", $data->input); + // $data->output = str_replace("\r\n\r\n", "", $data->output); + // $data->input = str_replace("\r\n\n", "", $data->input); + // $data->output = str_replace("\r\n\n", "", $data->output); +// $data->input = str_replace(chr(13), "", $data->input); + // $data->output = str_replace(chr(13), "", $data->output); + // $data->input = str_replace("\n\n", "\n", $data->input); + // $data->output = str_replace("\n\n", "\n", $data->output); + $data->input = rtrim($data->input); + $data->output = rtrim($data->output); +// $data->input .= "\n"; + // $data->output .= "\n"; + programming_test_add_instance($data); + + redirect(new moodle_url('list.php', array('id' => $cm->id)), get_string('testcasemodified', 'programming'), 0); +} else { + /// Print the page header + $PAGE->set_title(format_string($course->shortname) . ': ' . $programming->name) . ': ' . get_string('addtestcase', 'programming'); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + + /// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('edittest', 'testcase', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + + echo html_writer::tag('h2', $programming->name); + echo html_writer::tag('h3', get_string('addtestcase', 'programming')); + + /// Print page content + $mform->display(); + + /// Finish the page + echo $OUTPUT->footer($course); +} diff --git a/testcase/delete.php b/testcase/delete.php new file mode 100644 index 0000000..e5e5296 --- /dev/null +++ b/testcase/delete.php @@ -0,0 +1,39 @@ +set_url('/mod/programming/view.php', $params); + + if ($id) { + if (! $cm = get_coursemodule_from_id('programming', $id)) { + error('Course Module ID was incorrect'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + error('Course is misconfigured'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + error('Course module is incorrect'); + } + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + require_capability('mod/programming:edittestcase', $context); + + $DB->delete_records('programming_test_results', array('testid' => $case_id)); + $DB->delete_records('programming_tests', array('id' => $case_id)); + programming_testcase_adjust_sequence($programming->id); + redirect(new moodle_url('list.php', array('id' => $cm->id)), get_string('testcasedeleted', 'programming'), 0); diff --git a/testcase/download_io.php b/testcase/download_io.php new file mode 100644 index 0000000..ba497a9 --- /dev/null +++ b/testcase/download_io.php @@ -0,0 +1,89 @@ +set_url('/mod/programming/download_io.php', $params); + + if ($id) { + if (! $cm = get_coursemodule_from_id('programming', $id)) { + error('Course Module ID was incorrect'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + error('Course is misconfigured'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + error('Course module is incorrect'); + } + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + // Download input and output of testcase + if ($type == 'in' or ($type == 'out' and $submitid == -1)) { + if (! $test = $DB->get_record('programming_tests', array('id' => $testid))) { + error('Test ID was incorrect'); + } + programming_testcase_require_view_capability($context, $test); + $filename = sprintf('test-%d.%s', $testid, $type); + if ($type == 'in') { + $content = !empty($test->gzinput) ? bzdecompress($test->gzinput) : $test->input; + } else { + $content = !empty($test->gzoutput) ? bzdecompress($test->gzoutput) : $test->output; + } + } + // Download output and error message of user program + else if ($type == 'out' or $type == 'err') { + require_capability('mod/programming:viewdetailresult', $context); + if (! $result = $DB->get_record('programming_test_results', array('submitid' => $submitid, 'testid' => $testid))) { + error('Test ID or submit ID was incorrect.'); + } + $test = $DB->get_record('programming_tests', array('id' => $testid)); + if ($test->pub >= 0) { + require_capability('mod/programming:viewpubtestcase', $context); + } else { + require_capability('mod/programming:viewhiddentestcase', $context); + } + $submit = $DB->get_record('programming_submits', array('id' => $submitid)); + if ($submit->userid != $USER->id) { + require_capability('mod/programming:viewotherresult', $context); + } + if ($result->judgeresult == 'AC' && strlen($result->output) == 0) { + $result->output = $test->output; + } + $filename = sprintf('test-%d-%d.%s', $testid, $submitid, $type); + $content = $type == 'out' ? $result->output : $result->stderr; + } + + if ($filename && $download) { + header('Content-Type: application/octet-stream'); + header('Content-Disposition: attachment; filename="'.$filename.'"'); + } else { + header('Content-Type: text/plain'); + } + echo $content; diff --git a/testcase/edit.php b/testcase/edit.php new file mode 100644 index 0000000..d7b21b0 --- /dev/null +++ b/testcase/edit.php @@ -0,0 +1,85 @@ +libdir . '/weblib.php'); +require_once('../lib.php'); +require_once('form.php'); + +$id = required_param('id', PARAM_INT); // programming ID +$case_id = required_param('case', PARAM_INT); // testcase ID +$params = array('id' => $id, 'case' => $case_id); +$PAGE->set_url('/mod/programming/testcase/edit.php', $params); + +if (!$cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); +} + +if (!$course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); +} + +if (!$programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); +} + +require_login($course->id, true, $cm); +$context = context_module::instance($cm->id); +require_capability('mod/programming:edittestcase', $context); + +$mform = new testcase_form(); +if ($mform->is_cancelled()) { + redirect(new moodle_url('list.php', array('id' => $cm->id))); +} else if ($data = $mform->get_data()) { + $data->id = $data->case; + $data->programmingid = $programming->id; + unset($data->case); + $infile = $mform->get_file_content('inputfile'); + if (empty($infile)) { + $data->input = stripcslashes($data->input); + } else { + $data->input = $infile; + } + $outfile = $mform->get_file_content('outputfile'); + if (empty($outfile)) { + $data->output = stripcslashes($data->output); + } else { + $data->output = $outfile; + } +// $data->input = str_replace("\r\n\r\n", "", $data->input); + // $data->output = str_replace("\r\n\r\n", "", $data->output); +// $data->input = str_replace("\r\n\n", "", $data->input); + // $data->output = str_replace("\r\n\n", "", $data->output); +// $data->input = str_replace(chr(13), "", $data->input); + // $data->output = str_replace(chr(13), "", $data->output); + // $data->input = str_replace("\n\n", "\n", $data->input); + // $data->output = str_replace("\n\n", "\n", $data->output); + $data->input = rtrim($data->input); + $data->output = rtrim($data->output); +// $data->input .= "\n"; + // $data->output .= "\n"; + programming_test_update_instance($data); + + redirect(new moodle_url('list.php', array('id' => $cm->id)), get_string('testcasemodified', 'programming'), 0); +} else { + $data = $DB->get_record('programming_tests', array('id' => $case_id)); + $mform->set_data($data); + + /// Print the page header + $PAGE->set_title(format_string($course->shortname) . ': ' . $programming->name) . ': ' . get_string('edittestcase', 'programming'); + $PAGE->set_heading(format_string($course->fullname)); + $PAGE->requires->css('/mod/programming/programming.css'); + echo $OUTPUT->header(); + + /// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('edittest', 'testcase', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + + /// Print page content + echo html_writer::tag('h2', $programming->name); + echo html_writer::tag('h3', get_string('edittestcase', 'programming')); + $mform->display(); + + /// Finish the page + echo $OUTPUT->footer($course); +} diff --git a/testcase/form.php b/testcase/form.php new file mode 100644 index 0000000..85309bd --- /dev/null +++ b/testcase/form.php @@ -0,0 +1,65 @@ +libdir.'/formslib.php'); + +class testcase_form extends moodleform { + + function definition() { + global $CFG, $COURSE, $OUTPUT, $cm, $programming; + $mform =& $this->_form; + +//------------------------------------------------------------------------------- + $mform->addElement('hidden', 'id', $cm->id); + $mform->setType('id', PARAM_INT); + $mform->addElement('hidden', 'case'); + $mform->setType('case', PARAM_INT); + +// $mform->addElement('textarea', 'input', get_string('input', 'programming').$OUTPUT->help_icon('input', 'programming'), 'rows="2" cols="50"'); + $mform->addElement('filepicker', 'inputfile', get_string('usefile', 'programming')); +// $mform->addElement('textarea', 'output', get_string('output', 'programming').$OUTPUT->help_icon('output', 'programming'), 'rows="2" cols="50"'); + $mform->addElement('filepicker', 'outputfile', get_string('usefile', 'programming')); + + $mform->addElement('select', 'timelimit', get_string('timelimit', 'programming').$OUTPUT->help_icon('timelimit', 'programming'), programming_get_timelimit_options()); + $mform->setDefault('timelimit', $programming->timelimit); + + $mform->addElement('select', 'memlimit', get_string('memlimit', 'programming').$OUTPUT->help_icon('memlimit', 'programming'), programming_get_memlimit_options()); + $mform->setDefault('memlimit', $programming->memlimit); + + $mform->addElement('select', 'nproc', get_string('extraproc', 'programming').$OUTPUT->help_icon('nproc', 'programming'), programming_get_nproc_options()); + $mform->setDefault('nproc', $programming->nproc); + + $mform->addElement('select', 'weight', get_string('weight', 'programming').$OUTPUT->help_icon('weight', 'programming'), programming_get_weight_options()); + $mform->setDefault('weight', 1); + + $mform->addElement('select', 'pub', get_string('testcasepub', 'programming').$OUTPUT->help_icon('testcasepub', 'programming'), programming_testcase_pub_options()); + $mform->setDefault('pub',-1); + +// $mform->addElement('textarea', 'memo', get_string('memo', 'programming'), 'rows="2" cols="50"'); + +// buttons + $this->add_action_buttons(); + } + + function set_data($data) { + $data->case = $data->id; + unset($data->id); + if (strlen($data->input) > 1023) { + $data->input = ''; + } + if (strlen($data->output) > 1023) { + $data->output = ''; + } + parent::set_data($data); + } + + /* + function validation($data, $files) { + $errors = array(); + + if (empty($data['output']) or trim($data['output']) == '') + if (empty($files['outputfile'])) + $errors['output'] = get_string('required'); + + return $errors; + }*/ + +} diff --git a/testcase/list.php b/testcase/list.php new file mode 100644 index 0000000..7d71e45 --- /dev/null +++ b/testcase/list.php @@ -0,0 +1,150 @@ +libdir.'/tablelib.php'); + require_once('../lib.php'); + + $id = required_param('id', PARAM_INT); // programming ID + $params = array('id' => $id); + $PAGE->set_url('/mod/programming/testcase/list.php', $params); + + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + require_capability('mod/programming:viewhiddentestcase', $context); + +/// Print the page header + $PAGE->set_title(format_string($course->shortname).': '.$programming->name).': '.get_string('testcase', 'programming'); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + +/// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('edittest', 'testcase', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + +/// Print page content + echo html_writer::tag('h2', $programming->name); + echo html_writer::tag('h3', get_string('testcase', 'programming').$OUTPUT->help_icon('testcase', 'programming')); + print_testcase_table(); + +/// Finish the page + echo $OUTPUT->footer($course); + +function print_testcase_table() { + global $CFG, $OUTPUT, $DB, $cm, $params, $programming, $course, $language, $groupid; + + $table = new html_table(); + $table->head = array( + get_string('sequence', 'programming'), + get_string('testcasepub', 'programming').$OUTPUT->help_icon('testcasepub', 'programming'), + get_string('input', 'programming').$OUTPUT->help_icon('input', 'programming'), + get_string('output', 'programming').$OUTPUT->help_icon('output', 'programming'), + get_string('timelimit', 'programming').$OUTPUT->help_icon('timelimit', 'programming'), + get_string('memlimit', 'programming').$OUTPUT->help_icon('memlimit', 'programming'), + get_string('extraproc', 'programming').$OUTPUT->help_icon('nproc', 'programming'), + get_string('weight', 'programming').$OUTPUT->help_icon('weight', 'programming'), + get_string('action'), + ); + + //$table->set_attribute('id', 'presetcode-table'); + //$table->set_attribute('class', 'generaltable generalbox'); + $table->tablealign = 'center'; + $table->cellpadding = 3; + $table->cellspacing = 1; + $table->colclasses[2] = 'programming-io'; + $table->colclasses[3] = 'programming-io'; + //$table->no_sorting('code'); + $table->data = array(); + + $strshowasplaintext = get_string('showasplaintext', 'programming'); + $strdownload = get_string('download', 'programming'); + $stredit = get_string('edit'); + $strdelete = get_string('delete'); + $strmoveup = get_string('moveup'); + $strmovedown = get_string('movedown'); + $fields = 'id,programmingid,seq,input,output,cmdargs,timelimit,memlimit,nproc,pub,weight,memo,timemodified'; + $tests = $DB->get_records('programming_tests', array('programmingid' => $programming->id), 'seq',$fields); + + if (is_array($tests)) { + $tests_count = count($tests)-1; + $i = 0; + foreach ($tests as $case) { + $data = array(); + $data[] = $case->seq; + $data[] = programming_testcase_pub_getstring($case->pub); + + // stdin + $url = new moodle_url('/mod/programming/testcase/download_io.php', array('id' => $cm->id, 'test' => $case->id, 'type'=> 'in', 'download' => 0)); + $html = $OUTPUT->action_link($url, $strshowasplaintext, new popup_action('click', $url), array('class' => 'showasplaintext small')); + $html .= ' '; + $url->param('download', 1); + $html .= $OUTPUT->action_link($url, $strdownload, null, array('class' => 'download small')); + $html .= programming_format_io($case->input, false); + $data[] = $html; + + // stdout + $url->params(array('type' => 'out', 'download' => 0)); + $html = $OUTPUT->action_link($url, $strshowasplaintext, new popup_action('click', $url), array('class' => 'showasplaintext small')); + $html .= ' '; + $url->param('download', 1); + $html .= $OUTPUT->action_link($url, $strdownload, null, array('class' => 'download small')); + $html .= programming_format_io($case->output, false); + $data[] = $html; + + // limits + $data[] = get_string('nseconds', 'programming', $case->timelimit); + $data[] = get_string('nkb', 'programming', $case->memlimit); + $data[] = $case->nproc; + + $data[] = get_string('nweight', 'programming', $case->weight); + + // actions + $actions = array(); + $actions[] = $OUTPUT->action_link( + new moodle_url('edit.php', array('id' => $cm->id, 'case' => $case->id)), + html_writer::empty_tag('img', array('title' => $stredit, 'src' => $OUTPUT->image_url('t/edit'))), + null, + array('class' => 'icon edit')); + $url = new moodle_url('/mod/programming/testcase/delete.php', array('id' => $cm->id, 'case' => $case->id)); + $txt = html_writer::empty_tag('img', array('title' => $strdelete, 'src' => $OUTPUT->image_url('t/delete'))); + $act = new confirm_action(get_string('deletetestcaseconfirm', 'programming')); + $actions[] = $OUTPUT->action_link($url, $txt, $act, array('class' => 'icon delete')); + if ($i > 0) { + $actions[] = $OUTPUT->action_link( + new moodle_url('move.php', array('id' => $cm->id, 'case' => $case->id, 'direction' => 1)), + html_writer::empty_tag('img', array('title' => $strmoveup, 'src' => $OUTPUT->image_url('t/up'))), + null, + array('class' => 'icon up')); + } + if ($i < $tests_count) { + $actions[] = $OUTPUT->action_link( + new moodle_url('move.php', array('id' => $cm->id, 'case' => $case->id, 'direction' => 2)), + html_writer::empty_tag('img', array('title' => $strmovedown, 'src' => $OUTPUT->image_url('t/down'))), + null, + array('class' => 'icon down')); + } + $data[] = implode("\n",$actions); + + $table->data[] = $data; + $i++; + } + + echo html_writer::table($table); + } else { + echo html_writer::tag('p'.get_string('notestcase', 'programming')); + } + echo html_writer::tag('p', $OUTPUT->action_link(new moodle_url('add.php', array('id' => $cm->id)), get_string('addtestcase', 'programming'))); +} diff --git a/testcase/move.php b/testcase/move.php new file mode 100644 index 0000000..7367e58 --- /dev/null +++ b/testcase/move.php @@ -0,0 +1,29 @@ +get_record('course', array('id' => $cm->course))) { + error('Course is misconfigured'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + error('Course module is incorrect'); + } + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + require_capability('mod/programming:edittestcase', $context); + + programming_testcase_adjust_sequence($programming->id, $case, $direction); + redirect(new moodle_url('/mod/programming/testcase/list.php', array('id' => $cm->id)), get_string('testcasemoved', 'programming'), 0); diff --git a/text_diff_render_html.php b/text_diff_render_html.php new file mode 100644 index 0000000..ab0c2c6 --- /dev/null +++ b/text_diff_render_html.php @@ -0,0 +1,79 @@ +_x = $xbeg; + $this->_y = $ybeg; + } + + function _startBlock($header) { + return '' . $header; + } + + function _endBlock() { + return '
    '; + } + + function _lines($lines, $xi = 1, $yi = 1, $op = '', $clazz = 'normal', $nofirst = false, $nolast = false) { + $r = ''; + for ($i = 0; $i < count($lines); $i++) { + $line = $lines[$i]; + + $clazz1 = $clazz; + if ($i == 0 && $clazz1 != 'normal' && !$nofirst) { + $clazz1 .= ' first'; + } + if ($i == count($lines)-1 && $clazz1 != 'normal' && !$nolast) { + $clazz1 .= ' last'; + } + + $r .= ''; + $r .= ''.($xi ? $this->_x : '').''; + $r .= ''.($yi ? $this->_y : '').''; + $r .= ''.$op.''; + $r .= ''.htmlspecialchars($line).''; + $r .= ''; + + $this->_x += $xi; + $this->_y += $yi; + } + return $r; + } + + function _context($lines) { + return $this->_lines($lines); + } + + function _added($lines) + { + return $this->_lines($lines, 0, 1, '+', 'added'); + } + + function _deleted($lines) + { + return $this->_lines($lines, 1, 0, '-', 'deleted'); + } + + function _changed($orig, $final) + { + return $this->_lines($orig, 1, 0, '-', 'deleted', false, true) . $this->_lines($final, 0, 1, '+', 'added', true, false); + } +} + +?> diff --git a/validator/edit.php b/validator/edit.php new file mode 100644 index 0000000..25d9acc --- /dev/null +++ b/validator/edit.php @@ -0,0 +1,63 @@ + $id); + $PAGE->set_url('/mod/programming/validator/edit.php', $params); + + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + $context = context_module::instance($cm->id); + + require_capability('mod/programming:edittestcase', $context); + + $mform = new validator_form(); + if ($mform->is_cancelled()) { + redirect(new moodle_url('list.php', array('id' => $cm->id))); + + } else if ($data = $mform->get_data()) { + $data->id = $programming->id; + $DB->update_record('programming', $data); + + + redirect(new moodle_url('edit.php', array('id' => $cm->id)), get_string('validatormodified', 'programming')); + } else { + $data = $DB->get_record('programming', array('id' => $cm->instance)); + $data->id = $cm->id; + $mform->set_data($data); + + } + +/// Print the page header + $PAGE->set_title(format_string($course->shortname).': '.$programming->name).': '.get_string('validator', 'programming'); + $PAGE->set_heading(format_string($course->fullname)); + echo $OUTPUT->header(); + +/// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('edittest', 'validator', $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + +/// Print page content + echo html_writer::tag('h2', $programming->name); + echo html_writer::tag('h3', get_string('validator', 'programming').$OUTPUT->help_icon('validator', 'programming')); + + $mform->display(); + +/// Finish the page + echo $OUTPUT->footer($course); diff --git a/validator/form.php b/validator/form.php new file mode 100644 index 0000000..27f00da --- /dev/null +++ b/validator/form.php @@ -0,0 +1,40 @@ +libdir.'/formslib.php'); +require_once ('../lib.php'); + +class validator_form extends moodleform { + + function definition() { + global $CFG, $COURSE; + $mform =& $this->_form; + +//------------------------------------------------------------------------------- + $mform->addElement('hidden', 'id'); + $mform->setType('id', PARAM_INT); + + $options = array( + '0' => get_string('comparetext', 'programming'), + '1' => get_string('comparetextwithpe', 'programming'), + '2' => get_string('comparefilesizeandmd5', 'programming'), + '9' => get_string('customizedjudgescript', 'programming') + ); + $mform->addElement('select', 'validatortype', get_string('validatortype', 'programming'), $options); + + $options = programming_get_language_options(); + $mform->addElement('select', 'validatorlang', get_string('validatorlang', 'programming'), $options); + $mform->disabledIf('validatorlang', 'validatortype', 'neq', 9); + + $mform->addElement('textarea', 'validator', get_string('validatorcode', 'programming'), 'rows="10" cols="50"'); + $mform->disabledIf('validator', 'validatortype', 'neq', 9); + +// buttons + $this->add_action_buttons(); + } + + function validation($data, $files) { + $errors = array(); + + return $errors; + } + +} diff --git a/version.php b/version.php new file mode 100644 index 0000000..cd7ec0b --- /dev/null +++ b/version.php @@ -0,0 +1,16 @@ +version = 2012122601; // The current module version (Date: YYYYMMDDXX) +$plugin->requires = 2011062402; // Requires this Moodle version--2011062402 is the latest version fits for moodle1.9x +$plugin->component = 'mod_programming'; // Full name of the plugin (used for diagnostics) +$plugin->release = '2.x (Build: 2012051101)';// Human-readable version name +$plugin->cron = 0; // Period for cron to check this module (secs) + +?> diff --git a/view.php b/view.php new file mode 100644 index 0000000..aa95d79 --- /dev/null +++ b/view.php @@ -0,0 +1,176 @@ + $id); + if (! $cm = get_coursemodule_from_id('programming', $id)) { + print_error('invalidcoursemodule'); + } + } else { + $params = array('course' => $cid); + if(! $cm = get_coursemodule_from_instance('programming' , $cid ) ){ + print_error('invalidcoursemodule'); + } + } + + $PAGE->set_url('/mod/programming/view.php', $params); + + if (! $course = $DB->get_record('course', array('id' => $cm->course))) { + print_error('coursemisconf'); + } + + if (! $programming = $DB->get_record('programming', array('id' => $cm->instance))) { + print_error('invalidprogrammingid', 'programming'); + } + + require_login($course->id, true, $cm); + + $context = context_module::instance($cm->id); + + if (!$cm->visible) { + require_capability('moodle/course:viewhiddenactivities', $context); + } + + require_capability('mod/programming:viewcontent', $context); + + +/// Print the page header + $PAGE->set_title($programming->name); + $PAGE->set_heading(format_string($course->fullname)); + $PAGE->requires->css('/mod/programming/js/dp/SyntaxHighlighter.css'); + $PAGE->requires->js('/mod/programming/js/dp/shCore.js'); + $PAGE->requires->js('/mod/programming/js/dp/shBrushCSharp.js'); + echo $OUTPUT->header(); + +/// Print tabs + $renderer = $PAGE->get_renderer('mod_programming'); + $tabs = programming_navtab('view', null, $course, $programming, $cm); + echo $renderer->render_navtab($tabs); + +/// Print the main part of the page + $fields = 'id,programmingid,seq,input,output,cmdargs,timelimit,memlimit,nproc,pub,weight,memo,timemodified'; + $pubtests = $DB->get_records('programming_tests', array('programmingid' => $programming->id, 'pub' => 1), 'seq',$fields); + $presetcodes = $DB->get_records('programming_presetcode', array('programmingid' => $programming->id), 'sequence'); + $datafiles = $DB->get_records('programming_datafile', array('programmingid' => $programming->id), 'seq', 'id, programmingid, filename, isbinary, datasize, checkdatasize'); + + $notlate = $programming->allowlate || time() <= $programming->timeclose; + + print_content(); + +/// Finish the page + echo $OUTPUT->footer($course); + +function print_content() { + global $CFG, $OUTPUT, $cm, $programming, $context; + global $datafiles, $presetcodes, $viewpubtestcase, $pubtests; + + echo html_writer::tag('h2', $programming->name); + + if ($programming->showmode == PROGRAMMING_SHOWMODE_NORMAL) { + echo $OUTPUT->box_start('time-table'); + + $table = new html_table(); + $table->data = array(); + + $table->data[] = array(get_string('grade','mod_programming'), $programming->grade, get_string('timeopen', 'programming'), userdate($programming->timeopen)); + $table->data[] = array(get_string('discount', 'programming'), $programming->discount/10.0, get_string('timediscount', 'programming'), userdate($programming->timediscount)); + $table->data[] = array(get_string('allowlate', 'programming'), get_string($programming->allowlate ? 'yes' : 'no'), get_string('timeclose', 'programming'), userdate($programming->timeclose)); + if($programming->inputfile) { + $table->data[] = array(get_string('inputfile', 'programming'), ''.$programming->inputfile.'', get_string('outputfile', 'programming'), ''.$programming->outputfile.''); + } + echo html_writer::table($table); + + echo $OUTPUT->box_end(); + } else { + echo html_writer::start_tag('span', array('class' => 'limit')); + echo get_string('timelimit', 'programming'); + echo programming_format_timelimit($programming->timelimit); + echo ' '; + echo get_string('memlimit', 'programming'); + echo programming_format_memlimit($programming->memlimit); + echo html_writer::end_tag('span'); + } + + echo $OUTPUT->box_start('description'); + + echo $OUTPUT->box_start('intro'); + echo format_module_intro('programming', $programming, $cm->id); + echo $OUTPUT->box_end(); + + if (is_array($datafiles) && !empty($datafiles)) { + echo $OUTPUT->box_start('datafile'); + echo html_writer::tag('h3', get_string('datafile', 'programming')); + echo html_writer::start_tag('ul'); + foreach ($datafiles as $datafile) { + $url = new moodle_url('/mod/programming/datafile/download.php', array('id' => $cm->id, 'datafile' => $datafile->id)); + echo html_writer::tag('li', $OUTPUT->action_link($url, $datafile->filename, null, array('title' => get_string('presstodownload', 'programming')))); + } + echo html_writer::end_tag('ul'); + echo $OUTPUT->box_end(); + } + + if (is_array($presetcodes) && !empty($presetcodes)) { + echo $OUTPUT->box_start('presetcode'); + echo html_writer::tag('h3', get_string('presetcode', 'programming')); + foreach ($presetcodes as $pcode) { + echo html_writer::tag('h4', programming_get_presetcode_name($pcode)); + echo html_writer::tag('textarea', htmlspecialchars(programming_format_presetcode($pcode)), array('rows' => 20, 'cols' => 60, 'name' => 'code', 'class' => 'c#', 'id' => 'code')); + } + echo $OUTPUT->box_end(); + } + + $viewpubtestcase = has_capability('mod/programming:viewpubtestcase', $context); + if ($viewpubtestcase && $programming->showmode == PROGRAMMING_SHOWMODE_NORMAL && count($pubtests) > 0) { + $strshowasplaintext = get_string('showasplaintext', 'programming'); + + echo $OUTPUT->box_start('testcase-table'); + $table = new html_table(); + $table->head = array( + ' ', + get_string('input', 'programming').$OUTPUT->help_icon('input', 'programming'), + get_string('expectedoutput', 'programming').$OUTPUT->help_icon('expectedoutput', 'programming'), + get_string('timelimit', 'programming').$OUTPUT->help_icon('timelimit', 'programming'), + get_string('memlimit', 'programming').$OUTPUT->help_icon('memlimit', 'programming'), + get_string('extraproc', 'programming').$OUTPUT->help_icon('nproc', 'programming')); + $table->colclasses[1] = 'programming-io'; + $table->colclasses[2] = 'programming-io'; + + $table->data = array(); + $i = 0; $ioid = 0; + foreach ($pubtests as $programmingtest) { + $row = array(); + $row[] = get_string('testcasen', 'programming', $programmingtest->seq); + + $url = new moodle_url($CFG->wwwroot.'/mod/programming/testcase/download_io.php', array('id' => $cm->id, 'test' => $programmingtest->id, 'type' => 'in', 'download' => 0)); + $action = new popup_action('click', $url, '_blank', array('height' => 300, 'width' => 400)); + $html = $OUTPUT->action_link($url, $strshowasplaintext, $action, array('class' => 'showasplaintext small')); + $html.= programming_format_io($programmingtest->input, true); + $row[] = $html; + + $url->param('type', 'out'); + $action = new popup_action('click', $url, '_blank', array('height' => 300, 'width' => 400)); + $html = $OUTPUT->action_link($url, $strshowasplaintext, $action, array('class' => 'showasplaintext small')); + $html.= programming_format_io($programmingtest->output, true); + $row[] = $html; + $row[] = programming_format_timelimit($programmingtest->timelimit); + $row[] = programming_format_memlimit($programmingtest->memlimit); + $row[] = $programmingtest->nproc; + + $table->data[] = $row; + } + + echo html_writer::table($table); + echo $OUTPUT->box_end(); + } + + echo $OUTPUT->box_end(); // description + +}