` for each element covering its bounding box area.
+ _.each(elementViews, this.createSelectionBox, this);
+
+ // The root element of the selection switches `position` to `static` when `selected`. This
+ // is neccessary in order for the `selection-box` coordinates to be relative to the
+ // `paper` element, not the `selection` `
`.
+ this.$el.addClass('selected');
+
+ } else {
+
+ // Hide the selection box if there was no element found in the area covered by the
+ // selection box.
+ this.$el.hide();
+ }
+
+ this.model.reset(_.pluck(elementViews, 'model'));
+ break;
+
+ case 'translating':
+
+ this.options.graph.trigger('batch:stop');
+ // Everything else is done during the translation.
+ break;
+
+ case 'cherry-picking':
+ // noop; All is done in the `createSelectionBox()` function.
+ // This is here to avoid removing selection boxes as a reaction on mouseup event and
+ // propagating to the `default` branch in this switch.
+ break;
+
+ default:
+ // Hide selection if the user clicked somehwere else in the document.
+ // this.$el.hide().empty();
+ // this.model.reset([]);
+ break;
+ }
+
+ delete this._action;
+ },
+
+ cancelSelection: function() {
+
+ this.$('.selection-box').remove();
+ this.$el.hide().removeClass('selected');
+ this.model.reset([]);
+ },
+
+ destroySelectionBox: function(elementView) {
+
+ this.$('[data-model="' + elementView.model.get('id') + '"]').remove();
+ if (this.$('.selection-box').length === 0) {
+
+ this.$el.hide().removeClass('selected');
+ }
+ },
+
+ createSelectionBox: function(elementView) {
+
+ var element = elementView.model;
+
+ if (!element.isLink()) {
+
+ var $selectionBox = $('
', {
+ 'class': 'selection-box',
+ 'data-model': element.get('id')
+ });
+ this.$el.append($selectionBox);
+
+ this.updateBox(element);
+
+ this.$el.addClass('selected').show();
+
+ this._action = 'cherry-picking';
+ }
+ },
+
+ updateBox: function(element) {
+
+ var border = 12;
+
+ var bbox = element.getBBox();
+ var state = this.options.state;
+
+ $("div[data-model='" + element.get('id') + "']").css({
+ left: bbox.x * state.zoom + state.pan.x +
+ bbox.width / 2.0 * (state.zoom - 1) - border / 2,
+ top: bbox.y * state.zoom + state.pan.y +
+ bbox.height / 2.0 * (state.zoom - 1) - border / 2,
+ width: bbox.width + border,
+ height: bbox.height + border,
+ transform: 'scale(' + state.zoom + ')'
+ });
+ }
+
+});
diff --git a/app/scripts/services/boards.service.js b/app/scripts/services/boards.service.js
new file mode 100644
index 000000000..019ef5c51
--- /dev/null
+++ b/app/scripts/services/boards.service.js
@@ -0,0 +1,186 @@
+'use strict';
+
+angular.module('icestudio')
+ .service('boards', function() {
+
+ this.getBoards = function() {
+ return [
+ { id: 'icezum', label: 'Icezum' },
+ { id: 'icestick', label: 'iCEstick' },
+ { id: 'go-board', label: 'Go board' }
+ ]
+ };
+
+ this.selectedBoard = this.getBoards()[0];
+
+ this.selectBoard = function(id) {
+ var boards = this.getBoards();
+ for (var i in boards) {
+ if (id == boards[i].id) {
+ this.selectedBoard = boards[i];
+ break;
+ }
+ }
+ };
+
+ this.pinouts = {};
+
+ this.pinouts['icezum'] = [
+ { name: 'LED0', value: '95' },
+ { name: 'LED1', value: '96' },
+ { name: 'LED2', value: '97' },
+ { name: 'LED3', value: '98' },
+ { name: 'LED4', value: '99' },
+ { name: 'LED5', value: '101' },
+ { name: 'LED6', value: '102' },
+ { name: 'LED7', value: '104' },
+ { name: 'SW1', value: '10' },
+ { name: 'SW2', value: '11' },
+ { name: 'D13', value: '144' },
+ { name: 'D12', value: '143' },
+ { name: 'D11', value: '142' },
+ { name: 'D10', value: '141' },
+ { name: 'D9', value: '139' },
+ { name: 'D8', value: '138' },
+ { name: 'D7', value: '112' },
+ { name: 'D6', value: '113' },
+ { name: 'D5', value: '114' },
+ { name: 'D4', value: '115' },
+ { name: 'D3', value: '116' },
+ { name: 'D2', value: '117' },
+ { name: 'D1', value: '118' },
+ { name: 'D0', value: '119' },
+ { name: 'DD0', value: '78' },
+ { name: 'DD1', value: '79' },
+ { name: 'DD2', value: '80' },
+ { name: 'DD3', value: '81' },
+ { name: 'DD4', value: '88' },
+ { name: 'DD5', value: '87' },
+ { name: 'GP0', value: '37' },
+ { name: 'GP1', value: '38' },
+ { name: 'GP2', value: '39' },
+ { name: 'GP3', value: '41' },
+ { name: 'GP4', value: '42' },
+ { name: 'GP5', value: '43' },
+ { name: 'GP6', value: '49' },
+ { name: 'GP7', value: '50' },
+ { name: 'ADC_SCL', value: '91' },
+ { name: 'ADC_SDA', value: '90' },
+ { name: 'ADC_INT', value: '93' },
+ { name: 'CLK', value: '21' },
+ { name: 'RES', value: '66' },
+ { name: 'DONE', value: '65' },
+ { name: 'SS', value: '71' },
+ { name: 'MISO', value: '67' },
+ { name: 'MOSI', value: '68' },
+ { name: 'SCK', value: '70' },
+ { name: 'DCD', value: '1' },
+ { name: 'DSR', value: '2' },
+ { name: 'DTR', value: '3' },
+ { name: 'CTS', value: '4' },
+ { name: 'RTS', value: '7' },
+ { name: 'TX', value: '8' },
+ { name: 'RX', value: '9' }
+ ];
+
+ this.pinouts['icestick'] = [
+ { name: 'D1', value: '99' },
+ { name: 'D2', value: '98' },
+ { name: 'D3', value: '97' },
+ { name: 'D4', value: '96' },
+ { name: 'D5', value: '95' },
+ { name: 'IrDA_TX', value: '105' },
+ { name: 'IrDA_RX', value: '106' },
+ { name: 'SD', value: '107' },
+ { name: 'PMOD1', value: '78' },
+ { name: 'PMOD2', value: '79' },
+ { name: 'PMOD3', value: '80' },
+ { name: 'PMOD4', value: '81' },
+ { name: 'PMOD7', value: '87' },
+ { name: 'PMOD8', value: '88' },
+ { name: 'PMOD9', value: '90' },
+ { name: 'PMOD10', value: '91' },
+ { name: 'TR3', value: '112' },
+ { name: 'TR4', value: '113' },
+ { name: 'TR5', value: '114' },
+ { name: 'TR6', value: '115' },
+ { name: 'TR7', value: '116' },
+ { name: 'TR8', value: '117' },
+ { name: 'TR9', value: '118' },
+ { name: 'TR10', value: '119' },
+ { name: 'BR3', value: '62' },
+ { name: 'BR4', value: '61' },
+ { name: 'BR5', value: '60' },
+ { name: 'BR6', value: '56' },
+ { name: 'BR7', value: '48' },
+ { name: 'BR8', value: '47' },
+ { name: 'BR9', value: '45' },
+ { name: 'BR10', value: '44' },
+ { name: 'CLK', value: '21' },
+ { name: 'RES', value: '66' },
+ { name: 'DONE', value: '65' },
+ { name: 'SS', value: '71' },
+ { name: 'MISO', value: '67' },
+ { name: 'MOSI', value: '68' },
+ { name: 'SCK', value: '70' },
+ { name: 'DCD', value: '1' },
+ { name: 'DSR', value: '2' },
+ { name: 'DTR', value: '3' },
+ { name: 'CTS', value: '4' },
+ { name: 'RTS', value: '7' },
+ { name: 'TX', value: '8' },
+ { name: 'RX', value: '9' }
+ ];
+
+ this.pinouts['go-board'] = [
+ { name: 'LED1', value: '56' },
+ { name: 'LED2', value: '57' },
+ { name: 'LED3', value: '59' },
+ { name: 'LED4', value: '60' },
+ { name: 'SW1', value: '53' },
+ { name: 'SW2', value: '51' },
+ { name: 'SW3', value: '54' },
+ { name: 'SW4', value: '52' },
+ { name: 'S1_A', value: '3' },
+ { name: 'S1_B', value: '4' },
+ { name: 'S1_C', value: '93' },
+ { name: 'S1_D', value: '91' },
+ { name: 'S1_E', value: '90' },
+ { name: 'S1_F', value: '1' },
+ { name: 'S1_G', value: '2' },
+ { name: 'S2_A', value: '100' },
+ { name: 'S2_B', value: '99' },
+ { name: 'S2_C', value: '97' },
+ { name: 'S2_D', value: '95' },
+ { name: 'S2_E', value: '94' },
+ { name: 'S2_F', value: '8' },
+ { name: 'S2_G', value: '96' },
+ { name: 'CLK', value: '15' },
+ { name: 'RX', value: '73' },
+ { name: 'TX', value: '74' },
+ { name: 'VGA_HS', value: '26' },
+ { name: 'VGA_VS', value: '27' },
+ { name: 'VGA_R0', value: '36' },
+ { name: 'VGA_R1', value: '37' },
+ { name: 'VGA_R2', value: '40' },
+ { name: 'VGA_G0', value: '29' },
+ { name: 'VGA_G1', value: '30' },
+ { name: 'VGA_G2', value: '33' },
+ { name: 'VGA_B0', value: '28' },
+ { name: 'VGA_B1', value: '41' },
+ { name: 'VGA_B2', value: '42' },
+ { name: 'PMOD1', value: '65' },
+ { name: 'PMOD2', value: '64' },
+ { name: 'PMOD3', value: '63' },
+ { name: 'PMOD4', value: '62' },
+ { name: 'PMOD7', value: '78' },
+ { name: 'PMOD8', value: '79' },
+ { name: 'PMOD9', value: '80' },
+ { name: 'PMOD10', value: '81' }
+ ]
+
+ this.getPinout = function() {
+ return this.pinouts[this.selectedBoard.id];
+ }
+
+ });
diff --git a/app/scripts/services/common.service.js b/app/scripts/services/common.service.js
new file mode 100644
index 000000000..7df8228fd
--- /dev/null
+++ b/app/scripts/services/common.service.js
@@ -0,0 +1,214 @@
+'use strict';
+
+angular.module('icestudio')
+ .service('common', ['$rootScope', 'window', 'graph', 'boards', 'compiler', 'utils',
+ function($rootScope, window, graph, boards, compiler, utils) {
+
+ // Variables
+
+ this.project = {
+ image: '',
+ state: null,
+ board: '',
+ graph: {},
+ deps: {}
+ };
+ this.projectName = '';
+
+ // Functions
+
+ this.newProject = function(name) {
+ this.project = {
+ image: '',
+ state: null,
+ board: '',
+ graph: {},
+ deps: {}
+ };
+ graph.clearAll();
+ graph.setState(this.project.state);
+ this.updateProjectName(name);
+ alertify.success('New project ' + name + ' created');
+ };
+
+ this.openProject = function(filepath) {
+ utils.readFile(filepath, (function(_this) {
+ return function(data) {
+ var project = data;
+ if (project) {
+ var name = utils.basename(filepath);
+ _this.loadProject(name, project);
+ }
+ };
+ })(this));
+ };
+
+ this.loadProject = function(name, project) {
+ this.updateProjectName(name);
+ this.project = project;
+ boards.selectBoard(project.board);
+ if (graph.loadGraph(project)) {
+ alertify.success('Project ' + name + ' loaded');
+ }
+ else {
+ alertify.error('Wrong project format: ' + name);
+ }
+ };
+
+ this.saveProject = function(filepath) {
+ var name = utils.basename(filepath);
+ this.updateProjectName(name);
+ this.refreshProject();
+ utils.saveFile(filepath, this.project, function() {
+ alertify.success('Project ' + name + ' saved');
+ }, true);
+ };
+
+ this.importBlock = function(filepath) {
+ utils.readFile(filepath, (function(_this) {
+ return function(data) {
+ var block = data;
+ if (block) {
+ var name = utils.basename(filepath);
+ graph.importBlock(name, block);
+ _this.project.deps[name] = block;
+ alertify.success('Block ' + name + ' imported');
+ }
+ };
+ })(this));
+ };
+
+ this.exportAsBlock = function(filepath) {
+ var name = utils.basename(filepath);
+ this.refreshProject();
+ // Convert project to block
+ var block = angular.copy(this.project);
+ delete block.board;
+ for (var i in block.graph.blocks) {
+ if (block.graph.blocks[i].type == 'basic.input' ||
+ block.graph.blocks[i].type == 'basic.output') {
+ delete block.graph.blocks[i].data.pin;
+ }
+ }
+ utils.saveFile(filepath, block, function() {
+ alertify.success('Block exported as ' + name);
+ }, true);
+ };
+
+ this.exportVerilog = function(filepath) {
+ var name = utils.basename(filepath);
+ this.refreshProject();
+ // Generate verilog code from project
+ var verilog = compiler.generateVerilog(this.project);
+ utils.saveFile(filepath, verilog, function() {
+ alertify.success('Exported verilog from project ' + name);
+ }, false);
+ };
+
+ this.exportPCF = function(filepath) {
+ var name = utils.basename(filepath);
+ this.refreshProject();
+ // Generate pcf code from project
+ var pcf = compiler.generatePCF(this.project);
+ utils.saveFile(filepath, pcf, function() {
+ alertify.success('Exported PCF from project ' + name);
+ }, false);
+ };
+
+ this.refreshProject = function(callback) {
+ var graphData = graph.toJSON();
+
+ var blocks = [];
+ var wires = [];
+
+ for (var c = 0; c < graphData.cells.length; c++) {
+ var cell = graphData.cells[c];
+
+ if (cell.type == 'ice.Generic' ||
+ cell.type == 'ice.Input' ||
+ cell.type == 'ice.Output' ||
+ cell.type == 'ice.Code' ||
+ cell.type == 'ice.Info') {
+ var block = {};
+ block.id = cell.id;
+ block.type = cell.blockType;
+ block.data = cell.data;
+ block.position = cell.position;
+ if (cell.type == 'ice.Code') {
+ block.data.code = graph.getContent(cell.id);
+ }
+ else if (cell.type == 'ice.Info') {
+ block.data.info = graph.getContent(cell.id);
+ }
+ blocks.push(block);
+ }
+ else if (cell.type == 'ice.Wire') {
+ var wire = {};
+ wire.source = { block: cell.source.id, port: cell.source.port };
+ wire.target = { block: cell.target.id, port: cell.target.port };
+ wire.vertices = cell.vertices;
+ wires.push(wire);
+ }
+ }
+
+ this.project.state = graph.getState();
+
+ this.project.board = boards.selectedBoard.id;
+
+ this.project.graph = { blocks: blocks, wires: wires };
+
+ if (callback)
+ callback();
+ };
+
+ this.clearProject = function() {
+ this.project = {
+ image: '',
+ state: this.project.state,
+ board: '',
+ graph: {},
+ deps: {}
+ };
+ graph.clearAll();
+ graph.breadcrumbs = [{ name: this.projectName }];
+ if(!$rootScope.$$phase) {
+ $rootScope.$apply();
+ }
+ };
+
+ this.cloneSelected = function() {
+ graph.cloneSelected();
+ };
+
+ this.removeSelected = function() {
+ graph.removeSelected((function(_this) {
+ return function(type) {
+ delete _this.project.deps[type];
+ }
+ })(this));
+ };
+
+ this.setImagePath = function(imagePath) {
+ this.project.image = imagePath;
+ }
+
+ this.updateProjectName = function(name) {
+ if (name) {
+ this.projectName = name
+ if (graph.breadcrumbs.length > 1) {
+ graph.breadcrumbs = [{ name: name }];
+ }
+ graph.breadcrumbs[0].name = name;
+ if(!$rootScope.$$phase) {
+ $rootScope.$apply();
+ }
+ window.get().title = 'Icestudio - ' + name;
+ }
+ };
+
+ this.addBlock = function(type, block) {
+ this.project.deps[type] = block;
+ graph.createBlock(type, block);
+ }
+
+ }]);
diff --git a/app/scripts/services/compiler.service.js b/app/scripts/services/compiler.service.js
new file mode 100644
index 000000000..15096b4bc
--- /dev/null
+++ b/app/scripts/services/compiler.service.js
@@ -0,0 +1,240 @@
+'use strict';
+
+angular.module('icestudio')
+ .service('compiler', ['nodeSha1',
+ function(nodeSha1) {
+
+ this.generateVerilog = function(project) {
+ return verilogCompiler('main', project);
+ };
+
+ this.generatePCF = function(project) {
+ return pcfCompiler(project);
+ };
+
+ function digestId(id, force) {
+ if (id.indexOf('-') != -1) {
+ return 'v' + nodeSha1(id).toString().substring(0, 6);
+ }
+ else {
+ return id.replace('.', '_');
+ }
+ return id;
+ }
+
+ function module(data) {
+ var code = '';
+
+ if (data &&
+ data.name &&
+ data.ports &&
+ data.content) {
+
+ // Header
+
+ code += 'module ';
+ code += data.name;
+ code += ' (';
+
+ var params = [];
+ var paramsSpace = 10 + data.name.length;
+
+ for (var i in data.ports.in) {
+ params.push('input ' + data.ports.in[i]);
+ }
+ for (var o in data.ports.out) {
+ params.push('output ' + data.ports.out[o]);
+ }
+
+ code += params.join(',\n' + new Array(paramsSpace).join(' '));
+
+ code += ');\n';
+
+ // Content
+
+ var content = data.content.split('\n');
+
+ content.forEach(function (element, index, array) {
+ array[index] = ' ' + element;
+ });
+
+ code += content.join('\n');
+
+ // Footer
+
+ code += '\nendmodule\n\n';
+ }
+
+ return code;
+ }
+
+ function getPorts(project) {
+ var ports = {
+ in: [],
+ out: []
+ };
+ var graph = project.graph;
+
+ for (var i in graph.blocks) {
+ var block = graph.blocks[i];
+ if (block.type == 'basic.input') {
+ ports.in.push(digestId(block.id));
+ }
+ else if (block.type == 'basic.output') {
+ ports.out.push(digestId(block.id));
+ }
+ }
+
+ return ports;
+ }
+
+ function getContent(name, project) {
+ var content = '';
+ var graph = project.graph;
+
+ // Wires
+
+ for (var w in graph.wires) {
+ content += 'wire w' + w + ';\n'
+ }
+
+ // I/O connections
+
+ for (var w in graph.wires) {
+ var wire = graph.wires[w];
+ for (var i in graph.blocks) {
+ var block = graph.blocks[i];
+ if (block.type == 'basic.input') {
+ if (wire.source.block == block.id) {
+ content += 'assign w' + w + ' = ' + digestId(block.id) + ';\n';
+ }
+ }
+ else if (block.type == 'basic.output') {
+ if (wire.target.block == block.id) {
+ content += 'assign ' + digestId(block.id) + ' = w' + w + ';\n';
+ }
+ }
+ }
+ }
+
+ // Wires Connections
+
+ var numWires = graph.wires.length;
+ for (var i = 1; i < numWires; i++) {
+ for (var j = 0; j < i; j++) {
+ var wi = graph.wires[i];
+ var wj = graph.wires[j];
+ if (wi.source.block == wj.source.block &&
+ wi.source.port == wj.source.port) {
+ content += 'assign w' + i + ' = w' + j + ';\n';
+ }
+ }
+ }
+
+ // Block instances
+
+ var instances = []
+ for (var b in graph.blocks) {
+ var block = graph.blocks[b];
+ if (block.type != 'basic.input' &&
+ block.type != 'basic.output' &&
+ block.type != 'basic.info') {
+
+ var id = digestId(block.type, true);
+ if (block.type == 'basic.code') {
+ id += '_' + digestId(block.id);
+ }
+ instances.push(name + '_' + id + ' ' + digestId(block.id) + ' (');
+
+ // Parameters
+
+ var params = [];
+ var paramsNames = [];
+ for (var w in graph.wires) {
+ var param = '';
+ var paramName = '';
+ var wire = graph.wires[w];
+ if (block.id == wire.source.block) {
+ paramName = digestId(wire.source.port);
+ }
+ else if (block.id == wire.target.block) {
+ paramName = digestId(wire.target.port);
+ }
+ if (paramName && paramsNames.indexOf(paramName) == -1) {
+ paramsNames.push(paramName);
+ param += ' .' + paramName;
+ param += '(w' + w + ')';
+ params.push(param);
+ }
+ }
+
+ instances.push(params.join(',\n') + '\n);');
+ }
+ }
+ content += instances.join('\n');
+
+ return content;
+ }
+
+ function verilogCompiler(name, project) {
+ var code = '';
+
+ if (project &&
+ project.graph) {
+
+ // Main module
+
+ if (name) {
+ var data = {
+ name: name,
+ ports: getPorts(project),
+ content: getContent(name, project)
+ };
+ code += module(data);
+ }
+
+ // Dependencies modules
+
+ for (var d in project.deps) {
+ code += verilogCompiler(name + '_' + digestId(d, true), project.deps[d]);
+ }
+
+ // Code modules
+
+ for (var i in project.graph.blocks) {
+ var block = project.graph.blocks[i];
+ if (block) {
+ if (block.type == 'basic.code') {
+ var data = {
+ name: name + '_' + digestId(block.type, true) + '_' + digestId(block.id),
+ ports: block.data.ports,
+ content: block.data.code
+ }
+ code += module(data);
+ }
+ }
+ }
+ }
+
+ return code;
+ }
+
+ function pcfCompiler(project) {
+ var code = '';
+
+ for (var i in project.graph.blocks) {
+ var block = project.graph.blocks[i];
+ if (block.type == 'basic.input' ||
+ block.type == 'basic.output') {
+ code += 'set_io ';
+ code += digestId(block.id);
+ code += ' ';
+ code += block.data.pin.value;
+ code += '\n';
+ }
+ }
+
+ return code;
+ }
+
+ }]);
diff --git a/app/scripts/services/graph.service.js b/app/scripts/services/graph.service.js
new file mode 100644
index 000000000..5069a2b28
--- /dev/null
+++ b/app/scripts/services/graph.service.js
@@ -0,0 +1,876 @@
+'use strict';
+
+angular.module('icestudio')
+ .service('graph', ['$rootScope', 'nodeFs', 'joint', 'boards', 'nodeSha1',
+ function($rootScope, nodeFs, joint, boards, nodeSha1) {
+
+ // Variables
+
+ var zIndex = 100;
+ var ctrlPressed = false;
+
+ var graph = null;
+ var paper = null;
+ var selection = null;
+ var selectionView = null;
+
+ var dependencies = {};
+ this.breadcrumbs = [{ name: '' }];
+
+ var gridsize = 8;
+ var state = {
+ pan: {
+ x: 0,
+ y: 0
+ },
+ zoom: 1
+ };
+
+ // Functions
+
+ $(document).on('keydown', function(event) {
+ ctrlPressed = event.keyCode == 17;
+ });
+
+ this.getState = function() {
+ // Clone state
+ return JSON.parse(JSON.stringify(state));
+ }
+
+ this.setState = function(_state) {
+ if (!_state) {
+ _state = {
+ pan: {
+ x: 0,
+ y: 0
+ },
+ zoom: 1
+ };
+ }
+ this.panAndZoom.zoom(_state.zoom);
+ this.panAndZoom.pan(_state.pan);
+ setGrid(paper, gridsize*2*_state.zoom, '#777', _state.pan);
+ }
+
+ this.resetState = function() {
+ this.setState(null);
+ }
+
+ function setGrid(paper, size, color, offset) {
+ // Set grid size on the JointJS paper object (joint.dia.Paper instance)
+ paper.options.gridsize = gridsize;
+ // Draw a grid into the HTML 5 canvas and convert it to a data URI image
+ var canvas = $('
', { width: size, height: size });
+ canvas[0].width = size;
+ canvas[0].height = size;
+ var context = canvas[0].getContext('2d');
+ context.beginPath();
+ context.rect(1, 1, 1, 1);
+ context.fillStyle = color || '#AAAAAA';
+ context.fill();
+ // Finally, set the grid background image of the paper container element.
+ var gridBackgroundImage = canvas[0].toDataURL('image/png');
+ $(paper.el.childNodes[0]).css(
+ 'background-image', 'url("' + gridBackgroundImage + '")');
+ if(typeof(offset) != 'undefined'){
+ $(paper.el.childNodes[0]).css(
+ 'background-position', offset.x + 'px ' + offset.y + 'px');
+ }
+ }
+
+ this.createPaper = function(element) {
+ graph = new joint.dia.Graph();
+ paper = new joint.dia.Paper({
+ el: element,
+ width: 2000,
+ height: 1000,
+ model: graph,
+ gridSize: gridsize,
+ snapLinks: { radius: 15 },
+ linkPinning: false,
+ embeddingMode: false,
+ //markAvailable: true,
+ defaultLink: new joint.shapes.ice.Wire(),
+ guard: function(evt, view) {
+ // FALSE means the event isn't guarded.
+ return false;
+ },
+ validateMagnet: function(cellView, magnet) {
+ // Prevent to start wires from an input port
+ return (magnet.getAttribute('type') == 'output');
+ },
+ validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
+ // Prevent output-output links
+ if (magnetS.getAttribute('type') == 'output' &&
+ magnetT.getAttribute('type') == 'output')
+ return false;
+ // Prevent multiple input links
+ var links = graph.getLinks();
+ for (var i in links) {
+ if (linkView == links[i].findView(paper)) //Skip the wire the user is drawing
+ continue;
+ if ((cellViewT.model.id == links[i].get('target').id) &&
+ (magnetT.getAttribute('port') == links[i].get('target').port)) {
+ return false;
+ }
+ }
+ // Ensure input -> input-config connections
+ if (cellViewT.model.attributes.blockType == 'config.Input-config') {
+ return (cellViewS.model.attributes.blockType == 'basic.input');
+ }
+ // Prevent loop links
+ return magnetS !== magnetT;
+ }
+ });
+
+ setGrid(paper, gridsize * 2, '#777');
+
+ var targetElement= element[0];
+
+ this.panAndZoom = svgPanZoom(targetElement.childNodes[0],
+ {
+ viewportSelector: targetElement.childNodes[0].childNodes[0],
+ fit: false,
+ center: false,
+ zoomEnabled: true,
+ panEnabled: false,
+ zoomScaleSensitivity: 0.2,
+ dblClickZoomEnabled: false,
+ minZoom: 0.5,
+ maxZoom: 2,
+ beforeZoom: function(oldzoom, newzoom) {
+ },
+ onZoom: function(scale) {
+ state.zoom = scale;
+ setGrid(paper, gridsize*2*state.zoom, '#777');
+ // Already rendered in pan
+ },
+ beforePan: function(oldpan, newpan) {
+ setGrid(paper, gridsize*2*state.zoom, '#777', newpan);
+ },
+ onPan: function(newPan) {
+ state.pan = newPan;
+ selectionView.options.state = state;
+
+ var cells = graph.getCells();
+
+ _.each(cells, function(cell) {
+ if (!cell.isLink()) {
+ cell.attributes.state = state;
+ var elementView = paper.findViewByModel(cell);
+ // Pan blocks
+ elementView.updateBox();
+ // Pan selection boxes
+ selectionView.updateBox(elementView.model);
+ }
+ });
+ }
+ });
+
+ selection = new Backbone.Collection;
+ selectionView = new joint.ui.SelectionView({
+ paper: paper,
+ graph: graph,
+ model: selection,
+ state: state
+ });
+
+ // Events
+
+ selectionView.on('selection-box:pointerdown', function(evt) {
+ // Selection to top view
+ if (selection) {
+ selection.each(function(cell) {
+ var cellView = paper.findViewByModel(cell);
+ if (cellView) {
+ if (!cellView.model.isLink()) {
+ if (cellView.$box.css('z-index') < zIndex) {
+ cellView.$box.css('z-index', ++zIndex);
+ }
+ }
+ }
+ });
+ }
+ // Toggle selection
+ if ((evt.which == 3) && (evt.ctrlKey || evt.metaKey)) {
+ var cell = selection.get($(evt.target).data('model'));
+ selection.reset(selection.without(cell));
+ selectionView.destroySelectionBox(paper.findViewByModel(cell));
+ }
+ });
+
+ paper.on('cell:pointerup',
+ function(cellView, evt, x, y) {
+ if (paper.options.interactive) {
+ if (!cellView.model.isLink()) {
+ if (evt.which == 3) {
+ // Disable current focus
+ document.activeElement.blur();
+ // Right button
+ selection.add(cellView.model);
+ selectionView.createSelectionBox(cellView);
+ cellView.$box.removeClass('highlight');
+ }
+ }
+ }
+ }
+ );
+
+ paper.on('cell:pointerdown',
+ function(cellView, evt, x, y) {
+ if (paper.options.interactive) {
+ if (!cellView.model.isLink()) {
+ if (cellView.$box.css('z-index') < zIndex) {
+ cellView.$box.css('z-index', ++zIndex);
+ }
+ }
+ }
+ }
+ );
+
+ paper.on('cell:pointerdblclick',
+ (function(_this) {
+ return function(cellView, evt, x, y) {
+ var data = cellView.model.attributes;
+ if (data.blockType == 'basic.input' ||
+ data.blockType == 'basic.output') {
+ if (paper.options.interactive) {
+ alertify.prompt('Insert the block label', '',
+ function(evt, label) {
+ data.data.label = label;
+ cellView.renderLabel();
+ alertify.success('Label updated');
+ });
+ }
+ }
+ else if (data.blockType == 'basic.code') {
+ if (paper.options.interactive) {
+ var block = {
+ data: {
+ code: _this.getContent(cellView.model.id)
+ },
+ position: cellView.model.attributes.position
+ };
+ _this.createBlock('basic.code', block, function() {
+ cellView.model.remove();
+ });
+ }
+ }
+ else if (data.type != 'ice.Wire' && data.type != 'ice.Info') {
+ _this.breadcrumbs.push({ name: data.blockType });
+ if(!$rootScope.$$phase) {
+ $rootScope.$apply();
+ }
+ var disabled = true;
+ zIndex = 1;
+ if (_this.breadcrumbs.length == 2) {
+ $rootScope.$broadcast('refreshProject', function() {
+ _this.loadGraph(dependencies[data.blockType], disabled);
+ _this.appEnable(false);
+ });
+ }
+ else {
+ _this.loadGraph(dependencies[data.blockType], disabled);
+ _this.appEnable(false);
+ }
+ }
+ }
+ })(this)
+ );
+
+ paper.on('blank:pointerdown',
+ (function(_this) {
+ return function(evt, x, y) {
+ // Disable current focus
+ document.activeElement.blur();
+
+ if (paper.options.interactive) {
+ if (evt.which == 3) {
+ // Right button
+ selectionView.startSelecting(evt, x, y);
+ }
+ else if (evt.which == 1) {
+ // Left button
+ _this.panAndZoom.enablePan();
+ }
+ }
+ }
+ })(this)
+ );
+
+ paper.on('cell:pointerup blank:pointerup',
+ (function(_this) {
+ return function(cellView, evt) {
+ _this.panAndZoom.disablePan();
+ }
+ })(this)
+ );
+
+ paper.on('cell:mouseover',
+ function(cellView, evt) {
+ if (!cellView.model.isLink()) {
+ cellView.$box.addClass('highlight');
+ }
+ }
+ );
+
+ paper.on('cell:mouseout',
+ function(cellView, evt) {
+ if (!cellView.model.isLink()) {
+ cellView.$box.removeClass('highlight');
+ }
+ }
+ );
+
+ graph.on('change:position', function(cell) {
+ if (!selectionView.isTranslating()) {
+ // Update wires on obstacles motion
+ var cells = graph.getCells();
+ for (var i in cells) {
+ var cell = cells[i];
+ if (cell.isLink()) {
+ paper.findViewByModel(cell).update();
+ }
+ }
+ }
+ });
+ };
+
+ this.clearAll = function() {
+ graph.clear();
+ this.appEnable(true);
+ selection.reset();
+ selectionView.cancelSelection();
+ };
+
+ this.appEnable = function(value) {
+ paper.options.interactive = value;
+ var cells = graph.getCells();
+ for (var i in cells) {
+ paper.findViewByModel(cells[i].id).options.interactive = value;
+ }
+ if (value) {
+ angular.element('#menu').removeClass('disable-menu');
+ angular.element('#paper').css('opacity', '1.0');
+ this.panAndZoom.enableZoom();
+ }
+ else {
+ angular.element('#menu').addClass('disable-menu');
+ angular.element('#paper').css('opacity', '0.5');
+ this.panAndZoom.disableZoom();
+ }
+ };
+
+ this.createBlock = function(type, block, callback) {
+ var blockInstance = {
+ id: null,
+ data: {},
+ type: type,
+ position: { x: 4 * gridsize, y: 4 * gridsize }
+ };
+
+ if (type == 'basic.code') {
+ alertify.prompt('Insert the block i/o', 'a,b c',
+ function(evt, ports) {
+ if (ports) {
+ blockInstance.data = {
+ code: '',
+ ports: { in: [], out: [] }
+ };
+ // Parse ports
+ var inPorts = [];
+ var outPorts = [];
+ if (ports.split(' ').length > 0) {
+ inPorts = ports.split(' ')[0].split(',');
+ }
+ if (ports.split(' ').length > 1) {
+ outPorts = ports.split(' ')[1].split(',');
+ }
+
+ for (var i in inPorts) {
+ if (inPorts[i])
+ blockInstance.data.ports.in.push(inPorts[i]);
+ }
+ for (var o in outPorts) {
+ if (outPorts[o])
+ blockInstance.data.ports.out.push(outPorts[o]);
+ }
+ blockInstance.position.x = 31 * gridsize;
+
+ if (block) {
+ blockInstance.data.code = block.data.code;
+ blockInstance.position = block.position;
+ }
+ var cell = addBasicCodeBlock(blockInstance);
+ var cellView = paper.findViewByModel(cell);
+ if (cellView.$box.css('z-index') < zIndex) {
+ cellView.$box.css('z-index', ++zIndex);
+ }
+
+ if (callback)
+ callback();
+ }
+ });
+ }
+ else if (type == 'basic.info') {
+ blockInstance.data = {
+ info: ''
+ };
+ blockInstance.position.x = 31 * gridsize;
+ blockInstance.position.y = 26 * gridsize;
+ var cell = addBasicInfoBlock(blockInstance);
+ var cellView = paper.findViewByModel(cell);
+ if (cellView.$box.css('z-index') < zIndex) {
+ cellView.$box.css('z-index', ++zIndex);
+ }
+ }
+ else if (type == 'basic.input') {
+ alertify.prompt('Insert the block name', 'i',
+ function(evt, name) {
+ if (name) {
+ var names = name.split(' ');
+ for (var n in names) {
+ if (names[n]) {
+ blockInstance.data = {
+ label: names[n],
+ pin: {
+ name: '',
+ value: 0
+ }
+ };
+ var cell = addBasicInputBlock(blockInstance);
+ var cellView = paper.findViewByModel(cell);
+ if (cellView.$box.css('z-index') < zIndex) {
+ cellView.$box.css('z-index', ++zIndex);
+ }
+ blockInstance.position.y += 10 * gridsize;
+ }
+ }
+ }
+ else {
+ blockInstance.data = {
+ label: '',
+ pin: {
+ name: '',
+ value: 0
+ }
+ };
+ var cell = addBasicInputBlock(blockInstance);
+ var cellView = paper.findViewByModel(cell);
+ if (cellView.$box.css('z-index') < zIndex) {
+ cellView.$box.css('z-index', ++zIndex);
+ }
+ blockInstance.position.y += 10 * gridsize;
+ }
+ });
+ }
+ else if (type == 'basic.output') {
+ alertify.prompt('Insert the block name', 'o',
+ function(evt, name) {
+ if (name) {
+ var names = name.split(' ');
+ blockInstance.position.x = 95 * gridsize;
+ for (var n in names) {
+ if (names[n]) {
+ blockInstance.data = {
+ label: names[n],
+ pin: {
+ name: '',
+ value: 0
+ }
+ };
+ var cell = addBasicOutputBlock(blockInstance);
+ var cellView = paper.findViewByModel(cell);
+ if (cellView.$box.css('z-index') < zIndex) {
+ cellView.$box.css('z-index', ++zIndex);
+ }
+ blockInstance.position.y += 10 * gridsize;
+ }
+ }
+ }
+ else {
+ blockInstance.position.x = 95 * gridsize;
+ blockInstance.data = {
+ label: '',
+ pin: {
+ name: '',
+ value: 0
+ }
+ };
+ var cell = addBasicOutputBlock(blockInstance);
+ var cellView = paper.findViewByModel(cell);
+ if (cellView.$box.css('z-index') < zIndex) {
+ cellView.$box.css('z-index', ++zIndex);
+ }
+ blockInstance.position.y += 10 * gridsize;
+ }
+ });
+ }
+ else {
+ if (block &&
+ block.graph &&
+ block.graph.blocks &&
+ block.graph.wires &&
+ block.deps) {
+ dependencies[type] = block;
+ blockInstance.position.x = 6 * gridsize;
+ blockInstance.position.y = 16 * gridsize;
+ var cell = addGenericBlock(blockInstance, block);
+ var cellView = paper.findViewByModel(cell);
+ if (cellView.$box.css('z-index') < zIndex) {
+ cellView.$box.css('z-index', ++zIndex);
+ }
+ }
+ else {
+ alertify.error('Wrong block format: ' + type);
+ }
+ }
+ };
+
+ this.toJSON = function() {
+ return graph.toJSON();
+ }
+
+ this.getContent = function(id) {
+ return paper.findViewByModel(id).$box.find(
+ '#content' + sha1(id).toString().substring(0, 6)).val();
+ }
+
+ this.resetIOChoices = function() {
+ var cells = graph.getCells();
+ // Reset choices in all i/o blocks
+ for (var i in cells) {
+ var cell = cells[i];
+ var type = cell.attributes.blockType;
+ if (type == 'basic.input' || type == 'basic.output') {
+ cell.attributes.choices = boards.getPinout();
+ var view = paper.findViewByModel(cell.id);
+ view.renderChoices();
+ view.clearValue();
+ }
+ }
+ }
+
+ this.cloneSelected = function() {
+ if (selection) {
+ selection.each((function(_this) {
+ return function(cell) {
+ var newCell = cell.clone();
+ var type = cell.attributes.blockType;
+ var content = _this.getContent(cell.id);
+ if (type == 'basic.code') {
+ newCell.attributes.data.code = content;
+ }
+ else if (type == 'basic.info') {
+ newCell.attributes.data.info = content;
+ }
+ newCell.translate(6 * gridsize, 6 * gridsize);
+ addCell(newCell);
+ if (type == 'config.Input-config') {
+ paper.findViewByModel(newCell).$box.addClass('config-block');
+ }
+ var cellView = paper.findViewByModel(newCell);
+ if (cellView.$box.css('z-index') < zIndex) {
+ cellView.$box.css('z-index', ++zIndex);
+ }
+ selection.reset(selection.without(cell));
+ selectionView.cancelSelection();
+ };
+ })(this));
+ }
+ }
+
+ this.hasSelection = function() {
+ return selection.length > 0;
+ }
+
+ this.removeSelected = function(removeDep) {
+ if (selection) {
+ selection.each(function(cell) {
+ selection.reset(selection.without(cell));
+ selectionView.cancelSelection();
+ var type = cell.attributes.blockType;
+ cell.remove();
+ if (!typeInGraph(type)) {
+ // Check if it is the last "type" block
+ if (removeDep) {
+ // Remove "type" dependency in the project
+ removeDep(type);
+ }
+ }
+ });
+ }
+ }
+
+ function typeInGraph(type) {
+ var cells = graph.getCells();
+ for (var i in cells) {
+ if (cells[i].attributes.blockType == type) {
+ return true;
+ }
+ }
+ return false;
+ };
+
+ this.isEmpty = function() {
+ return (graph.getCells().length == 0);
+ }
+
+ this.isEnabled = function() {
+ return paper.options.interactive;
+ }
+
+ this.loadGraph = function(project, disabled) {
+ if (project &&
+ project.graph &&
+ project.graph.blocks &&
+ project.graph.wires &&
+ project.deps) {
+
+ var blockInstances = project.graph.blocks;
+ var wires = project.graph.wires;
+ var deps = project.deps;
+
+ dependencies = project.deps;
+
+ this.clearAll();
+
+ this.setState(project.state);
+
+ // Blocks
+ for (var i in blockInstances) {
+ var blockInstance = blockInstances[i];
+ if (blockInstance.type == 'basic.code') {
+ addBasicCodeBlock(blockInstance, disabled);
+ }
+ else if (blockInstance.type == 'basic.info') {
+ addBasicInfoBlock(blockInstance, disabled);
+ }
+ else if (blockInstance.type == 'basic.input') {
+ addBasicInputBlock(blockInstance, disabled);
+ }
+ else if (blockInstance.type == 'basic.output') {
+ addBasicOutputBlock(blockInstance, disabled);
+ }
+ else {
+ addGenericBlock(blockInstance, deps[blockInstance.type]);
+ }
+ }
+
+ // Wires
+ for (var i in wires) {
+ addWire(wires[i]);
+ }
+
+ return true;
+ }
+ }
+
+ this.importBlock = function(type, block) {
+ var blockInstance = {
+ id: null,
+ data: {},
+ type: type,
+ position: { x: 6 * gridsize, y: 16 * gridsize }
+ }
+ dependencies[type] = block;
+ var cell = addGenericBlock(blockInstance, block);
+ var cellView = paper.findViewByModel(cell);
+ if (cellView.$box.css('z-index') < zIndex) {
+ cellView.$box.css('z-index', ++zIndex);
+ }
+ }
+
+ function addBasicInputBlock(blockInstances, disabled) {
+ var cell = new joint.shapes.ice.Input({
+ id: blockInstances.id,
+ blockType: blockInstances.type,
+ data: blockInstances.data,
+ label: blockInstances.data.label,
+ position: blockInstances.position,
+ disabled: disabled,
+ choices: boards.getPinout()
+ });
+
+ addCell(cell);
+ return cell;
+ };
+
+ function addBasicOutputBlock(blockInstances, disabled) {
+ var cell = new joint.shapes.ice.Output({
+ id: blockInstances.id,
+ blockType: blockInstances.type,
+ data: blockInstances.data,
+ label: blockInstances.data.label,
+ position: blockInstances.position,
+ disabled: disabled,
+ choices: boards.getPinout()
+ });
+
+ addCell(cell);
+ return cell;
+ };
+
+ function addBasicCodeBlock(blockInstances, disabled) {
+ var inPorts = [];
+ var outPorts = [];
+
+ for (var i in blockInstances.data.ports.in) {
+ inPorts.push({
+ id: blockInstances.data.ports.in[i],
+ label: blockInstances.data.ports.in[i],
+ gridUnits: 32
+ });
+ }
+
+ for (var o in blockInstances.data.ports.out) {
+ outPorts.push({
+ id: blockInstances.data.ports.out[o],
+ label: blockInstances.data.ports.out[o],
+ gridUnits: 32
+ });
+ }
+
+ var cell = new joint.shapes.ice.Code({
+ id: blockInstances.id,
+ blockType: blockInstances.type,
+ data: blockInstances.data,
+ position: blockInstances.position,
+ disabled: disabled,
+ inPorts: inPorts,
+ outPorts: outPorts
+ });
+
+ addCell(cell);
+ return cell;
+ };
+
+ function addBasicInfoBlock(blockInstances, disabled) {
+ var cell = new joint.shapes.ice.Info({
+ id: blockInstances.id,
+ blockType: blockInstances.type,
+ data: blockInstances.data,
+ position: blockInstances.position,
+ disabled: disabled
+ });
+
+ addCell(cell);
+ return cell;
+ };
+
+ function addGenericBlock(blockInstance, block) {
+ var inPorts = [];
+ var outPorts = [];
+
+ for (var i in block.graph.blocks) {
+ var item = block.graph.blocks[i];
+ if (item.type == 'basic.input') {
+ inPorts.push({
+ id: item.id,
+ label: item.data.label
+ });
+ }
+ else if (item.type == 'basic.output') {
+ outPorts.push({
+ id: item.id,
+ label: item.data.label
+ });
+ }
+ }
+
+ var numPorts = Math.max(inPorts.length, outPorts.length);
+ var height = Math.max(4 * gridsize * numPorts, 8 * gridsize);
+
+ var gridUnits = height / gridsize;
+
+ for (var i in inPorts) {
+ inPorts[i].gridUnits = gridUnits;
+ }
+ for (var o in outPorts) {
+ outPorts[o].gridUnits = gridUnits;
+ }
+
+
+ var blockLabel = blockInstance.type.toUpperCase();
+ var width = Math.min((blockLabel.length + 8) * gridsize, 24 * gridsize);
+ if (blockInstance.type.indexOf('.') != -1) {
+ blockLabel = [
+ blockInstance.type.split('.')[0],
+ blockInstance.type.split('.')[1].toUpperCase()
+ ].join('');
+ }
+
+ var blockImage = '';
+ if (block.image &&
+ nodeFs.existsSync(block.image) &&
+ nodeFs.lstatSync(block.image).isFile()) {
+ blockImage = block.image;
+ width = 12 * gridsize;
+ }
+
+ var cell = new joint.shapes.ice.Generic({
+ id: blockInstance.id,
+ blockType: blockInstance.type,
+ data: {},
+ image: blockImage,
+ label: blockLabel,
+ position: blockInstance.position,
+ inPorts: inPorts,
+ outPorts: outPorts,
+ size: {
+ width: width,
+ height: height
+ }
+ });
+
+ addCell(cell);
+
+ if (blockInstance.type == 'config.Input-config') {
+ paper.findViewByModel(cell).$box.addClass('config-block');
+ }
+
+ return cell;
+ }
+
+ function addWire(wire) {
+ var source = graph.getCell(wire.source.block);
+ var target = graph.getCell(wire.target.block);
+
+ // Find selectors
+ var sourceSelector, targetSelector;
+ for (var _out = 0; _out < source.attributes.outPorts.length; _out++) {
+ if (source.attributes.outPorts[_out] == wire.source.port) {
+ sourcePort = _out;
+ break;
+ }
+ }
+ for (var _in = 0; _in < source.attributes.inPorts.length; _in++) {
+ if (target.attributes.inPorts[_in] == wire.target.port) {
+ targetPort = _in;
+ break;
+ }
+ }
+
+ var _wire = new joint.shapes.ice.Wire({
+ source: {
+ id: source.id,
+ selector: sourceSelector,
+ port: wire.source.port
+ },
+ target: {
+ id: target.id,
+ selector: targetSelector,
+ port: wire.target.port
+ },
+ vertices: wire.vertices
+ });
+
+ addCell(_wire);
+ }
+
+ function addCell(cell) {
+ cell.attributes.state = state;
+ graph.addCell(cell);
+ }
+
+ }]);
diff --git a/app/scripts/services/profile.service.js b/app/scripts/services/profile.service.js
new file mode 100644
index 000000000..ba2977d1c
--- /dev/null
+++ b/app/scripts/services/profile.service.js
@@ -0,0 +1,35 @@
+'use strict';
+
+angular.module('icestudio')
+ .service('profile', function(nodeFs, nodePath, utils) {
+
+ const BASE_DIR = process.env.HOME || process.env.USERPROFILE;
+ const ICESTUDIO_DIR = nodePath.join(BASE_DIR, '.icestudio');
+ const PROFILE_PATH = nodePath.join(ICESTUDIO_DIR, 'profile.json');
+
+ this.data = {
+ 'language': 'en'
+ }
+
+ this.load = function(callback) {
+ utils.readFile(PROFILE_PATH, (function(_this) {
+ return function(data) {
+ if (data) {
+ _this.data = data;
+ }
+ if (callback)
+ callback()
+ console.log('Profile loaded');
+ };
+ })(this));
+ }
+
+ this.save = function() {
+ if (!nodeFs.existsSync(ICESTUDIO_DIR))
+ nodeFs.mkdirSync(ICESTUDIO_DIR);
+ utils.saveFile(PROFILE_PATH, this.data, function() {
+ console.log('Profile saved');
+ }, true);
+ }
+ }
+ );
diff --git a/app/scripts/services/resources.service.js b/app/scripts/services/resources.service.js
new file mode 100644
index 000000000..62832c6a1
--- /dev/null
+++ b/app/scripts/services/resources.service.js
@@ -0,0 +1,19 @@
+'use strict';
+
+angular.module('icestudio')
+ .service('resources', ['nodePath', 'utils',
+ function(nodePath, utils) {
+
+ this.getExamples = function() {
+ return utils.getFilesRecursive(nodePath.join('resources', 'examples'), '.ice');
+ }
+
+ this.getTemplates = function() {
+ return utils.getFilesRecursive(nodePath.join('resources', 'templates'), '.ice');
+ }
+
+ this.getMenuBlocks = function() {
+ return utils.getFilesRecursive(nodePath.join('resources', 'blocks'), '.iceb');
+ }
+
+ }]);
diff --git a/app/scripts/services/tools.service.js b/app/scripts/services/tools.service.js
new file mode 100644
index 000000000..4d5ba4032
--- /dev/null
+++ b/app/scripts/services/tools.service.js
@@ -0,0 +1,337 @@
+'use strict';
+
+angular.module('icestudio')
+ .service('tools', ['nodeFs', 'nodeOs', 'nodePath', 'nodeProcess', 'nodeChildProcess', 'nodePing', 'common', 'boards', 'compiler', 'utils',
+ function(nodeFs, nodeOs, nodePath, nodeProcess, nodeChildProcess, nodePing, common, boards, compiler, utils) {
+
+ var currentAlert = null;
+ var toolchain = { installed: false };
+
+ this.toolchain = toolchain;
+ this.buildPath = '_build';
+ this.currentProjectPath = '';
+
+ checkToolchain();
+
+ this.verifyCode = function() {
+ this.apio(['verify'], false);
+ };
+
+ this.buildCode = function() {
+ this.apio(['build', '--board', boards.selectedBoard.id], true);
+ };
+
+ this.uploadCode = function() {
+ this.apio(['upload', '--board', boards.selectedBoard.id], true);
+ };
+
+ this.apio = function(commands, checkFiles) {
+ var check = true;
+ var code = this.generateCode();
+ if (code) {
+ if (toolchain.installed) {
+ angular.element('#menu').addClass('disable-menu');
+ currentAlert = alertify.notify(commands[0] + ' start...', 'message', 100000);
+ $('body').addClass('waiting');
+ nodeProcess.chdir('_build');
+ if (checkFiles) {
+ check = this.syncVerilogResources(code);
+ }
+ try {
+ if (check) {
+ execute(([utils.getApioExecutable()].concat(commands)).join(' '), commands[0], function() {
+ if (currentAlert) {
+ setTimeout(function() {
+ angular.element('#menu').removeClass('disable-menu');
+ currentAlert.dismiss(true);
+ }, 1000);
+ }
+ });
+ }
+ else {
+ setTimeout(function() {
+ angular.element('#menu').removeClass('disable-menu');
+ currentAlert.dismiss(true);
+ $('body').removeClass('waiting');
+ }, 1000);
+ }
+ }
+ catch(e) {
+ }
+ finally {
+ nodeProcess.chdir('..');
+ }
+ }
+ else {
+ installToolchain();
+ }
+ }
+ }
+
+ function checkToolchain() {
+ var apio = utils.getApioExecutable();
+ var exists = nodeFs.existsSync(apio);
+ if (exists) {
+ nodeChildProcess.exec([apio, 'clean'].join(' '), function(error, stdout, stderr) {
+ if (stdout) {
+ toolchain.installed = (stdout.indexOf('not installed') == -1);
+ }
+ });
+ }
+ }
+
+ this.generateCode = function() {
+ if (!nodeFs.existsSync(this.buildPath))
+ nodeFs.mkdirSync(this.buildPath);
+ common.refreshProject();
+ var verilog = compiler.generateVerilog(common.project);
+ var pcf = compiler.generatePCF(common.project);
+ nodeFs.writeFileSync(nodePath.join(this.buildPath, 'main.v'), verilog, 'utf8');
+ nodeFs.writeFileSync(nodePath.join(this.buildPath, 'main.pcf'), pcf, 'utf8');
+ return verilog;
+ }
+
+ this.syncVerilogResources = function(code) {
+ var ret = true;
+ var files = code.match(/\".*list\"/g);
+
+ if (files && files.length > 0) {
+ // Force rebuild
+ var apio = utils.getApioExecutable();
+ nodeChildProcess.execSync([apio, 'clean'].join(' ')).toString();
+ }
+
+ for (var i in files) {
+
+ var file = files[i].replace(/\"/g, "");
+ var destPath = nodePath.join('.', file);
+ var origPath = nodePath.join(this.currentProjectPath, file);
+
+ try {
+ // Remove link if exists
+ if (nodeFs.existsSync(destPath)) {
+ nodeFs.unlinkSync(destPath);
+ }
+ // Link list file
+ if (nodeFs.existsSync(origPath)) {
+ nodeFs.linkSync(origPath, destPath);
+ }
+ else {
+ // Error: file does not exist
+ alertify.notify('File: ' + file + ' does not exist', 'error', 3);
+ ret = false;
+ break;
+ }
+ }
+ catch (e) {
+ alertify.notify('Error: ' + e.toString(), 'error', 3);
+ ret = false;
+ break;
+ }
+ }
+
+ return ret;
+ }
+
+ this.setProjectPath = function(path) {
+ this.currentProjectPath = path;
+ }
+
+ function execute(command, label, callback) {
+ nodeChildProcess.exec(command, function(error, stdout, stderr) {
+ //console.log(error, stdout, stderr);
+ if (callback)
+ callback();
+ if (label) {
+ if (error) {
+ if (stdout) {
+ if (stdout.indexOf('[upload] Error') != -1 ||
+ stdout.indexOf('Error: board not detected') != -1) {
+ alertify.notify('Board not detected', 'error', 3);
+ }
+ else if (stdout.indexOf('set_io: too few arguments') != -1) {
+ alertify.notify('FPGA I/O not defined', 'error', 3);
+ }
+ else if (stdout.indexOf('error: unknown pin') != -1) {
+ alertify.notify('FPGA I/O not defined', 'error', 3);
+ }
+ else if (stdout.indexOf('error: duplicate pin constraints') != -1) {
+ alertify.notify('Duplicated FPGA I/O', 'error', 3);
+ }
+ else {
+ var stdoutError = stdout.split('\n').filter(isError);
+ function isError(line) {
+ return (line.indexOf('syntax error') != -1 ||
+ line.indexOf('not installed') != -1 ||
+ line.indexOf('error: ') != -1 ||
+ line.indexOf('ERROR: ') != -1 ||
+ line.indexOf('already declared') != -1);
+ }
+ if (stdoutError.length > 0) {
+ alertify.notify(stdoutError[0], 'error', 5);
+ }
+ }
+ }
+ else {
+ alertify.notify(stderr, 'error', 5);
+ }
+ }
+ else {
+ alertify.success(label + ' success');
+ }
+ $('body').removeClass('waiting');
+ }
+ });
+ }
+
+ this.installToolchain = installToolchain;
+
+ function installToolchain() {
+
+ // Configure alert
+ alertify.defaults.closable = false;
+
+ utils.disableClickEvent();
+
+ var content = [
+ '
',
+ '
Installing toolchain
',
+ ' ',
+ '
',
+ '
'].join('\n');
+ alertify.alert(content, function() {
+ setTimeout(function() {
+ initProgress();
+ }, 200);
+ });
+
+ // Install toolchain
+ async.series([
+ ensurePythonIsAvailable,
+ extractVirtualEnv,
+ makeVenvDirectory,
+ ensureInternetConnection,
+ installApio,
+ apioInstallSystem,
+ apioInstallScons,
+ apioInstallIcestorm,
+ apioInstallIverilog,
+ installationCompleted
+ ]);
+
+ // Restore alert
+ alertify.defaults.closable = true;
+ }
+
+ this.removeToolchain = function() {
+ utils.removeToolchain();
+ toolchain.installed = false;
+ }
+
+ function ensurePythonIsAvailable(callback) {
+ updateProgress('Check Python executable...', 0);
+ if (utils.getPythonExecutable()) {
+ callback();
+ }
+ else {
+ errorProgress('Python 2.7 is required');
+ utils.enableClickEvent();
+ callback(true);
+ }
+ }
+
+ function extractVirtualEnv(callback) {
+ updateProgress('Extract virtual env files...', 5);
+ utils.extractVirtualEnv(callback);
+ }
+
+ function makeVenvDirectory(callback) {
+ updateProgress('Make virtual env...', 10);
+ utils.makeVenvDirectory(callback);
+ }
+
+ function ensureInternetConnection(callback) {
+ updateProgress('Check Internet connection...', 20);
+ nodePing.probe('google.com', function(isAlive) {
+ if (isAlive) {
+ callback();
+ }
+ else {
+ errorProgress('Internet connection is required');
+ utils.enableClickEvent();
+ callback(true);
+ }
+ });
+ }
+
+ function installApio(callback) {
+ updateProgress('pip install -U apio', 30);
+ utils.installApio(callback);
+ }
+
+ function apioInstallSystem(callback) {
+ updateProgress('apio install system', 50);
+ utils.apioInstall('system', callback);
+ }
+
+ function apioInstallScons(callback) {
+ updateProgress('apio install scons', 60);
+ utils.apioInstall('scons', callback);
+ }
+
+ function apioInstallIcestorm(callback) {
+ updateProgress('apio install icestorm', 70);
+ utils.apioInstall('icestorm', callback);
+ }
+
+ function apioInstallIverilog(callback) {
+ updateProgress('apio install iverilog', 90);
+ utils.apioInstall('iverilog', callback);
+ }
+
+ function installationCompleted(callback) {
+ updateProgress('Installation completed', 100);
+ alertify.success('Toolchain installed');
+ toolchain.installed = true;
+ utils.enableClickEvent();
+ callback();
+ }
+
+ function updateProgress(message, value) {
+ angular.element('#progress-message')
+ .text(message);
+ var bar = angular.element('#progress-bar')
+ if (value == 100)
+ bar.removeClass('progress-bar-striped active');
+ bar.text(value + '%')
+ bar.attr('aria-valuenow', value)
+ bar.css('width', value + '%');
+ }
+
+ function initProgress() {
+ angular.element('#progress-bar')
+ .addClass('notransition progress-bar-info progress-bar-striped active')
+ .removeClass('progress-bar-danger')
+ .text('0%')
+ .attr('aria-valuenow', 0)
+ .css('width', '0%')
+ .removeClass('notransition');
+
+ }
+
+ function errorProgress(message) {
+ angular.element('#progress-message')
+ .text(message);
+ angular.element('#progress-bar')
+ .addClass('notransition progress-bar-danger')
+ .removeClass('progress-bar-info progress-bar-striped active')
+ .text('Error')
+ .attr('aria-valuenow', 100)
+ .css('width', '100%');
+ }
+
+ }]);
diff --git a/app/scripts/services/utils.service.js b/app/scripts/services/utils.service.js
new file mode 100644
index 000000000..6d734e658
--- /dev/null
+++ b/app/scripts/services/utils.service.js
@@ -0,0 +1,290 @@
+'use strict';
+
+angular.module('icestudio')
+ .service('utils', ['nodeFs', 'nodeOs', 'nodePath', 'nodeChildProcess', 'nodeTarball', 'nodeZlib',
+ function(nodeFs, nodeOs, nodePath, nodeChildProcess, nodeTarball, nodeZlib) {
+
+ const WIN32 = Boolean(nodeOs.platform().indexOf('win32') > -1);
+ const DARWIN = Boolean(nodeOs.platform().indexOf('darwin') > -1);
+
+ const VENV = 'virtualenv-15.0.1';
+ const VENV_DIR = nodePath.join('_build', VENV);
+ const VENV_TARGZ = nodePath.join('resources', 'virtualenv', VENV + '.tar.gz');
+
+ const BASE_DIR = process.env.HOME || process.env.USERPROFILE;
+ const APIO_DIR = nodePath.join(BASE_DIR, '.apio');
+ const ICESTUDIO_DIR = nodePath.join(BASE_DIR, '.icestudio');
+ const ENV_DIR = _get_env_dir(nodePath.join(ICESTUDIO_DIR, 'venv'));
+ const ENV_BIN_DIR = nodePath.join(ENV_DIR, WIN32 ? 'Scripts' : 'bin');
+
+ const ENV_PIP = nodePath.join(ENV_BIN_DIR, 'pip');
+ const ENV_APIO = nodePath.join(ENV_BIN_DIR, WIN32 ? 'apio.exe' : 'apio');
+
+ function _get_env_dir(defaultEnvDir) {
+ if (WIN32) {
+ // Put the env directory to the root of the current local disk when
+ // default path contains non-ASCII characters. Virtualenv will fail to
+ for (var i in defaultEnvDir) {
+ var char = defaultEnvDir[i];
+ if (char.charCodeAt(0) > 127) {
+ var defaultEnvDirFormat = nodeOs.parse(defaultEnvDir);
+ return nodeOs.format({
+ root: defaultEnvDirFormat.root,
+ dir: defaultEnvDirFormat.root,
+ base: '.icestudiovenv',
+ name: '.icestudiovenv',
+ });
+ }
+ }
+ }
+
+ return defaultEnvDir;
+ };
+
+ var _pythonExecutableCached = null;
+ // Get the system executable
+ this.getPythonExecutable = function() {
+ if (!_pythonExecutableCached) {
+ const possibleExecutables = [];
+
+ if (WIN32) {
+ possibleExecutables.push('python.exe');
+ possibleExecutables.push('C:\\Python27\\python.exe');
+ } else {
+ possibleExecutables.push('python2.7');
+ possibleExecutables.push('python');
+ }
+
+ for (var i in possibleExecutables) {
+ var executable = possibleExecutables[i];
+ if (isPython2(executable)) {
+ _pythonExecutableCached = executable;
+ break;
+ }
+ }
+ }
+ return _pythonExecutableCached;
+ };
+
+ function isPython2(executable) {
+ const args = ['-c', 'import sys; print \'.\'.join(str(v) for v in sys.version_info[:2])'];
+ try {
+ const result = nodeChildProcess.spawnSync(executable, args);
+ return 0 === result.status && result.stdout.toString().startsWith('2.7');
+ } catch(e) {
+ return false;
+ }
+ };
+
+ this.extractTargz = function(source, destination, callback) {
+ nodeTarball.extractTarball(source, destination, function(err) {
+ if(err) {
+ //console.log(err);
+ callback(true);
+ }
+ else {
+ callback();
+ }
+ })
+ }
+
+ this.extractVirtualEnv = function(callback) {
+ this.extractTargz(VENV_TARGZ, '_build', callback);
+ }
+
+ function disableClick(e) {
+ e.stopPropagation();
+ e.preventDefault();
+ }
+
+ function enableClickEvent() {
+ document.removeEventListener('click', disableClick, true);
+ }
+
+ function disableClickEvent() {
+ document.addEventListener('click', disableClick, true);
+ }
+
+ this.enableClickEvent = enableClickEvent;
+ this.disableClickEvent = disableClickEvent;
+
+ this.executeCommand = function(command, callback) {
+ nodeChildProcess.exec(command.join(' '),
+ function (error, stdout, stderr) {
+ if (error) {
+ //console.log(error, stdout, stderr);
+ enableClickEvent();
+ callback(true);
+ angular.element('#progress-message')
+ .text('Remove the current toolchain');
+ angular.element('#progress-bar')
+ .addClass('notransition progress-bar-danger')
+ .removeClass('progress-bar-info progress-bar-striped active')
+ .text('Error')
+ .attr('aria-valuenow', 100)
+ .css('width', '100%');
+ }
+ else {
+ callback();
+ }
+ }
+ );
+ }
+
+ this.makeVenvDirectory = function(callback) {
+ if (!nodeFs.existsSync(ICESTUDIO_DIR))
+ nodeFs.mkdirSync(ICESTUDIO_DIR);
+ if (!nodeFs.existsSync(ENV_DIR)) {
+ nodeFs.mkdirSync(ENV_DIR);
+ this.executeCommand(
+ [this.getPythonExecutable(), nodePath.join(VENV_DIR, 'virtualenv.py'), ENV_DIR], callback)
+ }
+ else {
+ callback();
+ }
+ }
+
+ this.installApio = function(callback) {
+ this.executeCommand([ENV_PIP, 'install', '-U', 'apio'], callback);
+ }
+
+ this.apioInstall = function(_package, callback) {
+ this.executeCommand([ENV_APIO, 'install', _package], callback);
+ }
+
+ this.getApioExecutable = function() {
+ return ENV_APIO;
+ }
+
+ this.removeToolchain = function() {
+ deleteFolderRecursive(APIO_DIR);
+ deleteFolderRecursive(ICESTUDIO_DIR);
+ }
+
+ var deleteFolderRecursive = function(path) {
+ if (nodeFs.existsSync(path)) {
+ nodeFs.readdirSync(path).forEach(function(file,index){
+ var curPath = nodePath.join(path, file);
+ if (nodeFs.lstatSync(curPath).isDirectory()) { // recurse
+ deleteFolderRecursive(curPath);
+ }
+ else { // delete file
+ nodeFs.unlinkSync(curPath);
+ }
+ });
+ nodeFs.rmdirSync(path);
+ }
+ }
+
+ this.sep = nodePath.sep;
+
+ this.basename = basename;
+ function basename(filepath) {
+ return nodePath.basename(filepath).split('.')[0];
+ }
+
+ this.dirname = function(filepath) {
+ return nodePath.dirname(filepath);
+ }
+
+ this.readFile = function(filepath, callback) {
+ nodeFs.readFile(filepath,
+ function(err, data) {
+ if (!err && callback) {
+ decompressJSON(data, callback);
+ }
+ });
+ }
+
+ var saveBin = false;
+
+ this.saveFile = function(filepath, content, callback, compress) {
+ if (compress) {
+ compressJSON(content, function(compressed) {
+ nodeFs.writeFile(filepath, compressed, saveBin ? 'binary' : null,
+ function(err) {
+ if (!err && callback) {
+ callback();
+ }
+ });
+ });
+ }
+ else {
+ nodeFs.writeFile(filepath, content, function(err) {
+ if (!err && callback) {
+ callback();
+ }
+ });
+ }
+ }
+
+ function compressJSON(json, callback) {
+ if (!saveBin) {
+ if (callback)
+ callback(JSON.stringify(json, null, 2));
+ }
+ else {
+ var data = JSON.stringify(json);
+ nodeZlib.gzip(data, function (_, result) {
+ if (callback)
+ callback(result);
+ });
+ }
+ }
+
+ function decompressJSON(json, callback) {
+ var data = isJSON(json);
+ if (data) {
+ if (callback)
+ callback(data);
+ }
+ else {
+ nodeZlib.gunzip(json, function(_, uncompressed) {
+ var result = JSON.parse(uncompressed);
+ if (callback)
+ callback(result);
+ });
+ }
+ }
+
+ function isJSON(str) {
+ var result = false;
+ try {
+ result = JSON.parse(str);
+ } catch (e) {
+ return false;
+ }
+ return result;
+ }
+
+ this.getFilesRecursive = getFilesRecursive;
+
+ function getFilesRecursive(folder, extension) {
+ var fileContents = nodeFs.readdirSync(folder),
+ fileTree = [],
+ stats;
+
+ fileContents.forEach(function (fileName) {
+ var filePath = nodePath.join(folder, fileName);
+ stats = nodeFs.lstatSync(filePath);
+
+ if (stats.isDirectory()) {
+ fileTree.push({
+ name: fileName,
+ children: getFilesRecursive(filePath, extension)
+ });
+ } else {
+ if (fileName.endsWith(extension)) {
+ var content = JSON.parse(nodeFs.readFileSync(filePath).toString());
+ fileTree.push({
+ name: basename(fileName),
+ project: content
+ });
+ }
+ }
+ });
+
+ return fileTree;
+ };
+
+ }]);
diff --git a/app/styles/main.css b/app/styles/main.css
new file mode 100644
index 000000000..43b35a1ca
--- /dev/null
+++ b/app/styles/main.css
@@ -0,0 +1,27 @@
+* {
+ -webkit-touch-callout: none; /* iOS Safari */
+ -webkit-user-select: none; /* Chrome/Safari/Opera */
+ -khtml-user-select: none; /* Konqueror */
+ -moz-user-select: none; /* Firefox */
+ -ms-user-select: none; /* Internet Explorer/Edge */
+ user-select: none; /* Non-prefixed version, currently
+ not supported by any browser */
+}
+
+.notransition {
+ -webkit-transition: none !important;
+ -moz-transition: none !important;
+ -o-transition: none !important;
+ -ms-transition: none !important;
+ transition: none !important;
+}
+
+body {
+ overflow: hidden;
+ margin: 0;
+ height: 100%;
+}
+
+body.waiting * {
+ cursor: progress;
+}
diff --git a/app/styles/menu.css b/app/styles/menu.css
new file mode 100644
index 000000000..64eff7b65
--- /dev/null
+++ b/app/styles/menu.css
@@ -0,0 +1,95 @@
+.disable-menu {
+ pointer-events: none;
+}
+
+.navbar {
+ z-index: 1501;
+}
+
+.dropdown-submenu {
+ position: relative;
+}
+
+.dropdown-submenu > .dropdown-menu {
+ top: 0;
+ left: 100%;
+ margin-top: -6px;
+ margin-left: 0px;
+ -webkit-border-radius: 0;
+ -moz-border-radius: 0;
+ border-radius: 0;
+}
+
+.dropdown-submenu:hover > .dropdown-menu {
+ display: block;
+}
+
+.dropdown-submenu > a:after {
+ display: block;
+ content: " ";
+ float: right;
+ width: 0;
+ height: 0;
+ border-color: transparent;
+ border-style: solid;
+ border-width: 5px 0 5px 5px;
+ border-left-color: #ccc;
+ margin-top: 5px;
+ margin-right: -10px;
+}
+
+.dropdown-submenu:hover > a:after {
+ border-left-color: #fff;
+}
+
+.dropdown-submenu.pull-left {
+ float: none;
+}
+
+.dropdown-submenu.pull-left > .dropdown-menu {
+ left: -100%;
+ margin-left: 10px;
+ -webkit-border-radius: 6px 0 6px 6px;
+ -moz-border-radius: 6px 0 6px 6px;
+ border-radius: 6px 0 6px 6px;
+}
+
+.dropdown-submenu-right {
+ position: relative;
+}
+
+.dropdown-submenu-right > .dropdown-menu {
+ top: 0;
+ right: 100%;
+ margin-top: -6px;
+ margin-left: -1px;
+ -webkit-border-radius: 0;
+ -moz-border-radius: 0;
+ border-radius: 0;
+}
+
+.dropdown-submenu-right:hover > .dropdown-menu {
+ display: block;
+}
+
+.dropdown-submenu-right > a:after {
+ display: block;
+ content: " ";
+ float: right;
+ width: 0;
+ height: 0;
+ border-color: transparent;
+ border-style: solid;
+ border-width: 5px 0 5px 5px;
+ border-left-color: #ccc;
+ margin-top: 5px;
+ margin-right: -10px;
+}
+
+.dropdown-submenu-right:hover > a:after {
+ border-left-color: #fff;
+}
+
+.navbar-default .navbar-nav>li>a:focus, .navbar-default .navbar-nav>li>a:hover {
+ color: #777;
+}
diff --git a/app/styles/project.css b/app/styles/project.css
new file mode 100644
index 000000000..b3aba5478
--- /dev/null
+++ b/app/styles/project.css
@@ -0,0 +1,163 @@
+#paper {
+ top: -20px;
+ position: relative;
+ display: inline-block;
+ background: transparent;
+ overflow: hidden;
+ cursor: move;
+}
+
+#paper svg {
+ background: transparent;
+ position: relative;
+ z-index: 0;
+}
+
+#breadcrumbs {
+ position: absolute;
+ bottom: -5px;
+ width: 100%;
+ z-index: 1501;
+}
+
+.generic-block {
+ position: absolute;
+ background: #C0DFEB;
+ border-radius: 5px;
+ border: 2px solid #777;
+ pointer-events: none;
+ -webkit-user-select: none;
+ z-index: 0;
+}
+
+.config-block {
+ background: #FAFAD2;
+}
+
+.generic-block img {
+ position: absolute;
+ margin: auto;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ width: 80%;
+}
+
+.generic-block label {
+ display: block;
+ margin-top: 10px;
+ text-align: center;
+ font-size: 1em;
+}
+
+
+.io-block {
+ position: absolute;
+ background: #FAFAD2;
+ border-radius: 5px;
+ border: 2px solid #777;
+ pointer-events: none;
+ -webkit-user-select: none;
+ z-index: 0;
+}
+
+.io-block label {
+ display: block;
+ margin-top: 4px;
+ text-align: center;
+ font-size: 1em;
+ font-weight: bold
+}
+
+.io-block .select2 {
+ position: absolute;
+ left: 5px;
+ bottom: 5px;
+ width: 82px;
+ pointer-events: auto;
+}
+
+.code-block {
+ position: absolute;
+ background: #C0DFEB;
+ border-radius: 5px;
+ border: 2px solid #777;
+ pointer-events: none;
+ -webkit-user-select: none;
+ z-index: 0;
+}
+
+.code-block .code-editor {
+ position: absolute;
+ margin: auto;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ width: 95%;
+ height: 93%;
+ border-radius: 5px;
+ border: 1px solid #BBB;
+ pointer-events: auto;
+}
+
+.info-block {
+ position: absolute;
+ background: #DDD;
+ border-radius: 5px;
+ border: 2px solid #777;
+ pointer-events: none;
+ -webkit-user-select: none;
+ z-index: 0;
+}
+
+.info-block .info-editor {
+ position: absolute;
+ margin: auto;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ width: 95%;
+ height: 93%;
+ border-radius: 5px;
+ border: 1px solid #BBB;
+ pointer-events: auto;
+}
+
+.port-body:hover {
+ fill: yellow;
+}
+
+.highlight {
+ box-shadow: 0px 0px 30px 0px rgba(200,200,200,1);
+}
+
+.selectionarea {
+ position: absolute;
+ border: 2px solid #EB2222;
+ opacity: .7;
+ overflow: visible;
+ z-index: 1500;
+}
+
+.selectionarea.selected {
+ background-color: transparent;
+ border: none;
+ opacity: 1;
+ cursor: move;
+ /* Position the selection rectangle static so that the selection-boxe are contained within
+ the paper container (which is supposed to be positioned relative). The height 0 !important
+ makes sure the selection rectangle is not-visible, only the selection-boxes inside it (thanks to overflow: visible). */
+ position: static;
+ height: 0 !important;
+}
+
+.selection-box {
+ position: absolute;
+ border: 2px dashed #EB2222;
+ opacity: .7;
+ border-radius: 5px;
+ z-index: 1500;
+}
diff --git a/app/views/main.html b/app/views/main.html
new file mode 100644
index 000000000..4cf38b88f
--- /dev/null
+++ b/app/views/main.html
@@ -0,0 +1,4 @@
+
diff --git a/app/views/menu.html b/app/views/menu.html
new file mode 100644
index 000000000..779d2f80e
--- /dev/null
+++ b/app/views/menu.html
@@ -0,0 +1,233 @@
+
+
+
+
diff --git a/app/views/project.html b/app/views/project.html
new file mode 100644
index 000000000..df3569cd0
--- /dev/null
+++ b/app/views/project.html
@@ -0,0 +1,9 @@
+
diff --git a/doc/images/bq-logo-cc-sa-small-150px.png b/doc/images/bq-logo-cc-sa-small-150px.png
deleted file mode 100644
index a7f91c3fc..000000000
Binary files a/doc/images/bq-logo-cc-sa-small-150px.png and /dev/null differ
diff --git a/doc/images/icestudio-0.2-blink.png b/doc/images/icestudio-0.2-blink.png
new file mode 100644
index 000000000..822ec2756
Binary files /dev/null and b/doc/images/icestudio-0.2-blink.png differ
diff --git a/doc/images/icestudio-0.2-block-inspection.png b/doc/images/icestudio-0.2-block-inspection.png
new file mode 100644
index 000000000..570ec5328
Binary files /dev/null and b/doc/images/icestudio-0.2-block-inspection.png differ
diff --git a/doc/images/icestudio-0.2-counter-inspection.png b/doc/images/icestudio-0.2-counter-inspection.png
new file mode 100644
index 000000000..152c5d80c
Binary files /dev/null and b/doc/images/icestudio-0.2-counter-inspection.png differ
diff --git a/doc/images/icestudio-0.2-crono.png b/doc/images/icestudio-0.2-crono.png
new file mode 100644
index 000000000..e4683873a
Binary files /dev/null and b/doc/images/icestudio-0.2-crono.png differ
diff --git a/doc/images/icestudio-0.2-mux21-inspection.png b/doc/images/icestudio-0.2-mux21-inspection.png
new file mode 100644
index 000000000..280ba1868
Binary files /dev/null and b/doc/images/icestudio-0.2-mux21-inspection.png differ
diff --git a/doc/images/icestudio-0.2-or-inspection.png b/doc/images/icestudio-0.2-or-inspection.png
new file mode 100644
index 000000000..c614bb157
Binary files /dev/null and b/doc/images/icestudio-0.2-or-inspection.png differ
diff --git a/doc/images/icestudio-0.2-project.png b/doc/images/icestudio-0.2-project.png
new file mode 100644
index 000000000..855a9b7cb
Binary files /dev/null and b/doc/images/icestudio-0.2-project.png differ
diff --git a/doc/images/icestudio-logo-label.png b/doc/images/icestudio-logo-label.png
new file mode 100644
index 000000000..faf2a7d45
Binary files /dev/null and b/doc/images/icestudio-logo-label.png differ
diff --git a/doc/images/icestudio-logo-label.svg b/doc/images/icestudio-logo-label.svg
new file mode 100644
index 000000000..cde93a65a
--- /dev/null
+++ b/doc/images/icestudio-logo-label.svg
@@ -0,0 +1,160 @@
+
+
+
+
diff --git a/doc/images/icestudio-logo.icns b/doc/images/icestudio-logo.icns
new file mode 100644
index 000000000..5b214437f
Binary files /dev/null and b/doc/images/icestudio-logo.icns differ
diff --git a/doc/images/icestudio-logo.ico b/doc/images/icestudio-logo.ico
new file mode 100644
index 000000000..f8dbf862d
Binary files /dev/null and b/doc/images/icestudio-logo.ico differ
diff --git a/doc/images/icestudio-logo.svg b/doc/images/icestudio-logo.svg
new file mode 100644
index 000000000..b82c896b1
--- /dev/null
+++ b/doc/images/icestudio-logo.svg
@@ -0,0 +1,137 @@
+
+
+
+
diff --git a/doc/images/installer-background.png b/doc/images/installer-background.png
new file mode 100644
index 000000000..ee40957f6
Binary files /dev/null and b/doc/images/installer-background.png differ
diff --git a/doc/images/installer-background.svg b/doc/images/installer-background.svg
new file mode 100644
index 000000000..375cddac6
--- /dev/null
+++ b/doc/images/installer-background.svg
@@ -0,0 +1,674 @@
+
+
+
+
diff --git a/doc/images/main.png b/doc/images/main.png
new file mode 100644
index 000000000..554ce0359
Binary files /dev/null and b/doc/images/main.png differ
diff --git a/gruntfile.js b/gruntfile.js
new file mode 100644
index 000000000..0ebd391de
--- /dev/null
+++ b/gruntfile.js
@@ -0,0 +1,246 @@
+module.exports = function(grunt) {
+ var os = require('os');
+
+ const DARWIN = Boolean(os.platform().indexOf('darwin') > -1);
+ if (DARWIN) {
+ var platforms = ['osx64'];
+ var options = { scope: ['devDependencies', 'optionalDependencies'] };
+ var distCommands = ['nwjs', 'appdmg', 'compress:osx64'];
+ }
+ else {
+ var platforms = ['linux32', 'linux64', 'win32', 'win64', 'osx64'];
+ var options = { scope: ['devDependencies'] };
+ var distCommands = ['nwjs', 'compress'];
+ }
+
+ require('load-grunt-tasks')(grunt, options);
+
+ // Project configuration.
+ grunt.initConfig({
+
+ pkg: grunt.file.readJSON('package.json'),
+
+ // Automatically inject Bower components into the app
+ wiredep: {
+ task: {
+ directory: 'app/bower_components',
+ bowerJson: grunt.file.readJSON('app/bower.json'),
+ src: ['index.html']
+ }
+ },
+
+ // Executes nw application
+ exec: {
+ nw: 'node_modules/nw/bin/nw app',
+ stop_NW: 'killall nw || killall nwjs || true'
+ },
+
+ // Reads HTML for usemin blocks to enable smart builds that automatically
+ // concat, minify and revision files. Creates configurations in memory so
+ // additional tasks can operate on them
+ useminPrepare: {
+ html: 'app/index.html',
+ options: {
+ dest: 'dist/tmp'
+ }
+ },
+
+ // Copies dist files
+ copy: {
+ dist: {
+ files: [
+ {
+ expand: true,
+ cwd: 'app',
+ dest: 'dist/tmp',
+ src: [
+ 'index.html',
+ 'package.json',
+ 'resources/**',
+ 'node_modules/**',
+ 'views/*.html'
+ ]
+ },
+ {
+ expand: true,
+ cwd: 'app/bower_components/bootstrap/fonts',
+ dest: 'dist/tmp/fonts/',
+ src: '*.*'
+ }
+ ]
+ }
+ },
+
+ // Uglify configurationoptions:
+ uglify: {
+ options: {
+ mangle: false
+ }
+ },
+
+ // Performs rewrites based on filerev and the useminPrepare configuration
+ usemin: {
+ html: ['dist/tmp/index.html']
+ },
+
+ // Executes nw-build packaging
+ nwjs: {
+ options: {
+ version: '0.12.3',
+ buildDir: 'dist/',
+ winIco: 'doc/images/icestudio-logo.ico',
+ macIcns: 'doc/images/icestudio-logo.icns',
+ macPlist: { 'CFBundleIconFile': 'app.icns' },
+ platforms: platforms
+ },
+ src: ['dist/tmp/**']
+ },
+
+ // ONLY MAC: generates a dmg package
+ appdmg: {
+ options: {
+ basepath: '.',
+ title: 'Icestudio Installer',
+ icon: 'doc/images/icestudio-logo.icns',
+ background: 'doc/images/installer-background.png',
+ window: {
+ size: {
+ width: 512,
+ height: 385,
+ }
+ },
+ contents: [
+ {
+ x: 345,
+ y: 250,
+ type: 'link',
+ path: '/Applications'
+ },
+ {
+ x: 170,
+ y: 250,
+ type: 'file',
+ path: 'dist/Icestudio/osx64/Icestudio.app'
+ }
+ ]
+ },
+ target: {
+ dest: 'dist/<%=pkg.name%>-<%=pkg.version%>-osx64.dmg'
+ }
+ },
+
+ // Compress packages usin zip
+ compress: {
+ linux32: {
+ options: {
+ archive: 'dist/<%=pkg.name%>-<%=pkg.version%>-linux32.zip'
+ },
+ files: [{
+ expand: true,
+ cwd: 'dist/Icestudio/linux32/',
+ src: ['Icestudio', 'icudtl.dat', 'nw.pak', '*.so'],
+ dest: ''
+ }]
+ },
+ linux64: {
+ options: {
+ archive: 'dist/<%=pkg.name%>-<%=pkg.version%>-linux64.zip'
+ },
+ files: [{
+ expand: true,
+ cwd: 'dist/Icestudio/linux64/',
+ src: ['Icestudio', 'icudtl.dat', 'nw.pak', '*.so'],
+ dest: '.'
+ }]
+ },
+ win32: {
+ options: {
+ archive: 'dist/<%=pkg.name%>-<%=pkg.version%>-win32.zip'
+ },
+ files: [{
+ expand: true,
+ cwd: 'dist/Icestudio/win32/',
+ src: ['Icestudio.exe', 'icudtl.dat', 'nw.pak', '*.dll'],
+ dest: '.'
+ }]
+ },
+ win64: {
+ options: {
+ archive: 'dist/<%=pkg.name%>-<%=pkg.version%>-win64.zip'
+ },
+ files: [{
+ expand: true,
+ cwd: 'dist/Icestudio/win64/',
+ src: ['Icestudio.exe', 'icudtl.dat', 'nw.pak', '*.dll'],
+ dest: '.'
+ }]
+ },
+ osx64: {
+ options: {
+ archive: 'dist/<%=pkg.name%>-<%=pkg.version%>-osx64.zip'
+ },
+ files: [{
+ expand: true,
+ cwd: 'dist/Icestudio/osx64/',
+ src: ['Icestudio.app/**'],
+ dest: '.'
+ }]
+ }
+ },
+
+ // Watches files for changes and runs tasks based on the changed files
+ watch: {
+ scripts: {
+ files: [
+ 'app/resources/**/*.*',
+ 'app/scripts/**/*.*',
+ 'app/styles/**/*.*',
+ 'app/views/**/*.*',
+ 'app/*.*',
+ '!app/a.out',
+ '!app/_build'
+ ],
+ tasks: [
+ 'wiredep',
+ 'exec:stop_NW',
+ 'exec:nw'
+ ],
+ options: {
+ atBegin: true,
+ interrupt: true
+ }
+ }
+ },
+
+ // Empties folders to start fresh
+ clean: {
+ tmp: ['.tmp', 'dist/tmp'],
+ dist: ['dist'],
+ // node: ['node_modules'],
+ // appnode: ['app/node_modules'],
+ // appbower: ['app/bower_components'],
+ // cache: ['cache']
+ }
+ });
+
+ // Default tasks.
+ grunt.registerTask('default', function() {
+ console.log('Icestudio');
+ });
+ grunt.registerTask('serve', [
+ 'watch:scripts'
+ ]);
+ grunt.registerTask('dist', [
+ 'clean:dist',
+ 'useminPrepare',
+ 'concat',
+ 'copy:dist',
+ 'uglify',
+ 'cssmin',
+ 'usemin',
+ ]
+ .concat(distCommands)
+ .concat([
+ 'clean:tmp'
+ ]));
+};
diff --git a/icestudio/SConstruct b/icestudio/SConstruct
deleted file mode 100644
index df259525e..000000000
--- a/icestudio/SConstruct
+++ /dev/null
@@ -1,45 +0,0 @@
-import os
-import platform
-from SCons.Script import (Builder, Environment, Default)
-
-EXT = ''
-if 'Windows' == platform.system():
- EXT = '.exe'
-
-TARGET = "gen/main"
-
-JSON = TARGET + ".json"
-PCF = TARGET + ".pcf"
-
-# -- Builder 0 (.json --> .v)
-graph = Builder(action='python build.py $SOURCE',
- suffix='.v',
- src_suffix='.json')
-
-# -- Builder 1 (.v --> .blif)
-synth = Builder(action='yosys{0} -p \"synth_ice40 -blif $TARGET\" $SOURCE'.format(EXT),
- suffix='.blif',
- src_suffix='.v')
-
-# -- Builder 2 (.blif --> .asc)
-pnr = Builder(action='arachne-pnr{0} -d 1k -o $TARGET -p {1} $SOURCE'.format(EXT, PCF),
- suffix='.asc',
- src_suffix='.blif')
-
-# -- Builder 3 (.asc --> .bin)
-bitstream = Builder(action='icepack{0} $SOURCE $TARGET'.format(EXT),
- suffix='.bin',
- src_suffix='.asc')
-
-env = Environment(BUILDERS={'Graph': graph, 'Synth': synth, 'PnR': pnr, 'Bin': bitstream},
- ENV=os.environ)
-
-ver = env.Graph(TARGET, [JSON])
-blif = env.Synth(TARGET, [ver])
-asc = env.PnR(TARGET, [blif, PCF])
-binf = env.Bin(TARGET, asc)
-
-upload = env.Alias('upload', binf, 'iceprog{0} $SOURCE'.format(EXT))
-AlwaysBuild(upload)
-
-Default([binf])
diff --git a/icestudio/build.py b/icestudio/build.py
deleted file mode 100755
index 556776e55..000000000
--- a/icestudio/build.py
+++ /dev/null
@@ -1,246 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-# JSON to verilog compiler
-# February 2016
-# GPLv2
-
-import sys
-import json
-import codecs
-
-from os.path import abspath, dirname, basename, splitext, join
-
-__author__ = 'Jesús Arroyo Torrens
'
-__license__ = 'GNU General Public License v2 http://www.gnu.org/licenses/gpl2.html'
-
-
-class Module:
-
- def __init__(self, name='', _input=[], _output=[], inline=''):
- self.name = name
- self.input = _input
- self.output = _output
- self.inline = inline
-
- def __str__(self):
- code = '\nmodule ' + self.name + '('
- if self.input:
- code += 'input ' + ', '.join(self.input)
- if self.output:
- code += ', '
- if self.output:
- code += 'output ' + ', '.join(self.output)
- code += ');\n'
- code += self.inline
- code += 'endmodule\n'
- return code
-
-
-def generate_verilog_modules(nodes):
- """
- JSON
- {
- "type": "driver",
- "vcode": "...",
- "id": 11,
- ...
- }
-
- Verilog
- vcode value
- """
- code = ''
- types = {}
- # Filter modules
- for node in nodes:
- if node['type'] != 'input' and \
- node['type'] != 'output' and \
- node['type'] != 'linput' and \
- node['type'] != 'loutput' and \
- node['type'] not in types.values():
- types[node['id']] = node['type']
- # Generate modules
- for node in nodes:
- if node['id'] in types:
- code += '\n' + node['vcode']
- return code
-
-
-def generate_verilog_main(name, nodes, connections):
- """
- JSON + name: main
- {
- "nodes": [
- {
- "type": "driver",
- "params": [ { "name": "B", "value": "1'b1"} ],
- "id": 10,
- "outputConnectors": [ { "name": "o" } ]
- },
- {
- "type": "output",
- "params": [ "97" ],
- "id": 11,
- "inputConnectors": [ { "label": "97" } ]
- }
- ],
- "connections": [
- {
- "source": { "nodeID": 10, "connectorIndex": 0 },
- "dest": { "nodeID": 11, "connectorIndex": 0 }
- }
- ]
- }
-
- Verilog
- module main(output output11);
- wire w0;
- assign output11 = w0;
- driver #(
- .B(1'b1)
- )
- driver10 (
- .o(w0)
- );
- endmodule
- """
- _input = _list('input', nodes)
- _output = _list('output', nodes)
- inline = ''
- # Wires
- wires = len(connections)
- if wires > 0:
- for wire in range(wires):
- inline += 'wire w{0};\n'.format(wire)
- # Assign i/o
- for index, connection in enumerate(connections):
- for i in _input:
- if i == 'input' + str(connection['source']['nodeID']):
- inline += 'assign w{0} = {1};\n'.format(index, i)
- for o in _output:
- if o == 'output' + str(connection['dest']['nodeID']):
- inline += 'assign {1} = w{0};\n'.format(index, o)
- # Assign wires (TODO: optimize)
- num = len(connections)
- for i in range(num):
- for j in range(num):
- if i < j:
- ni = connections[i]['source']['nodeID']
- nj = connections[j]['source']['nodeID']
- ci = connections[i]['source']['connectorIndex']
- cj = connections[j]['source']['connectorIndex']
- if ni == nj and ci == cj:
- inline += 'assign w{0} = w{1};\n'.format(i, j)
- # Assign labels and Entities (TODO: optimize)
- for node in nodes:
- if node['type'] == 'linput':
- num = len(connections)
- for i in range(num):
- if node['id'] == connections[i]['source']['nodeID']:
- inline += 'assign w{0} = {1};\n'.format(i, node['outputConnectors'][0]['value'])
- elif node['type'] == 'loutput':
- num = len(connections)
- for i in range(num):
- if node['id'] == connections[i]['dest']['nodeID']:
- inline += 'assign {0} = w{1};\n'.format(node['inputConnectors'][0]['value'], i)
- elif node['type'] != 'input' and node['type'] != 'output':
- inline += node['type']
- # Parameters
- params = []
- if node['params']:
- for param in node['params']:
- params += [' .{0}({1})'.format(param['name'], param['value'])]
- inline += ' #(\n'
- inline += ',\n'.join(params) + '\n'
- inline += ' )\n'
- # Name
- inline += ' ' + node['type'] + str(node['id']) + ' (\n'
- # I/O
- ios = []
- ioh = []
- for index, connection in enumerate(connections):
- if node['id'] == connection['source']['nodeID']:
- io = node['outputConnectors'][connection['source']['connectorIndex']]['name']
- if io not in ioh:
- ioh += [io]
- ios += [' .{0}(w{1})'.format(io, index)]
- if node['id'] == connection['dest']['nodeID']:
- io = node['inputConnectors'][connection['dest']['connectorIndex']]['name']
- if io not in ioh:
- ioh += [io]
- ios += [' .{0}(w{1})'.format(io, index)]
- inline += ',\n'.join(ios) + '\n'
- inline += ');\n'
-
- module = Module(name, _input, _output, inline)
- return str(module)
-
-
-def _list(_type, nodes):
- ret = []
- for node in nodes:
- if node['type'] == _type:
- ret += [_type + str(node['id'])]
- return ret
-
-
-def load_pcf(nodes):
- """
- # JSON
- {
- "type": "input", "params": [ "44" ], "id": 15
- },
- {
- "type": "output", "params": [ "95" ], "id": 16
- }
-
- # PCF
- set_io input15 44
- set_io output16 95
- """
- code = ''
- for n in nodes:
- if n['type'] == 'input' or n['type'] == 'output':
- code += 'set_io {0}{1} {2}\n'.format(n['type'], n['id'], n['params'][0])
- return code
-
-
-def main():
- if len(sys.argv) != 2:
- print('Error: json filename is required')
- return
- else:
- filename = sys.argv[1]
-
- path = abspath(dirname(filename))
- name = splitext(basename(filename))[0]
-
- # Load JSON graph
- with open(filename) as data:
- graph = json.load(data)
- nodes = graph['nodes']
- connections = graph['connections']
- data.close()
-
- # Write Verilog file
- with codecs.open(join(path, name + '.v'), 'w', 'utf-8') as data:
- # Generate Verilog
- code = '// Generated verilog\n'
- code += generate_verilog_modules(nodes)
- code += generate_verilog_main('main', nodes, connections)
- # Write Verilog
- data.write(code)
- data.close()
-
- # Write PCF file
- with open(join(path, name + '.pcf'), 'w') as data:
- # Generate PCF
- code = load_pcf(graph['nodes'])
- # Write PCF
- data.write(code)
- data.close()
-
- print("\nGenerated {0}.v and {0}.pcf [SUCCESS]\n".format(name))
-
-if __name__ == '__main__':
- main()
diff --git a/icestudio/examples/blink.json b/icestudio/examples/blink.json
deleted file mode 100644
index ad20b2747..000000000
--- a/icestudio/examples/blink.json
+++ /dev/null
@@ -1,177 +0,0 @@
-{
- "nodes": [
- {
- "label": "",
- "type": "input",
- "params": [
- "21"
- ],
- "id": 22,
- "x": 108,
- "y": 199,
- "width": 56,
- "outputConnectors": [
- {
- "label": "21"
- }
- ]
- },
- {
- "label": "",
- "type": "loutput",
- "params": [
- "_clk"
- ],
- "id": 23,
- "x": 192,
- "y": 199,
- "width": 72,
- "inputConnectors": [
- {
- "value": "_clk",
- "label": "_clk"
- }
- ]
- },
- {
- "label": "DIV (22)",
- "type": "div",
- "params": [
- {
- "name": "N",
- "value": "22"
- },
- {
- "name": "M",
- "value": 4194304
- }
- ],
- "id": 25,
- "x": 492,
- "y": 250,
- "width": 166,
- "vcode": "module div #(parameter N=22, M=4194304)(input clk, output reg o);\n wire clk_temp;\n reg [N - 1:0] c = 0;\n always @(posedge clk)\n if (M == 0)\n c <= 0;\n else if (c == M - 1)\n c <= 0;\n else\n c <= c + 1;\n assign clk_temp = (c == 0) ? 1 : 0;\n always @(posedge clk)\n if (N == 0)\n o <= 0;\n else if (clk_temp == 1)\n o <= ~o;\nendmodule\n",
- "inputConnectors": [
- {
- "name": "clk",
- "label": "clk"
- }
- ],
- "outputConnectors": [
- {
- "name": "o",
- "label": "out"
- }
- ]
- },
- {
- "label": "",
- "type": "output",
- "params": [
- "95"
- ],
- "id": 26,
- "x": 206,
- "y": 280,
- "width": 56,
- "inputConnectors": [
- {
- "label": "95"
- }
- ]
- },
- {
- "label": "",
- "type": "linput",
- "params": [
- "_led"
- ],
- "id": 27,
- "x": 105,
- "y": 279,
- "width": 72,
- "outputConnectors": [
- {
- "value": "_led",
- "label": "_led"
- }
- ]
- },
- {
- "label": "",
- "type": "linput",
- "params": [
- "_clk"
- ],
- "id": 28,
- "x": 386,
- "y": 249,
- "width": 72,
- "outputConnectors": [
- {
- "value": "_clk",
- "label": "_clk"
- }
- ]
- },
- {
- "label": "",
- "type": "loutput",
- "params": [
- "_led"
- ],
- "id": 29,
- "x": 690,
- "y": 251,
- "width": 72,
- "inputConnectors": [
- {
- "value": "_led",
- "label": "_led"
- }
- ]
- }
- ],
- "connections": [
- {
- "source": {
- "nodeID": 22,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 23,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 27,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 26,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 28,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 25,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 25,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 29,
- "connectorIndex": 0
- }
- }
- ]
-}
\ No newline at end of file
diff --git a/icestudio/examples/blinkdec.json b/icestudio/examples/blinkdec.json
deleted file mode 100644
index ddee88ef7..000000000
--- a/icestudio/examples/blinkdec.json
+++ /dev/null
@@ -1,247 +0,0 @@
-{
- "nodes": [
- {
- "label": "",
- "type": "loutput",
- "params": [
- "_clk"
- ],
- "id": 29,
- "x": 141,
- "y": 128,
- "width": 72,
- "inputConnectors": [
- {
- "value": "_clk",
- "label": "_clk"
- }
- ]
- },
- {
- "label": "",
- "type": "linput",
- "params": [
- "_clk"
- ],
- "id": 31,
- "x": 97,
- "y": 242,
- "width": 72,
- "outputConnectors": [
- {
- "value": "_clk",
- "label": "_clk"
- }
- ]
- },
- {
- "label": "DEC",
- "type": "dec",
- "params": [],
- "vcode": "module dec (input c, output reg o0, o1);\n always @(*)\n begin\n o0 = (c == 0) ? 1 : 0;\n o1 = (c == 1) ? 1 : 0;\n end\nendmodule\n",
- "id": 36,
- "x": 420,
- "y": 242,
- "width": 140,
- "inputConnectors": [
- {
- "name": "c",
- "label": "c"
- }
- ],
- "outputConnectors": [
- {
- "name": "o0",
- "label": "o0"
- },
- {
- "name": "o1",
- "label": "o1"
- }
- ]
- },
- {
- "label": "DIV (22)",
- "type": "div",
- "params": [
- {
- "name": "N",
- "value": "22"
- },
- {
- "name": "M",
- "value": 4194304
- }
- ],
- "id": 37,
- "x": 212,
- "y": 242,
- "width": 166,
- "vcode": "module div #(parameter N=22, M=4194304)(input clk, output reg out);\n wire clk_temp;\n reg [N - 1:0] c = 0;\n always @(posedge clk)\n if (M == 0)\n c <= 0;\n else if (c == M - 1)\n c <= 0;\n else\n c <= c + 1;\n assign clk_temp = (c == 0) ? 1 : 0;\n always @(posedge clk)\n if (N == 0)\n out <= 0;\n else if (clk_temp == 1)\n out <= ~out;\nendmodule\n",
- "inputConnectors": [
- {
- "name": "clk",
- "label": "clk"
- }
- ],
- "outputConnectors": [
- {
- "name": "out",
- "label": "out"
- }
- ]
- },
- {
- "label": "",
- "type": "output",
- "params": [
- "96"
- ],
- "id": 38,
- "x": 646,
- "y": 168,
- "width": 56,
- "inputConnectors": [
- {
- "label": "96"
- }
- ]
- },
- {
- "label": "",
- "type": "output",
- "params": [
- "97"
- ],
- "id": 39,
- "x": 646,
- "y": 228,
- "width": 56,
- "inputConnectors": [
- {
- "label": "97"
- }
- ]
- },
- {
- "label": "",
- "type": "output",
- "params": [
- "98"
- ],
- "id": 40,
- "x": 646,
- "y": 288,
- "width": 56,
- "inputConnectors": [
- {
- "label": "98"
- }
- ]
- },
- {
- "label": "",
- "type": "output",
- "params": [
- "99"
- ],
- "id": 41,
- "x": 646,
- "y": 348,
- "width": 56,
- "inputConnectors": [
- {
- "label": "99"
- }
- ]
- },
- {
- "label": "",
- "type": "input",
- "params": [
- "21"
- ],
- "id": 16,
- "x": 49,
- "y": 127,
- "width": 56,
- "outputConnectors": [
- {
- "label": "21"
- }
- ]
- }
- ],
- "connections": [
- {
- "source": {
- "nodeID": 16,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 29,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 31,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 37,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 36,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 38,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 36,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 39,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 36,
- "connectorIndex": 1
- },
- "dest": {
- "nodeID": 40,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 36,
- "connectorIndex": 1
- },
- "dest": {
- "nodeID": 41,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 37,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 36,
- "connectorIndex": 0
- }
- }
- ]
-}
\ No newline at end of file
diff --git a/icestudio/examples/counter.json b/icestudio/examples/counter.json
deleted file mode 100644
index d4425c095..000000000
--- a/icestudio/examples/counter.json
+++ /dev/null
@@ -1,330 +0,0 @@
-{
- "nodes": [
- {
- "label": "",
- "type": "output",
- "params": [
- "97"
- ],
- "id": 11,
- "x": 531,
- "y": 299,
- "width": 56,
- "inputConnectors": [
- {
- "label": "97"
- }
- ]
- },
- {
- "label": "",
- "type": "output",
- "params": [
- "98"
- ],
- "id": 12,
- "x": 531,
- "y": 359,
- "width": 56,
- "inputConnectors": [
- {
- "label": "98"
- }
- ]
- },
- {
- "label": "",
- "type": "output",
- "params": [
- "99"
- ],
- "id": 13,
- "x": 531,
- "y": 419,
- "width": 56,
- "inputConnectors": [
- {
- "label": "99"
- }
- ]
- },
- {
- "label": "CNT",
- "type": "counter",
- "params": [],
- "vcode": "module counter (input clk, ena, output c0, c1, c2, c3);\n reg [3:0] c = 0;\n always @(posedge clk)\n if (ena)\n c <= c + 1;\n assign c0 = c[0];\n assign c1 = c[1];\n assign c2 = c[2];\n assign c3 = c[3];\nendmodule\n",
- "id": 15,
- "x": 229,
- "y": 303,
- "width": 150,
- "inputConnectors": [
- {
- "name": "clk",
- "label": "clk"
- },
- {
- "name": "ena",
- "label": "ena"
- }
- ],
- "outputConnectors": [
- {
- "name": "c0",
- "label": "c0"
- },
- {
- "name": "c1",
- "label": "c1"
- },
- {
- "name": "c2",
- "label": "c2"
- },
- {
- "name": "c3",
- "label": "c3"
- }
- ]
- },
- {
- "label": "",
- "type": "output",
- "params": [
- "96"
- ],
- "id": 10,
- "x": 530,
- "y": 240,
- "width": 56,
- "inputConnectors": [
- {
- "label": "96"
- }
- ]
- },
- {
- "label": "",
- "type": "input",
- "params": [
- "21"
- ],
- "id": 16,
- "x": 43,
- "y": 134,
- "width": 56,
- "outputConnectors": [
- {
- "label": "21"
- }
- ]
- },
- {
- "label": "TIM (22)",
- "type": "timer",
- "params": [
- {
- "name": "N",
- "value": "22"
- },
- {
- "name": "M",
- "value": 4194304
- }
- ],
- "id": 14,
- "x": 446,
- "y": 140,
- "width": 166,
- "vcode": "module timer #(parameter N=22, M=4194304)(input clk, output wire out);\n reg [N-1:0] c = 0;\n always @(posedge clk)\n c <= (c == M - 1) ? 0 : c + 1;\n assign out = (c == M - 1) ? 1 : 0;\nendmodule\n",
- "inputConnectors": [
- {
- "name": "clk",
- "label": "clk"
- }
- ],
- "outputConnectors": [
- {
- "name": "out",
- "label": "out"
- }
- ]
- },
- {
- "label": "",
- "type": "loutput",
- "params": [
- "_clk"
- ],
- "id": 29,
- "x": 132,
- "y": 135,
- "width": 72,
- "inputConnectors": [
- {
- "value": "_clk",
- "label": "_clk"
- }
- ]
- },
- {
- "label": "",
- "type": "linput",
- "params": [
- "_clk"
- ],
- "id": 31,
- "x": 346,
- "y": 140,
- "width": 72,
- "outputConnectors": [
- {
- "value": "_clk",
- "label": "_clk"
- }
- ]
- },
- {
- "label": "",
- "type": "linput",
- "params": [
- "_clk"
- ],
- "id": 32,
- "x": 86,
- "y": 284,
- "width": 72,
- "outputConnectors": [
- {
- "value": "_clk",
- "label": "_clk"
- }
- ]
- },
- {
- "label": "",
- "type": "linput",
- "params": [
- "_ena"
- ],
- "id": 33,
- "x": 87,
- "y": 344,
- "width": 72,
- "outputConnectors": [
- {
- "value": "_ena",
- "label": "_ena"
- }
- ]
- },
- {
- "label": "",
- "type": "loutput",
- "params": [
- "_ena"
- ],
- "id": 35,
- "x": 647,
- "y": 140,
- "width": 72,
- "inputConnectors": [
- {
- "value": "_ena",
- "label": "_ena"
- }
- ]
- }
- ],
- "connections": [
- {
- "source": {
- "nodeID": 15,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 10,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 15,
- "connectorIndex": 1
- },
- "dest": {
- "nodeID": 11,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 15,
- "connectorIndex": 2
- },
- "dest": {
- "nodeID": 12,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 15,
- "connectorIndex": 3
- },
- "dest": {
- "nodeID": 13,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 16,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 29,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 31,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 14,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 32,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 15,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 33,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 15,
- "connectorIndex": 1
- }
- },
- {
- "source": {
- "nodeID": 14,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 35,
- "connectorIndex": 0
- }
- }
- ]
-}
\ No newline at end of file
diff --git a/icestudio/examples/flipflopt.json b/icestudio/examples/flipflopt.json
deleted file mode 100644
index 4d995003d..000000000
--- a/icestudio/examples/flipflopt.json
+++ /dev/null
@@ -1,334 +0,0 @@
-{
- "nodes": [
- {
- "label": "",
- "type": "input",
- "params": [
- "21"
- ],
- "id": 16,
- "x": 49,
- "y": 127,
- "width": 56,
- "outputConnectors": [
- {
- "label": "21"
- }
- ]
- },
- {
- "label": "TIM (22)",
- "type": "timer",
- "params": [
- {
- "name": "N",
- "value": "22"
- },
- {
- "name": "M",
- "value": 4194304
- }
- ],
- "id": 14,
- "x": 424,
- "y": 129,
- "width": 166,
- "vcode": "module timer #(parameter N=22, M=4194304)(input clk, output wire out);\n reg [N-1:0] c = 0;\n always @(posedge clk)\n c <= (c == M - 1) ? 0 : c + 1;\n assign out = (c == M - 1) ? 1 : 0;\nendmodule\n",
- "inputConnectors": [
- {
- "name": "clk",
- "label": "clk"
- }
- ],
- "outputConnectors": [
- {
- "name": "out",
- "label": "out"
- }
- ]
- },
- {
- "label": "FF",
- "type": "flipflop",
- "params": [],
- "vcode": "module flipflop (input clk, rst, d, ena, output reg q);\n always @(posedge clk)\n begin\n if (rst)\n q <= 0;\n else\n if (ena)\n q <= d;\n end\nendmodule\n",
- "id": 19,
- "x": 271,
- "y": 260,
- "width": 150,
- "inputConnectors": [
- {
- "name": "clk",
- "label": "clk"
- },
- {
- "name": "rst",
- "label": "rst"
- },
- {
- "name": "d",
- "label": "D"
- },
- {
- "name": "ena",
- "label": "ena"
- }
- ],
- "outputConnectors": [
- {
- "name": "q",
- "label": "Q"
- }
- ]
- },
- {
- "label": "NOT",
- "type": "notx",
- "params": [],
- "vcode": "module notx (input i, output o);\nassign o = ! i;\nendmodule\n",
- "id": 25,
- "x": 458,
- "y": 259,
- "width": 80,
- "inputConnectors": [
- {
- "name": "i",
- "label": ""
- }
- ],
- "outputConnectors": [
- {
- "name": "o",
- "label": ""
- }
- ]
- },
- {
- "label": "",
- "type": "linput",
- "params": [
- "_sig"
- ],
- "id": 26,
- "x": 110,
- "y": 301,
- "width": 72,
- "outputConnectors": [
- {
- "value": "_sig",
- "label": "_sig"
- }
- ]
- },
- {
- "label": "",
- "type": "output",
- "params": [
- "95"
- ],
- "id": 27,
- "x": 606,
- "y": 301,
- "width": 56,
- "inputConnectors": [
- {
- "label": "95"
- }
- ]
- },
- {
- "label": "",
- "type": "loutput",
- "params": [
- "_sig"
- ],
- "id": 28,
- "x": 594,
- "y": 243,
- "width": 72,
- "inputConnectors": [
- {
- "value": "_sig",
- "label": "_sig"
- }
- ]
- },
- {
- "label": "",
- "type": "loutput",
- "params": [
- "_clk"
- ],
- "id": 29,
- "x": 141,
- "y": 128,
- "width": 72,
- "inputConnectors": [
- {
- "value": "_clk",
- "label": "_clk"
- }
- ]
- },
- {
- "label": "",
- "type": "linput",
- "params": [
- "_clk"
- ],
- "id": 30,
- "x": 108,
- "y": 243,
- "width": 72,
- "outputConnectors": [
- {
- "value": "_clk",
- "label": "_clk"
- }
- ]
- },
- {
- "label": "",
- "type": "linput",
- "params": [
- "_clk"
- ],
- "id": 31,
- "x": 319,
- "y": 129,
- "width": 72,
- "outputConnectors": [
- {
- "value": "_clk",
- "label": "_clk"
- }
- ]
- },
- {
- "label": "",
- "type": "linput",
- "params": [
- "_ena"
- ],
- "id": 34,
- "x": 107,
- "y": 356,
- "width": 72,
- "outputConnectors": [
- {
- "value": "_ena",
- "label": "_ena"
- }
- ]
- },
- {
- "label": "",
- "type": "loutput",
- "params": [
- "_ena"
- ],
- "id": 35,
- "x": 628,
- "y": 131,
- "width": 72,
- "inputConnectors": [
- {
- "value": "_ena",
- "label": "_ena"
- }
- ]
- }
- ],
- "connections": [
- {
- "source": {
- "nodeID": 19,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 25,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 26,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 19,
- "connectorIndex": 2
- }
- },
- {
- "source": {
- "nodeID": 25,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 28,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 16,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 29,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 30,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 19,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 31,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 14,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 34,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 19,
- "connectorIndex": 3
- }
- },
- {
- "source": {
- "nodeID": 14,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 35,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 25,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 27,
- "connectorIndex": 0
- }
- }
- ]
-}
\ No newline at end of file
diff --git a/icestudio/examples/setbit.json b/icestudio/examples/setbit.json
deleted file mode 100644
index 46e98aac6..000000000
--- a/icestudio/examples/setbit.json
+++ /dev/null
@@ -1,178 +0,0 @@
-{
- "nodes": [
- {
- "label": "",
- "type": "driver",
- "params": [
- {
- "name": "B",
- "value": "1'b1"
- }
- ],
- "vcode": "module driver #(parameter B = 1'b0)(output o);\nassign o = B;\nendmodule\n",
- "id": 10,
- "x": 165,
- "y": 206,
- "width": 55,
- "outputConnectors": [
- {
- "name": "o",
- "label": "\"1\""
- }
- ]
- },
- {
- "label": "",
- "type": "output",
- "params": [
- "95"
- ],
- "id": 11,
- "x": 342,
- "y": 149,
- "width": 56,
- "inputConnectors": [
- {
- "label": "95"
- }
- ]
- },
- {
- "label": "",
- "type": "output",
- "params": [
- "96"
- ],
- "id": 12,
- "x": 342,
- "y": 209,
- "width": 56,
- "inputConnectors": [
- {
- "label": "96"
- }
- ]
- },
- {
- "label": "",
- "type": "output",
- "params": [
- "97"
- ],
- "id": 13,
- "x": 342,
- "y": 269,
- "width": 56,
- "inputConnectors": [
- {
- "label": "97"
- }
- ]
- },
- {
- "label": "",
- "type": "output",
- "params": [
- "98"
- ],
- "id": 14,
- "x": 342,
- "y": 329,
- "width": 56,
- "inputConnectors": [
- {
- "label": "98"
- }
- ]
- },
- {
- "label": "",
- "type": "output",
- "params": [
- "99"
- ],
- "id": 15,
- "x": 342,
- "y": 389,
- "width": 56,
- "inputConnectors": [
- {
- "label": "99"
- }
- ]
- },
- {
- "label": "",
- "type": "driver",
- "params": [
- {
- "name": "B",
- "value": "1'b0"
- }
- ],
- "vcode": "module driver #(parameter B = 1'b0)(output o);\nassign o = B;\nendmodule\n",
- "id": 16,
- "x": 167,
- "y": 357,
- "width": 55,
- "outputConnectors": [
- {
- "name": "o",
- "label": "\"0\""
- }
- ]
- }
- ],
- "connections": [
- {
- "source": {
- "nodeID": 10,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 11,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 10,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 12,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 10,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 13,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 16,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 14,
- "connectorIndex": 0
- }
- },
- {
- "source": {
- "nodeID": 16,
- "connectorIndex": 0
- },
- "dest": {
- "nodeID": 15,
- "connectorIndex": 0
- }
- }
- ]
-}
\ No newline at end of file
diff --git a/icestudio/flowchart/dragging_service.js b/icestudio/flowchart/dragging_service.js
deleted file mode 100644
index 5b4d0d270..000000000
--- a/icestudio/flowchart/dragging_service.js
+++ /dev/null
@@ -1,107 +0,0 @@
-
-angular.module('dragging', ['mouseCapture', ] )
-
-//
-// Service used to help with dragging and clicking on elements.
-//
-.factory('dragging', ['$rootScope', 'mouseCapture',function ($rootScope, mouseCapture) {
-
- //
- // Threshold for dragging.
- // When the mouse moves by at least this amount dragging starts.
- //
- var threshold = 5;
-
- return {
-
-
- //
- // Called by users of the service to register a mousedown event and start dragging.
- // Acquires the 'mouse capture' until the mouseup event.
- //
- startDrag: function (evt, config) {
-
- var dragging = false;
- var x = evt.pageX;
- var y = evt.pageY;
-
- //
- // Handler for mousemove events while the mouse is 'captured'.
- //
- var mouseMove = function (evt) {
-
- if (!dragging) {
- if (Math.abs(evt.pageX - x) > threshold ||
- Math.abs(evt.pageY - y) > threshold)
- {
- dragging = true;
-
- if (config.dragStarted) {
- config.dragStarted(x, y, evt);
- }
-
- if (config.dragging) {
- // First 'dragging' call to take into account that we have
- // already moved the mouse by a 'threshold' amount.
- config.dragging(evt.pageX, evt.pageY, evt);
- }
- }
- }
- else {
- if (config.dragging) {
- config.dragging(evt.pageX, evt.pageY, evt);
- }
-
- x = evt.pageX;
- y = evt.pageY;
- }
- };
-
- //
- // Handler for when mouse capture is released.
- //
- var released = function() {
-
- if (dragging) {
- if (config.dragEnded) {
- config.dragEnded();
- }
- }
- else {
- if (config.clicked) {
- config.clicked();
- }
- }
- };
-
- //
- // Handler for mouseup event while the mouse is 'captured'.
- // Mouseup releases the mouse capture.
- //
- var mouseUp = function (evt) {
-
- mouseCapture.release();
-
- evt.stopPropagation();
- evt.preventDefault();
- };
-
- //
- // Acquire the mouse capture and start handling mouse events.
- //
- mouseCapture.acquire(evt, {
- mouseMove: mouseMove,
- mouseUp: mouseUp,
- released: released,
- });
-
- evt.stopPropagation();
- evt.preventDefault();
- },
-
- };
-
-}])
-
-;
-
diff --git a/icestudio/flowchart/flowchart_directive.js b/icestudio/flowchart/flowchart_directive.js
deleted file mode 100644
index 773fa5b34..000000000
--- a/icestudio/flowchart/flowchart_directive.js
+++ /dev/null
@@ -1,421 +0,0 @@
-//
-// Flowchart module.
-//
-angular.module('flowChart', ['dragging'] )
-
-//
-// Directive that generates the rendered chart from the data model.
-//
-.directive('flowChart', function() {
- return {
- restrict: 'E',
- templateUrl: "flowchart/flowchart_template.html",
- replace: true,
- scope: {
- chart: "=chart",
- },
-
- //
- // Controller for the flowchart directive.
- // Having a separate controller is better for unit testing, otherwise
- // it is painful to unit test a directive without instantiating the DOM
- // (which is possible, just not ideal).
- //
- controller: 'FlowChartController',
- };
-})
-
-//
-// Directive that allows the chart to be edited as json in a textarea.
-//
-.directive('chartJsonEdit', function () {
- return {
- restrict: 'A',
- scope: {
- viewModel: "="
- },
- link: function (scope, elem, attr) {
-
- //
- // Serialize the data model as json and update the textarea.
- //
- var updateJson = function () {
- if (scope.viewModel) {
- var json = JSON.stringify(scope.viewModel.data, null, 4);
- $(elem).val(json);
- }
- };
-
- //
- // First up, set the initial value of the textarea.
- //
- updateJson();
-
- //
- // Watch for changes in the data model and update the textarea whenever necessary.
- //
- scope.$watch("viewModel.data", updateJson, true);
-
- //
- // Handle the change event from the textarea and update the data model
- // from the modified json.
- //
- $(elem).bind("input propertychange", function () {
- var json = $(elem).val();
- var dataModel = JSON.parse(json);
- scope.viewModel = new flowchart.ChartViewModel(dataModel);
-
- scope.$digest();
- });
- }
- }
-
-})
-
-//
-// Controller for the flowchart directive.
-// Having a separate controller is better for unit testing, otherwise
-// it is painful to unit test a directive without instantiating the DOM
-// (which is possible, just not ideal).
-//
-.controller('FlowChartController', ['$scope', 'dragging', '$element', function FlowChartController ($scope, dragging, $element) {
-
- var controller = this;
-
- //
- // Reference to the document and jQuery, can be overridden for testting.
- //
- this.document = document;
-
- //
- // Wrap jQuery so it can easily be mocked for testing.
- //
- this.jQuery = function (element) {
- return $(element);
- }
-
- //
- // Init data-model variables.
- //
- $scope.draggingConnection = false;
- $scope.connectorSize = 8;
- $scope.dragSelecting = false;
- /* Can use this to test the drag selection rect.
- $scope.dragSelectionRect = {
- x: 0,
- y: 0,
- width: 0,
- height: 0,
- };
- */
-
- //
- // Reference to the connection, connector or node that the mouse is currently over.
- //
- $scope.mouseOverConnector = null;
- $scope.mouseOverConnection = null;
- $scope.mouseOverNode = null;
-
- //
- // The class for connections and connectors.
- //
- this.connectionClass = 'connection';
- this.connectorClass = 'connector';
- this.nodeClass = 'node';
-
- //
- // Search up the HTML element tree for an element the requested class.
- //
- this.searchUp = function (element, parentClass) {
-
- //
- // Reached the root.
- //
- if (element == null || element.length == 0) {
- return null;
- }
-
- //
- // Check if the element has the class that identifies it as a connector.
- //
- if (hasClassSVG(element, parentClass)) {
- //
- // Found the connector element.
- //
- return element;
- }
-
- //
- // Recursively search parent elements.
- //
- return this.searchUp(element.parent(), parentClass);
- };
-
- //
- // Hit test and retreive node and connector that was hit at the specified coordinates.
- //
- this.hitTest = function (clientX, clientY) {
-
- //
- // Retreive the element the mouse is currently over.
- //
- return this.document.elementFromPoint(clientX, clientY);
- };
-
- //
- // Hit test and retreive node and connector that was hit at the specified coordinates.
- //
- this.checkForHit = function (mouseOverElement, whichClass) {
-
- //
- // Find the parent element, if any, that is a connector.
- //
- var hoverElement = this.searchUp(this.jQuery(mouseOverElement), whichClass);
- if (!hoverElement) {
- return null;
- }
-
- return hoverElement.scope();
- };
-
- //
- // Translate the coordinates so they are relative to the svg element.
- //
- this.translateCoordinates = function(x, y, evt) {
- var svg_elem = $element.get(0);
- var matrix = svg_elem.getScreenCTM();
- var point = svg_elem.createSVGPoint();
- point.x = x - evt.view.pageXOffset;
- point.y = y - evt.view.pageYOffset;
- return point.matrixTransform(matrix.inverse());
- };
-
- //
- // Called on mouse down in the chart.
- //
- $scope.mouseDown = function (evt) {
-
- $scope.chart.deselectAll();
-
- dragging.startDrag(evt, {
-
- //
- // Commence dragging... setup variables to display the drag selection rect.
- //
- dragStarted: function (x, y) {
- $scope.dragSelecting = true;
- var startPoint = controller.translateCoordinates(x, y, evt);
- $scope.dragSelectionStartPoint = startPoint;
- $scope.dragSelectionRect = {
- x: startPoint.x,
- y: startPoint.y,
- width: 0,
- height: 0,
- };
- },
-
- //
- // Update the drag selection rect while dragging continues.
- //
- dragging: function (x, y) {
- var startPoint = $scope.dragSelectionStartPoint;
- var curPoint = controller.translateCoordinates(x, y, evt);
-
- $scope.dragSelectionRect = {
- x: curPoint.x > startPoint.x ? startPoint.x : curPoint.x,
- y: curPoint.y > startPoint.y ? startPoint.y : curPoint.y,
- width: curPoint.x > startPoint.x ? curPoint.x - startPoint.x : startPoint.x - curPoint.x,
- height: curPoint.y > startPoint.y ? curPoint.y - startPoint.y : startPoint.y - curPoint.y,
- };
- },
-
- //
- // Dragging has ended... select all that are within the drag selection rect.
- //
- dragEnded: function () {
- $scope.dragSelecting = false;
- $scope.chart.applySelectionRect($scope.dragSelectionRect);
- delete $scope.dragSelectionStartPoint;
- delete $scope.dragSelectionRect;
- },
- });
- };
-
- //
- // Called for each mouse move on the svg element.
- //
- $scope.mouseMove = function (evt) {
-
- //
- // Clear out all cached mouse over elements.
- //
- $scope.mouseOverConnection = null;
- $scope.mouseOverConnector = null;
- $scope.mouseOverNode = null;
-
- var mouseOverElement = controller.hitTest(evt.clientX, evt.clientY);
- if (mouseOverElement == null) {
- // Mouse isn't over anything, just clear all.
- return;
- }
-
- if (!$scope.draggingConnection) { // Only allow 'connection mouse over' when not dragging out a connection.
-
- // Figure out if the mouse is over a connection.
- var scope = controller.checkForHit(mouseOverElement, controller.connectionClass);
- $scope.mouseOverConnection = (scope && scope.connection) ? scope.connection : null;
- if ($scope.mouseOverConnection) {
- // Don't attempt to mouse over anything else.
- return;
- }
- }
-
- // Figure out if the mouse is over a connector.
- var scope = controller.checkForHit(mouseOverElement, controller.connectorClass);
- $scope.mouseOverConnector = (scope && scope.connector) ? scope.connector : null;
- if ($scope.mouseOverConnector) {
- // Don't attempt to mouse over anything else.
- return;
- }
-
- // Figure out if the mouse is over a node.
- var scope = controller.checkForHit(mouseOverElement, controller.nodeClass);
- $scope.mouseOverNode = (scope && scope.node) ? scope.node : null;
- };
-
- //
- // Handle mousedown on a node.
- //
- $scope.nodeMouseDown = function (evt, node) {
-
- var chart = $scope.chart;
- var lastMouseCoords;
-
- dragging.startDrag(evt, {
-
- //
- // Node dragging has commenced.
- //
- dragStarted: function (x, y) {
-
- lastMouseCoords = controller.translateCoordinates(x, y, evt);
-
- //
- // If nothing is selected when dragging starts,
- // at least select the node we are dragging.
- //
- if (!node.selected()) {
- chart.deselectAll();
- node.select();
- if (node.data.vcode) {
- var editor = ace.edit('editor');
- editor.setValue(node.data.vcode, -1);
- }
- }
- },
-
- //
- // Dragging selected nodes... update their x,y coordinates.
- //
- dragging: function (x, y) {
-
- var curCoords = controller.translateCoordinates(x, y, evt);
- var deltaX = curCoords.x - lastMouseCoords.x;
- var deltaY = curCoords.y - lastMouseCoords.y;
-
- chart.updateSelectedNodesLocation(deltaX, deltaY);
-
- lastMouseCoords = curCoords;
- },
-
- //
- // The node wasn't dragged... it was clicked.
- //
- clicked: function () {
- chart.handleNodeClicked(node, evt.ctrlKey);
- },
-
- });
- };
-
- //
- // Handle mousedown on a connection.
- //
- $scope.connectionMouseDown = function (evt, connection) {
- var chart = $scope.chart;
- chart.handleConnectionMouseDown(connection, evt.ctrlKey);
-
- // Don't let the chart handle the mouse down.
- evt.stopPropagation();
- evt.preventDefault();
- };
-
- //
- // Handle mousedown on an input connector.
- //
- $scope.connectorMouseDown = function (evt, node, connector, connectorIndex, isInputConnector) {
-
- //
- // Initiate dragging out of a connection.
- //
- dragging.startDrag(evt, {
-
- //
- // Called when the mouse has moved greater than the threshold distance
- // and dragging has commenced.
- //
- dragStarted: function (x, y) {
-
- var curCoords = controller.translateCoordinates(x, y, evt);
-
- $scope.draggingConnection = true;
- $scope.dragPoint1 = flowchart.computeConnectorPos(node, connectorIndex, isInputConnector);
- $scope.dragPoint2 = {
- x: curCoords.x,
- y: curCoords.y
- };
- $scope.dragTangent1 = flowchart.computeConnectionSourceTangent($scope.dragPoint1, $scope.dragPoint2);
- $scope.dragTangent2 = flowchart.computeConnectionDestTangent($scope.dragPoint1, $scope.dragPoint2);
- },
-
- //
- // Called on mousemove while dragging out a connection.
- //
- dragging: function (x, y, evt) {
- var startCoords = controller.translateCoordinates(x, y, evt);
- $scope.dragPoint1 = flowchart.computeConnectorPos(node, connectorIndex, isInputConnector);
- $scope.dragPoint2 = {
- x: startCoords.x,
- y: startCoords.y
- };
- $scope.dragTangent1 = flowchart.computeConnectionSourceTangent($scope.dragPoint1, $scope.dragPoint2);
- $scope.dragTangent2 = flowchart.computeConnectionDestTangent($scope.dragPoint1, $scope.dragPoint2);
- },
-
- //
- // Clean up when dragging has finished.
- //
- dragEnded: function () {
-
- if ($scope.mouseOverConnector &&
- $scope.mouseOverConnector !== connector) {
-
- //
- // Dragging has ended...
- // The mouse is over a valid connector...
- // Create a new connection.
- //
- $scope.chart.createNewConnection(connector, $scope.mouseOverConnector);
- }
-
- $scope.draggingConnection = false;
- delete $scope.dragPoint1;
- delete $scope.dragTangent1;
- delete $scope.dragPoint2;
- delete $scope.dragTangent2;
- },
-
- });
- };
-}])
-;
diff --git a/icestudio/flowchart/flowchart_directive.spec.js b/icestudio/flowchart/flowchart_directive.spec.js
deleted file mode 100644
index 61658695b..000000000
--- a/icestudio/flowchart/flowchart_directive.spec.js
+++ /dev/null
@@ -1,662 +0,0 @@
-
-describe('flowchart-directive', function () {
-
- var testObject;
- var mockScope;
- var mockDragging;
- var mockSvgElement;
-
- //
- // Bring in the flowChart module before each test.
- //
- beforeEach(module('flowChart'));
-
- //
- // Helper function to create the controller for each test.
- //
- var createController = function ($rootScope, $controller) {
-
- mockScope = $rootScope.$new();
- mockDragging = createMockDragging();
- mockSvgElement = {
- get: function () {
- return createMockSvgElement();
- }
- };
-
- testObject = $controller('FlowChartController', {
- $scope: mockScope,
- dragging: mockDragging,
- $element: mockSvgElement,
- });
- };
-
- //
- // Setup the controller before each test.
- //
- beforeEach(inject(function ($rootScope, $controller) {
-
- createController($rootScope, $controller);
- }));
-
- //
- // Create a mock DOM element.
- //
- var createMockElement = function(attr, parent, scope) {
- return {
- attr: function() {
- return attr;
- },
-
- parent: function () {
- return parent;
- },
-
- scope: function () {
- return scope || {};
- },
-
- };
- }
-
- //
- // Create a mock node data model.
- //
- var createMockNode = function (inputConnectors, outputConnectors) {
- return {
- x: function () { return 0 },
- y: function () { return 0 },
- inputConnectors: inputConnectors || [],
- outputConnectors: outputConnectors || [],
- select: jasmine.createSpy(),
- selected: function () { return false; },
- };
- };
-
- //
- // Create a mock chart.
- //
- var createMockChart = function (mockNodes, mockConnections) {
- return {
- nodes: mockNodes,
- connections: mockConnections,
-
- handleNodeClicked: jasmine.createSpy(),
- handleConnectionMouseDown: jasmine.createSpy(),
- updateSelectedNodesLocation: jasmine.createSpy(),
- deselectAll: jasmine.createSpy(),
- createNewConnection: jasmine.createSpy(),
- applySelectionRect: jasmine.createSpy(),
- };
- };
-
- //
- // Create a mock dragging service.
- //
- var createMockDragging = function () {
-
- var mockDragging = {
- startDrag: function (evt, config) {
- mockDragging.evt = evt;
- mockDragging.config = config;
- },
- };
-
- return mockDragging;
- };
-
- //
- // Create a mock version of the SVG element.
- //
- var createMockSvgElement = function () {
- return {
- getScreenCTM: function () {
- return {
- inverse: function () {
- return this;
- },
- };
- },
-
- createSVGPoint: function () {
- return {
- x: 0,
- y: 0 ,
- matrixTransform: function () {
- return this;
- },
- };
- }
-
-
-
- };
- };
-
- it('searchUp returns null when at root 1', function () {
-
- expect(testObject.searchUp(null, "some-class")).toBe(null);
- });
-
-
- it('searchUp returns null when at root 2', function () {
-
- expect(testObject.searchUp([], "some-class")).toBe(null);
- });
-
- it('searchUp returns element when it has requested class', function () {
-
- var whichClass = "some-class";
- var mockElement = createMockElement(whichClass);
-
- expect(testObject.searchUp(mockElement, whichClass)).toBe(mockElement);
- });
-
- it('searchUp returns parent when it has requested class', function () {
-
- var whichClass = "some-class";
- var mockParent = createMockElement(whichClass);
- var mockElement = createMockElement('', mockParent);
-
- expect(testObject.searchUp(mockElement, whichClass)).toBe(mockParent);
- });
-
- it('hitTest returns result of elementFromPoint', function () {
-
- var mockElement = {};
-
- // Mock out the document.
- testObject.document = {
- elementFromPoint: function () {
- return mockElement;
- },
- };
-
- expect(testObject.hitTest(12, 30)).toBe(mockElement);
- });
-
- it('checkForHit returns null when the hit element has no parent with requested class', function () {
-
- var mockElement = createMockElement(null, null);
-
- testObject.jQuery = function (input) {
- return input;
- };
-
- expect(testObject.checkForHit(mockElement, "some-class")).toBe(null);
- });
-
- it('checkForHit returns the result of searchUp when found', function () {
-
- var mockConnectorScope = {};
-
- var whichClass = "some-class";
- var mockElement = createMockElement(whichClass, null, mockConnectorScope);
-
- testObject.jQuery = function (input) {
- return input;
- };
-
- expect(testObject.checkForHit(mockElement, whichClass)).toBe(mockConnectorScope);
- });
-
- it('checkForHit returns null when searchUp fails', function () {
-
- var mockElement = createMockElement(null, null, null);
-
- testObject.jQuery = function (input) {
- return input;
- };
-
- expect(testObject.checkForHit(mockElement, "some-class")).toBe(null);
- });
-
- it('test node dragging is started on node mouse down', function () {
-
- mockDragging.startDrag = jasmine.createSpy();
-
- var mockEvt = {};
- var mockNode = createMockNode();
-
- mockScope.nodeMouseDown(mockEvt, mockNode);
-
- expect(mockDragging.startDrag).toHaveBeenCalled();
-
- });
-
- it('test node click handling is forwarded to view model', function () {
-
- mockScope.chart = createMockChart([mockNode]);
-
- var mockEvt = {
- ctrlKey: false,
- };
- var mockNode = createMockNode();
-
- mockScope.nodeMouseDown(mockEvt, mockNode);
-
- mockDragging.config.clicked();
-
- expect(mockScope.chart.handleNodeClicked).toHaveBeenCalledWith(mockNode, false);
- });
-
- it('test control + node click handling is forwarded to view model', function () {
-
- var mockNode = createMockNode();
-
- mockScope.chart = createMockChart([mockNode]);
-
- var mockEvt = {
- ctrlKey: true,
- };
-
- mockScope.nodeMouseDown(mockEvt, mockNode);
-
- mockDragging.config.clicked();
-
- expect(mockScope.chart.handleNodeClicked).toHaveBeenCalledWith(mockNode, true);
- });
-
- it('test node dragging updates selected nodes location', function () {
-
- var mockEvt = {
- view: {
- pageXOffset: 0,
- pageYOffset: 0,
- },
- };
-
- mockScope.chart = createMockChart([createMockNode()]);
-
- mockScope.nodeMouseDown(mockEvt, mockScope.chart.nodes[0]);
-
- var xIncrement = 5;
- var yIncrement = 15;
-
- mockDragging.config.dragStarted(0, 0);
- mockDragging.config.dragging(xIncrement, yIncrement);
-
- expect(mockScope.chart.updateSelectedNodesLocation).toHaveBeenCalledWith(xIncrement, yIncrement);
- });
-
- it('test node dragging doesnt modify selection when node is already selected', function () {
-
- var mockNode1 = createMockNode();
- var mockNode2 = createMockNode();
-
- mockScope.chart = createMockChart([mockNode1, mockNode2]);
-
- mockNode2.selected = function () { return true; }
-
- var mockEvt = {
- view: {
- scrollX: 0,
- scrollY: 0,
- },
- };
-
- mockScope.nodeMouseDown(mockEvt, mockNode2);
-
- mockDragging.config.dragStarted(0, 0);
-
- expect(mockScope.chart.deselectAll).not.toHaveBeenCalled();
- });
-
- it('test node dragging selects node, when the node is not already selected', function () {
-
- var mockNode1 = createMockNode();
- var mockNode2 = createMockNode();
-
- mockScope.chart = createMockChart([mockNode1, mockNode2]);
-
- var mockEvt = {
- view: {
- scrollX: 0,
- scrollY: 0,
- },
- };
-
- mockScope.nodeMouseDown(mockEvt, mockNode2);
-
- mockDragging.config.dragStarted(0, 0);
-
- expect(mockScope.chart.deselectAll).toHaveBeenCalled();
- expect(mockNode2.select).toHaveBeenCalled();
- });
-
- it('test connection click handling is forwarded to view model', function () {
-
- var mockNode = createMockNode();
-
- var mockEvt = {
- stopPropagation: jasmine.createSpy(),
- preventDefault: jasmine.createSpy(),
- ctrlKey: false,
- };
- var mockConnection = {};
-
- mockScope.chart = createMockChart([mockNode]);
-
- mockScope.connectionMouseDown(mockEvt, mockConnection);
-
- expect(mockScope.chart.handleConnectionMouseDown).toHaveBeenCalledWith(mockConnection, false);
- expect(mockEvt.stopPropagation).toHaveBeenCalled();
- expect(mockEvt.preventDefault).toHaveBeenCalled();
- });
-
- it('test control + connection click handling is forwarded to view model', function () {
-
- var mockNode = createMockNode();
-
- var mockEvt = {
- stopPropagation: jasmine.createSpy(),
- preventDefault: jasmine.createSpy(),
- ctrlKey: true,
- };
- var mockConnection = {};
-
- mockScope.chart = createMockChart([mockNode]);
-
- mockScope.connectionMouseDown(mockEvt, mockConnection);
-
- expect(mockScope.chart.handleConnectionMouseDown).toHaveBeenCalledWith(mockConnection, true);
- });
-
- it('test selection is cleared when background is clicked', function () {
-
- var mockEvt = {};
-
- mockScope.chart = createMockChart([createMockNode()]);
-
- mockScope.chart.nodes[0].selected = true;
-
- mockScope.mouseDown(mockEvt);
-
- expect(mockScope.chart.deselectAll).toHaveBeenCalled();
- });
-
- it('test background mouse down commences selection dragging', function () {
-
- var mockNode = createMockNode();
- var mockEvt = {
- view: {
- scrollX: 0,
- scrollY: 0,
- },
- };
-
- mockScope.chart = createMockChart([mockNode]);
-
- mockScope.mouseDown(mockEvt);
-
- mockDragging.config.dragStarted(0, 0);
-
- expect(mockScope.dragSelecting).toBe(true);
- });
-
- it('test can end selection dragging', function () {
-
- var mockNode = createMockNode();
- var mockEvt = {
- view: {
- scrollX: 0,
- scrollY: 0,
- },
- };
-
- mockScope.chart = createMockChart([mockNode]);
-
- mockScope.mouseDown(mockEvt);
-
- mockDragging.config.dragStarted(0, 0, mockEvt);
- mockDragging.config.dragging(0, 0, mockEvt);
- mockDragging.config.dragEnded();
-
- expect(mockScope.dragSelecting).toBe(false);
- });
-
- it('test selection dragging ends by selecting nodes', function () {
-
- var mockNode = createMockNode();
- var mockEvt = {
- view: {
- scrollX: 0,
- scrollY: 0,
- },
- };
-
- mockScope.chart = createMockChart([mockNode]);
-
- mockScope.mouseDown(mockEvt);
-
- mockDragging.config.dragStarted(0, 0, mockEvt);
- mockDragging.config.dragging(0, 0, mockEvt);
-
- var selectionRect = {
- x: 1,
- y: 2,
- width: 3,
- height: 4,
- };
-
- mockScope.dragSelectionRect = selectionRect;
-
- mockDragging.config.dragEnded();
-
- expect(mockScope.chart.applySelectionRect).toHaveBeenCalledWith(selectionRect);
- });
-
- it('test mouse down commences connection dragging', function () {
-
- var mockNode = createMockNode();
- var mockEvt = {
- view: {
- scrollX: 0,
- scrollY: 0,
- },
- };
-
- mockScope.chart = createMockChart([mockNode]);
-
- mockScope.connectorMouseDown(mockEvt, mockScope.chart.nodes[0], mockScope.chart.nodes[0].inputConnectors[0], 0, false);
-
- mockDragging.config.dragStarted(0, 0);
-
- expect(mockScope.draggingConnection).toBe(true);
- });
-
- it('test can end connection dragging', function () {
-
- var mockNode = createMockNode();
- var mockEvt = {
- view: {
- scrollX: 0,
- scrollY: 0,
- },
- };
-
- mockScope.chart = createMockChart([mockNode]);
-
- mockScope.connectorMouseDown(mockEvt, mockScope.chart.nodes[0], mockScope.chart.nodes[0].inputConnectors[0], 0, false);
-
- mockDragging.config.dragStarted(0, 0, mockEvt);
- mockDragging.config.dragging(0, 0, mockEvt);
- mockDragging.config.dragEnded();
-
- expect(mockScope.draggingConnection).toBe(false);
- });
-
- it('test can make a connection by dragging', function () {
-
- var mockNode = createMockNode();
- var mockDraggingConnector = {};
- var mockDragOverConnector = {};
- var mockEvt = {
- view: {
- scrollX: 0,
- scrollY: 0,
- },
- };
-
- mockScope.chart = createMockChart([mockNode]);
-
- mockScope.connectorMouseDown(mockEvt, mockScope.chart.nodes[0], mockDraggingConnector, 0, false);
-
- mockDragging.config.dragStarted(0, 0, mockEvt);
- mockDragging.config.dragging(0, 0, mockEvt);
-
- // Fake out the mouse over connector.
- mockScope.mouseOverConnector = mockDragOverConnector;
-
- mockDragging.config.dragEnded();
-
- expect(mockScope.chart.createNewConnection).toHaveBeenCalledWith(mockDraggingConnector, mockDragOverConnector);
- });
-
- it('test connection creation by dragging is cancelled when dragged over invalid connector', function () {
-
- var mockNode = createMockNode();
- var mockDraggingConnector = {};
- var mockEvt = {
- view: {
- scrollX: 0,
- scrollY: 0,
- },
- };
-
- mockScope.chart = createMockChart([mockNode]);
-
- mockScope.connectorMouseDown(mockEvt, mockScope.chart.nodes[0], mockDraggingConnector, 0, false);
-
- mockDragging.config.dragStarted(0, 0, mockEvt);
- mockDragging.config.dragging(0, 0, mockEvt);
-
- // Fake out the invalid connector.
- mockScope.mouseOverConnector = null;
-
- mockDragging.config.dragEnded();
-
- expect(mockScope.chart.createNewConnection).not.toHaveBeenCalled();
- });
-
- it('mouse move over connection caches the connection', function () {
-
- var mockElement = {};
- var mockConnection = {};
- var mockConnectionScope = {
- connection: mockConnection
- };
- var mockEvent = {};
-
- //
- // Fake out the function that check if a connection has been hit.
- //
- testObject.checkForHit = function (element, whichClass) {
- if (whichClass === testObject.connectionClass) {
- return mockConnectionScope;
- }
-
- return null;
- };
-
- testObject.hitTest = function () {
- return mockElement;
- };
-
- mockScope.mouseMove(mockEvent);
-
- expect(mockScope.mouseOverConnection).toBe(mockConnection);
- });
-
- it('test mouse over connection clears mouse over connector and node', function () {
-
- var mockElement = {};
- var mockConnection = {};
- var mockConnectionScope = {
- connection: mockConnection
- };
- var mockEvent = {};
-
- //
- // Fake out the function that check if a connection has been hit.
- //
- testObject.checkForHit = function (element, whichClass) {
- if (whichClass === testObject.connectionClass) {
- return mockConnectionScope;
- }
-
- return null;
- };
-
- testObject.hitTest = function () {
- return mockElement;
- };
-
-
- mockScope.mouseOverConnector = {};
- mockScope.mouseOverNode = {};
-
- mockScope.mouseMove(mockEvent);
-
- expect(mockScope.mouseOverConnector).toBe(null);
- expect(mockScope.mouseOverNode).toBe(null);
- });
-
- it('test mouseMove handles mouse over connector', function () {
-
- var mockElement = {};
- var mockConnector = {};
- var mockConnectorScope = {
- connector: mockConnector
- };
- var mockEvent = {};
-
- //
- // Fake out the function that check if a connector has been hit.
- //
- testObject.checkForHit = function (element, whichClass) {
- if (whichClass === testObject.connectorClass) {
- return mockConnectorScope;
- }
-
- return null;
- };
-
- testObject.hitTest = function () {
- return mockElement;
- };
-
- mockScope.mouseMove(mockEvent);
-
- expect(mockScope.mouseOverConnector).toBe(mockConnector);
- });
-
- it('test mouseMove handles mouse over node', function () {
-
- var mockElement = {};
- var mockNode = {};
- var mockNodeScope = {
- node: mockNode
- };
- var mockEvent = {};
-
- //
- // Fake out the function that check if a connector has been hit.
- //
- testObject.checkForHit = function (element, whichClass) {
- if (whichClass === testObject.nodeClass) {
- return mockNodeScope;
- }
-
- return null;
- };
-
- testObject.hitTest = function () {
- return mockElement;
- };
-
- mockScope.mouseMove(mockEvent);
-
- expect(mockScope.mouseOverNode).toBe(mockNode);
- });
-});
diff --git a/icestudio/flowchart/flowchart_template.html b/icestudio/flowchart/flowchart_template.html
deleted file mode 100644
index 15c636bde..000000000
--- a/icestudio/flowchart/flowchart_template.html
+++ /dev/null
@@ -1,195 +0,0 @@
-
diff --git a/icestudio/flowchart/flowchart_viewmodel.js b/icestudio/flowchart/flowchart_viewmodel.js
deleted file mode 100644
index 25dd537c9..000000000
--- a/icestudio/flowchart/flowchart_viewmodel.js
+++ /dev/null
@@ -1,822 +0,0 @@
-
-//
-// Global accessor.
-//
-var flowchart = {
-
-};
-
-// Module.
-(function () {
-
- //
- // Width of a node.
- //
- flowchart.defaultNodeWidth = 250;
-
- //
- // Amount of space reserved for displaying the node's name.
- //
- flowchart.nodeNameHeight = 20;
-
- //
- // Height of a connector in a node.
- //
- flowchart.connectorHeight = 20;
-
- //
- // Compute the Y coordinate of a connector, given its index.
- //
- flowchart.computeConnectorY = function (connectorIndex) {
- return flowchart.nodeNameHeight + (connectorIndex * flowchart.connectorHeight);
- }
-
- //
- // Compute the position of a connector in the graph.
- //
- flowchart.computeConnectorPos = function (node, connectorIndex, inputConnector) {
- return {
- x: node.x() + (inputConnector ? 0 : node.width ? node.width() : flowchart.defaultNodeWidth),
- y: node.y() + flowchart.computeConnectorY(connectorIndex),
- };
- };
-
- //
- // View model for a connector.
- //
- flowchart.ConnectorViewModel = function (connectorDataModel, x, y, parentNode) {
-
- this.data = connectorDataModel;
- this._parentNode = parentNode;
- this._x = x;
- this._y = y;
-
- //
- // The label of the connector.
- //
- this.label = function () {
- return this.data.label;
- }
-
- //
- // X coordinate of the connector.
- //
- this.x = function () {
- return this._x;
- };
-
- //
- // Y coordinate of the connector.
- //
- this.y = function () {
- return this._y;
- };
-
- //
- // The parent node that the connector is attached to.
- //
- this.parentNode = function () {
- return this._parentNode;
- };
- };
-
- //
- // Create view model for a list of data models.
- //
- var createConnectorsViewModel = function (connectorDataModels, x, parentNode) {
- var viewModels = [];
-
- if (connectorDataModels) {
- for (var i = 0; i < connectorDataModels.length; ++i) {
- var connectorViewModel =
- new flowchart.ConnectorViewModel(connectorDataModels[i], x, flowchart.computeConnectorY(i), parentNode);
- viewModels.push(connectorViewModel);
- }
- }
-
- return viewModels;
- };
-
- //
- // View model for a node.
- //
- flowchart.NodeViewModel = function (nodeDataModel) {
-
- this.data = nodeDataModel;
-
- // set the default width value of the node
- if (!this.data.width || this.data.width < 0) {
- this.data.width = flowchart.defaultNodeWidth;
- }
- this.inputConnectors = createConnectorsViewModel(this.data.inputConnectors, 0, this);
- this.outputConnectors = createConnectorsViewModel(this.data.outputConnectors, this.data.width, this);
-
- // Set to true when the node is selected.
- this._selected = false;
-
- //
- // Label of the node.
- //
- this.label = function () {
- return this.data.label || "";
- };
-
- //
- // X coordinate of the node.
- //
- this.x = function () {
- return this.data.x;
- };
-
- //
- // Y coordinate of the node.
- //
- this.y = function () {
- return this.data.y;
- };
-
- //
- // Width of the node.
- //
- this.width = function () {
- return this.data.width;
- }
-
- //
- // Height of the node.
- //
- this.height = function () {
- var numConnectors =
- Math.max(
- this.inputConnectors.length,
- this.outputConnectors.length);
- return flowchart.computeConnectorY(numConnectors);
- }
-
- //
- // Select the node.
- //
- this.select = function () {
- this._selected = true;
- };
-
- //
- // Deselect the node.
- //
- this.deselect = function () {
- this._selected = false;
- var editor = ace.edit('editor');
- editor.setValue('', -1);
- };
-
- //
- // Toggle the selection state of the node.
- //
- this.toggleSelected = function () {
- this._selected = !this._selected;
- };
-
- //
- // Returns true if the node is selected.
- //
- this.selected = function () {
- return this._selected;
- };
-
- //
- // Internal function to add a connector.
- this._addConnector = function (connectorDataModel, x, connectorsDataModel, connectorsViewModel) {
- var connectorViewModel =
- new flowchart.ConnectorViewModel(connectorDataModel, x,
- flowchart.computeConnectorY(connectorsViewModel.length), this);
-
- connectorsDataModel.push(connectorDataModel);
-
- // Add to node's view model.
- connectorsViewModel.push(connectorViewModel);
- }
-
- //
- // Add an input connector to the node.
- //
- this.addInputConnector = function (connectorDataModel) {
-
- if (!this.data.inputConnectors) {
- this.data.inputConnectors = [];
- }
- this._addConnector(connectorDataModel, 0, this.data.inputConnectors, this.inputConnectors);
- };
-
- //
- // Add an ouput connector to the node.
- //
- this.addOutputConnector = function (connectorDataModel) {
-
- if (!this.data.outputConnectors) {
- this.data.outputConnectors = [];
- }
- this._addConnector(connectorDataModel, this.data.width, this.data.outputConnectors, this.outputConnectors);
- };
- };
-
- //
- // Wrap the nodes data-model in a view-model.
- //
- var createNodesViewModel = function (nodesDataModel) {
- var nodesViewModel = [];
-
- if (nodesDataModel) {
- for (var i = 0; i < nodesDataModel.length; ++i) {
- nodesViewModel.push(new flowchart.NodeViewModel(nodesDataModel[i]));
- }
- }
-
- return nodesViewModel;
- };
-
- //
- // View model for a connection.
- //
- flowchart.ConnectionViewModel = function (connectionDataModel, sourceConnector, destConnector) {
-
- this.data = connectionDataModel;
- this.source = sourceConnector;
- this.dest = destConnector;
-
- // Set to true when the connection is selected.
- this._selected = false;
-
- this.label = function() {
- return this.data.label || "";
- }
-
- this.sourceCoordX = function () {
- return this.source.parentNode().x() + this.source.x();
- };
-
- this.sourceCoordY = function () {
- return this.source.parentNode().y() + this.source.y();
- };
-
- this.sourceCoord = function () {
- return {
- x: this.sourceCoordX(),
- y: this.sourceCoordY()
- };
- }
-
- this.sourceTangentX = function () {
- return flowchart.computeConnectionSourceTangentX(this.sourceCoord(), this.destCoord());
- };
-
- this.sourceTangentY = function () {
- return flowchart.computeConnectionSourceTangentY(this.sourceCoord(), this.destCoord());
- };
-
- this.destCoordX = function () {
- return this.dest.parentNode().x() + this.dest.x();
- };
-
- this.destCoordY = function () {
- return this.dest.parentNode().y() + this.dest.y();
- };
-
- this.destCoord = function () {
- return {
- x: this.destCoordX(),
- y: this.destCoordY()
- };
- }
-
- this.destTangentX = function () {
- return flowchart.computeConnectionDestTangentX(this.sourceCoord(), this.destCoord());
- };
-
- this.destTangentY = function () {
- return flowchart.computeConnectionDestTangentY(this.sourceCoord(), this.destCoord());
- };
-
- this.middleX = function(scale) {
- if(typeof(scale)=="undefined")
- scale = 0.5;
- return this.sourceCoordX()*(1-scale)+this.destCoordX()*scale;
- };
-
- this.middleY = function(scale) {
- if(typeof(scale)=="undefined")
- scale = 0.5;
- return this.sourceCoordY()*(1-scale)+this.destCoordY()*scale;
- };
-
-
- //
- // Select the connection.
- //
- this.select = function () {
- this._selected = true;
- };
-
- //
- // Deselect the connection.
- //
- this.deselect = function () {
- this._selected = false;
- };
-
- //
- // Toggle the selection state of the connection.
- //
- this.toggleSelected = function () {
- this._selected = !this._selected;
- };
-
- //
- // Returns true if the connection is selected.
- //
- this.selected = function () {
- return this._selected;
- };
- };
-
- //
- // Helper function.
- //
- var computeConnectionTangentOffset = function (pt1, pt2) {
-
- return (pt2.x - pt1.x) / 2;
- }
-
- //
- // Compute the tangent for the bezier curve.
- //
- flowchart.computeConnectionSourceTangentX = function (pt1, pt2) {
-
- return pt1.x + computeConnectionTangentOffset(pt1, pt2);
- };
-
- //
- // Compute the tangent for the bezier curve.
- //
- flowchart.computeConnectionSourceTangentY = function (pt1, pt2) {
-
- return pt1.y;
- };
-
- //
- // Compute the tangent for the bezier curve.
- //
- flowchart.computeConnectionSourceTangent = function(pt1, pt2) {
- return {
- x: flowchart.computeConnectionSourceTangentX(pt1, pt2),
- y: flowchart.computeConnectionSourceTangentY(pt1, pt2),
- };
- };
-
- //
- // Compute the tangent for the bezier curve.
- //
- flowchart.computeConnectionDestTangentX = function (pt1, pt2) {
-
- return pt2.x - computeConnectionTangentOffset(pt1, pt2);
- };
-
- //
- // Compute the tangent for the bezier curve.
- //
- flowchart.computeConnectionDestTangentY = function (pt1, pt2) {
-
- return pt2.y;
- };
-
- //
- // Compute the tangent for the bezier curve.
- //
- flowchart.computeConnectionDestTangent = function(pt1, pt2) {
- return {
- x: flowchart.computeConnectionDestTangentX(pt1, pt2),
- y: flowchart.computeConnectionDestTangentY(pt1, pt2),
- };
- };
-
- //
- // View model for the chart.
- //
- flowchart.ChartViewModel = function (chartDataModel) {
-
- //
- // Find a specific node within the chart.
- //
- this.findNode = function (nodeID) {
-
- for (var i = 0; i < this.nodes.length; ++i) {
- var node = this.nodes[i];
- if (node.data.id == nodeID) {
- return node;
- }
- }
-
- throw new Error("Failed to find node " + nodeID);
- };
-
- //
- // Find a specific input connector within the chart.
- //
- this.findInputConnector = function (nodeID, connectorIndex) {
-
- var node = this.findNode(nodeID);
-
- if (!node.inputConnectors || node.inputConnectors.length <= connectorIndex) {
- throw new Error("Node " + nodeID + " has invalid input connectors.");
- }
-
- return node.inputConnectors[connectorIndex];
- };
-
- //
- // Find a specific output connector within the chart.
- //
- this.findOutputConnector = function (nodeID, connectorIndex) {
-
- var node = this.findNode(nodeID);
-
- if (!node.outputConnectors || node.outputConnectors.length <= connectorIndex) {
- throw new Error("Node " + nodeID + " has invalid output connectors.");
- }
-
- return node.outputConnectors[connectorIndex];
- };
-
- //
- // Create a view model for connection from the data model.
- //
- this._createConnectionViewModel = function(connectionDataModel) {
-
- var sourceConnector = this.findOutputConnector(connectionDataModel.source.nodeID, connectionDataModel.source.connectorIndex);
- var destConnector = this.findInputConnector(connectionDataModel.dest.nodeID, connectionDataModel.dest.connectorIndex);
- return new flowchart.ConnectionViewModel(connectionDataModel, sourceConnector, destConnector);
- }
-
- //
- // Wrap the connections data-model in a view-model.
- //
- this._createConnectionsViewModel = function (connectionsDataModel) {
-
- var connectionsViewModel = [];
-
- if (connectionsDataModel) {
- for (var i = 0; i < connectionsDataModel.length; ++i) {
- connectionsViewModel.push(this._createConnectionViewModel(connectionsDataModel[i]));
- }
- }
-
- return connectionsViewModel;
- };
-
- // Reference to the underlying data.
- this.data = chartDataModel;
-
- // Create a view-model for nodes.
- this.nodes = createNodesViewModel(this.data.nodes);
-
- // Create a view-model for connections.
- this.connections = this._createConnectionsViewModel(this.data.connections);
-
- //
- // Create a view model for a new connection.
- //
- this.createNewConnection = function (startConnector, endConnector) {
-
- var connectionsDataModel = this.data.connections;
- if (!connectionsDataModel) {
- connectionsDataModel = this.data.connections = [];
- }
-
- var connectionsViewModel = this.connections;
- if (!connectionsViewModel) {
- connectionsViewModel = this.connections = [];
- }
-
- var startNode = startConnector.parentNode();
- var startConnectorIndex = startNode.outputConnectors.indexOf(startConnector);
- var startConnectorType = 'output';
- if (startConnectorIndex == -1) {
- startConnectorIndex = startNode.inputConnectors.indexOf(startConnector);
- startConnectorType = 'input';
- if (startConnectorIndex == -1) {
- throw new Error("Failed to find source connector within either inputConnectors or outputConnectors of source node.");
- }
- }
-
- var endNode = endConnector.parentNode();
- var endConnectorIndex = endNode.inputConnectors.indexOf(endConnector);
- var endConnectorType = 'input';
- if (endConnectorIndex == -1) {
- endConnectorIndex = endNode.outputConnectors.indexOf(endConnector);
- endConnectorType = 'output';
- if (endConnectorIndex == -1) {
- throw new Error("Failed to find dest connector within inputConnectors or outputConnectors of dest node.");
- }
- }
-
- for (var i = 0; i < connectionsViewModel.length; i++) {
- if ((endConnectorType == 'input' &&
- connectionsViewModel[i].data.dest.nodeID == endNode.data.id &&
- connectionsViewModel[i].data.dest.connectorIndex == endConnectorIndex) ||
- (startConnectorType == 'input' &&
- connectionsViewModel[i].data.dest.nodeID == startNode.data.id &&
- connectionsViewModel[i].data.dest.connectorIndex == startConnectorIndex)) {
- throw new Error("Multiple input wires not allowed.")
- }
- }
-
- if (startConnectorType == endConnectorType) {
- throw new Error("Failed to create connection. Only output to input connections are allowed.")
- }
-
- if (startNode == endNode) {
- throw new Error("Failed to create connection. Cannot link a node with itself.")
- }
-
- var startNode = {
- nodeID: startNode.data.id,
- connectorIndex: startConnectorIndex,
- }
-
- var endNode = {
- nodeID: endNode.data.id,
- connectorIndex: endConnectorIndex,
- }
-
- var connectionDataModel = {
- source: startConnectorType == 'output' ? startNode : endNode,
- dest: startConnectorType == 'output' ? endNode : startNode,
- };
- connectionsDataModel.push(connectionDataModel);
-
- var outputConnector = startConnectorType == 'output' ? startConnector : endConnector;
- var inputConnector = startConnectorType == 'output' ? endConnector : startConnector;
-
- var connectionViewModel = new flowchart.ConnectionViewModel(connectionDataModel, outputConnector, inputConnector);
- connectionsViewModel.push(connectionViewModel);
- };
-
- //
- // Add a node to the view model.
- //
- this.addNode = function (nodeDataModel) {
- if (!this.data.nodes) {
- this.data.nodes = [];
- }
-
- //
- // Update the data model.
- //
- this.data.nodes.push(nodeDataModel);
-
- //
- // Update the view model.
- //
- this.nodes.push(new flowchart.NodeViewModel(nodeDataModel));
- }
-
- //
- // Select all nodes and connections in the chart.
- //
- this.selectAll = function () {
-
- var editor = ace.edit('editor');
- var nodes = this.nodes;
- for (var i = 0; i < nodes.length; ++i) {
- var node = nodes[i];
- node.select();
- if (node.data.vcode) {
- value = editor.getValue();
- if (value !== '') value += '\n';
- value += node.data.vcode;
- editor.setValue(value, -1);
- }
- }
-
- var connections = this.connections;
- for (var i = 0; i < connections.length; ++i) {
- var connection = connections[i];
- connection.select();
- }
- }
-
- //
- // Deselect all nodes and connections in the chart.
- //
- this.deselectAll = function () {
-
- var nodes = this.nodes;
- for (var i = 0; i < nodes.length; ++i) {
- var node = nodes[i];
- node.deselect();
- }
-
- var connections = this.connections;
- for (var i = 0; i < connections.length; ++i) {
- var connection = connections[i];
- connection.deselect();
- }
- };
-
- //
- // Update the location of the node and its connectors.
- //
- this.updateSelectedNodesLocation = function (deltaX, deltaY) {
-
- var selectedNodes = this.getSelectedNodes();
-
- for (var i = 0; i < selectedNodes.length; ++i) {
- var node = selectedNodes[i];
- node.data.x += deltaX;
- node.data.y += deltaY;
- }
- };
-
- //
- // Handle mouse click on a particular node.
- //
- this.handleNodeClicked = function (node, ctrlKey) {
-
- if (ctrlKey) {
- node.toggleSelected();
- }
- else {
- this.deselectAll();
- node.select();
- if (node.data.vcode) {
- var editor = ace.edit('editor');
- editor.setValue(node.data.vcode, -1);
- }
- }
-
- // Move node to the end of the list so it is rendered after all the other.
- // This is the way Z-order is done in SVG.
-
- var nodeIndex = this.nodes.indexOf(node);
- if (nodeIndex == -1) {
- throw new Error("Failed to find node in view model!");
- }
- this.nodes.splice(nodeIndex, 1);
- this.nodes.push(node);
- };
-
- //
- // Handle mouse down on a connection.
- //
- this.handleConnectionMouseDown = function (connection, ctrlKey) {
-
- if (ctrlKey) {
- connection.toggleSelected();
- }
- else {
- this.deselectAll();
- connection.select();
- }
- };
-
- //
- // Delete all nodes and connections that are selected.
- //
- this.deleteSelected = function () {
-
- var newNodeViewModels = [];
- var newNodeDataModels = [];
-
- var deletedNodeIds = [];
-
- var editor = ace.edit('editor');
- editor.setValue('', -1);
-
- //
- // Sort nodes into:
- // nodes to keep and
- // nodes to delete.
- //
-
- for (var nodeIndex = 0; nodeIndex < this.nodes.length; ++nodeIndex) {
-
- var node = this.nodes[nodeIndex];
- if (!node.selected()) {
- // Only retain non-selected nodes.
- newNodeViewModels.push(node);
- newNodeDataModels.push(node.data);
- }
- else {
- // Keep track of nodes that were deleted, so their connections can also
- // be deleted.
- deletedNodeIds.push(node.data.id);
- }
- }
-
- var newConnectionViewModels = [];
- var newConnectionDataModels = [];
-
- //
- // Remove connections that are selected.
- // Also remove connections for nodes that have been deleted.
- //
- for (var connectionIndex = 0; connectionIndex < this.connections.length; ++connectionIndex) {
-
- var connection = this.connections[connectionIndex];
- if (!connection.selected() &&
- deletedNodeIds.indexOf(connection.data.source.nodeID) === -1 &&
- deletedNodeIds.indexOf(connection.data.dest.nodeID) === -1)
- {
- //
- // The nodes this connection is attached to, where not deleted,
- // so keep the connection.
- //
- newConnectionViewModels.push(connection);
- newConnectionDataModels.push(connection.data);
- }
- }
-
- //
- // Update nodes and connections.
- //
- this.nodes = newNodeViewModels;
- this.data.nodes = newNodeDataModels;
- this.connections = newConnectionViewModels;
- this.data.connections = newConnectionDataModels;
- };
-
- //
- // Select nodes and connections that fall within the selection rect.
- //
- this.applySelectionRect = function (selectionRect) {
-
- this.deselectAll();
-
- var editor = ace.edit('editor');
- editor.setValue('', -1);
-
- for (var i = 0; i < this.nodes.length; ++i) {
- var node = this.nodes[i];
- if (node.x() >= selectionRect.x &&
- node.y() >= selectionRect.y &&
- node.x() + node.width() <= selectionRect.x + selectionRect.width &&
- node.y() + node.height() <= selectionRect.y + selectionRect.height)
- {
- // Select nodes that are within the selection rect.
- node.select();
- if (node.data.vcode) {
- value = editor.getValue();
- if (value !== '') value += '\n';
- value += node.data.vcode;
- editor.setValue(value, -1);
- }
- }
- }
-
- for (var i = 0; i < this.connections.length; ++i) {
- var connection = this.connections[i];
- if (connection.source.parentNode().selected() &&
- connection.dest.parentNode().selected())
- {
- // Select the connection if both its parent nodes are selected.
- connection.select();
- }
- }
-
- };
-
- //
- // Get the array of nodes that are currently selected.
- //
- this.getSelectedNodes = function () {
- var selectedNodes = [];
-
- for (var i = 0; i < this.nodes.length; ++i) {
- var node = this.nodes[i];
- if (node.selected()) {
- selectedNodes.push(node);
- }
- }
-
- return selectedNodes;
- };
-
- //
- // Get the array of connections that are currently selected.
- //
- this.getSelectedConnections = function () {
- var selectedConnections = [];
-
- for (var i = 0; i < this.connections.length; ++i) {
- var connection = this.connections[i];
- if (connection.selected()) {
- selectedConnections.push(connection);
- }
- }
-
- return selectedConnections;
- };
-
-
- };
-
-})();
diff --git a/icestudio/flowchart/flowchart_viewmodel.spec.js b/icestudio/flowchart/flowchart_viewmodel.spec.js
deleted file mode 100644
index d2ab771e9..000000000
--- a/icestudio/flowchart/flowchart_viewmodel.spec.js
+++ /dev/null
@@ -1,1282 +0,0 @@
-describe('flowchart-viewmodel', function () {
-
- //
- // Create a mock data model from a simple definition.
- //
- var createMockDataModel = function (nodeIds, connections) {
-
- var nodeDataModels = null;
-
- if (nodeIds) {
- nodeDataModels = [];
-
- for (var i = 0; i < nodeIds.length; ++i) {
- nodeDataModels.push({
- id: nodeIds[i],
- x: 0,
- y: 0,
- inputConnectors: [ {}, {}, {} ],
- outputConnectors: [ {}, {}, {} ],
- });
- }
- }
-
- var connectionDataModels = null;
-
- if (connections) {
- connectionDataModels = [];
-
- for (var i = 0; i < connections.length; ++i) {
- connectionDataModels.push({
- source: {
- nodeID: connections[i][0][0],
- connectorIndex: connections[i][0][1],
- },
- dest: {
- nodeID: connections[i][1][0],
- connectorIndex: connections[i][1][1],
- },
- });
- }
- }
-
- var dataModel = {};
-
- if (nodeDataModels) {
- dataModel.nodes = nodeDataModels;
- }
-
- if (connectionDataModels) {
- dataModel.connections = connectionDataModels;
- }
-
- return dataModel;
- };
-
- it('compute input connector pos', function () {
-
- var mockNode = {
- x: function () { return 10 },
- y: function () { return 15 },
- };
-
- flowchart.computeConnectorPos(mockNode, 0, true);
- flowchart.computeConnectorPos(mockNode, 1, true);
- flowchart.computeConnectorPos(mockNode, 2, true);
- });
-
- it('compute output connector pos', function () {
-
- var mockNode = {
- x: function () { return 10 },
- y: function () { return 15 },
- };
-
- flowchart.computeConnectorPos(mockNode, 0, false);
- flowchart.computeConnectorPos(mockNode, 1, false);
- flowchart.computeConnectorPos(mockNode, 2, false);
- });
-
- it('construct ConnectorViewModel', function () {
-
- var mockDataModel = {
- name: "Fooey",
- };
-
- new flowchart.ConnectorViewModel(mockDataModel, 0, 10, 0);
- new flowchart.ConnectorViewModel(mockDataModel, 0, 10, 1);
- new flowchart.ConnectorViewModel(mockDataModel, 0, 10, 2);
-
- });
-
- it('ConnectorViewModel has reference to parent node', function () {
-
- var mockDataModel = {
- name: "Fooey",
- };
- var mockParentNodeViewModel = {};
-
- var testObject = new flowchart.ConnectorViewModel(mockDataModel, 0, 10, mockParentNodeViewModel);
-
- expect(testObject.parentNode()).toBe(mockParentNodeViewModel);
- });
-
- it('construct NodeViewModel with no connectors', function () {
-
- var mockDataModel = {
- x: 10,
- y: 12,
- name: "Woot",
- };
-
- new flowchart.NodeViewModel(mockDataModel);
- });
-
- it('construct NodeViewModel with empty connectors', function () {
-
- var mockDataModel = {
- x: 10,
- y: 12,
- name: "Woot",
- inputConnectors: [],
- outputConnectors: [],
- };
-
- new flowchart.NodeViewModel(mockDataModel);
- });
-
- it('construct NodeViewModel with connectors', function () {
-
- var mockInputConnector = {
- name: "Input",
- };
-
- var mockOutputConnector = {
- name: "Output",
- };
-
- var mockDataModel = {
- x: 10,
- y: 12,
- name: "Woot",
- inputConnectors: [
- mockInputConnector
- ],
- outputConnectors: [
- mockOutputConnector
- ],
- };
-
- new flowchart.NodeViewModel(mockDataModel);
- });
-
- it('test name of NodeViewModel', function () {
-
- var mockDataModel = {
- name: "Woot",
- };
-
- var testObject = new flowchart.NodeViewModel(mockDataModel);
-
- expect(testObject.name()).toBe(mockDataModel.name);
- });
-
- it('test name of NodeViewModel defaults to empty string', function () {
-
- var mockDataModel = {};
-
- var testObject = new flowchart.NodeViewModel(mockDataModel);
-
- expect(testObject.name()).toBe("");
- });
-
- it('test node is deselected by default', function () {
-
- var mockDataModel = {};
-
- var testObject = new flowchart.NodeViewModel(mockDataModel);
-
- expect(testObject.selected()).toBe(false);
- });
-
- it('test node width is set by default', function () {
-
- var mockDataModel = {};
-
- var testObject = new flowchart.NodeViewModel(mockDataModel);
-
- expect(testObject.width() === flowchart.defaultNodeWidth).toBe(true);
- });
-
- it('test node width is used', function () {
-
- var mockDataModel = {"width": 900 };
-
- var testObject = new flowchart.NodeViewModel(mockDataModel);
-
- expect(testObject.width()).toBe(900);
- });
-
- it('test computeConnectorPos uses node width', function () {
-
- var mockDataModel = {
- x: function () {
- return 10;
- },
- y: function () {
- return 15;
- },
- width: function () {
- return 900;
- },
- };
-
- var testObject = flowchart.computeConnectorPos(mockDataModel, 1, false);
-
- expect(testObject.x).toBe(910);
- });
-
- it('test computeConnectorPos uses default node width', function () {
-
- var mockDataModel = {
- x: function () {
- return 10
- },
- y: function () {
- return 15
- },
- };
-
- var testObject = flowchart.computeConnectorPos(mockDataModel, 1, false);
-
- expect(testObject.x).toBe(flowchart.defaultNodeWidth + 10);
- });
-
- it('test node can be selected', function () {
-
- var mockDataModel = {};
-
- var testObject = new flowchart.NodeViewModel(mockDataModel);
-
- testObject.select();
-
- expect(testObject.selected()).toBe(true);
- });
-
- it('test node can be deselected', function () {
-
- var mockDataModel = {};
-
- var testObject = new flowchart.NodeViewModel(mockDataModel);
-
- testObject.select();
-
- testObject.deselect();
-
- expect(testObject.selected()).toBe(false);
- });
-
- it('test node can be selection can be toggled', function () {
-
- var mockDataModel = {};
-
- var testObject = new flowchart.NodeViewModel(mockDataModel);
-
- testObject.toggleSelected();
-
- expect(testObject.selected()).toBe(true);
-
- testObject.toggleSelected();
-
- expect(testObject.selected()).toBe(false);
- });
-
- it('test can add input connector to node', function () {
-
- var mockDataModel = {};
-
- var testObject = new flowchart.NodeViewModel(mockDataModel);
-
- var name1 = "Connector1";
- var name2 = "Connector2";
- var data1 = {
- name: name1
- };
- var data2 = {
- name: name2
- }
- testObject.addInputConnector(data1);
- testObject.addInputConnector(data2);
-
- expect(testObject.inputConnectors.length).toBe(2);
- expect(testObject.inputConnectors[0].data).toBe(data1);
- expect(testObject.inputConnectors[1].data).toBe(data2);
-
- expect(testObject.data.inputConnectors.length).toBe(2);
- expect(testObject.data.inputConnectors[0]).toBe(data1);
- expect(testObject.data.inputConnectors[1]).toBe(data2);
- });
-
- it('test can add output connector to node', function () {
-
- var mockDataModel = {};
-
- var testObject = new flowchart.NodeViewModel(mockDataModel);
-
- var name1 = "Connector1";
- var name2 = "Connector2";
- var data1 = {
- name: name1
- };
- var data2 = {
- name: name2
- }
- testObject.addOutputConnector(data1);
- testObject.addOutputConnector(data2);
-
- expect(testObject.outputConnectors.length).toBe(2);
- expect(testObject.outputConnectors[0].data).toBe(data1);
- expect(testObject.outputConnectors[1].data).toBe(data2);
-
- expect(testObject.data.outputConnectors.length).toBe(2);
- expect(testObject.data.outputConnectors[0]).toBe(data1);
- expect(testObject.data.outputConnectors[1]).toBe(data2);
- });
-
- it('construct ChartViewModel with no nodes or connections', function () {
-
- var mockDataModel = {};
-
- new flowchart.ChartViewModel(mockDataModel);
-
- });
-
- it('construct ChartViewModel with empty nodes and connections', function () {
-
- var mockDataModel = {
- nodes: [],
- connections: [],
- };
-
- new flowchart.ChartViewModel(mockDataModel);
-
- });
-
- it('construct ConnectionViewModel', function () {
-
- var mockDataModel = {};
- var mockSourceConnector = {};
- var mockDestConnector = {};
-
- new flowchart.ConnectionViewModel(mockDataModel, mockSourceConnector, mockDestConnector);
- });
-
- it('retreive source and dest coordinates', function () {
-
- var mockDataModel = {
- };
-
- var mockSourceParentNode = {
- x: function () { return 5 },
- y: function () { return 10 },
- };
-
- var mockSourceConnector = {
- parentNode: function () {
- return mockSourceParentNode;
- },
-
- x: function() {
- return 5;
- },
-
- y: function() {
- return 15;
- },
- };
-
- var mockDestParentNode = {
- x: function () { return 50 },
- y: function () { return 30 },
- };
-
- var mockDestConnector = {
- parentNode: function () {
- return mockDestParentNode;
- },
-
- x: function() {
- return 25;
- },
-
- y: function() {
- return 35;
- },
- };
-
- var testObject = new flowchart.ConnectionViewModel(mockDataModel, mockSourceConnector, mockDestConnector);
-
- testObject.sourceCoord();
- expect(testObject.sourceCoordX()).toBe(10);
- expect(testObject.sourceCoordY()).toBe(25);
- testObject.sourceTangentX();
- testObject.sourceTangentY();
-
- testObject.destCoord();
- expect(testObject.destCoordX()).toBe(75);
- expect(testObject.destCoordY()).toBe(65);
- testObject.destTangentX();
- testObject.destTangentY();
- });
-
- it('test connection is deselected by default', function () {
-
- var mockDataModel = {};
-
- var testObject = new flowchart.ConnectionViewModel(mockDataModel);
-
- expect(testObject.selected()).toBe(false);
- });
-
- it('test connection can be selected', function () {
-
- var mockDataModel = {};
-
- var testObject = new flowchart.ConnectionViewModel(mockDataModel);
-
- testObject.select();
-
- expect(testObject.selected()).toBe(true);
- });
-
- it('test connection can be deselected', function () {
-
- var mockDataModel = {};
-
- var testObject = new flowchart.ConnectionViewModel(mockDataModel);
-
- testObject.select();
-
- testObject.deselect();
-
- expect(testObject.selected()).toBe(false);
- });
-
- it('test connection can be selection can be toggled', function () {
-
- var mockDataModel = {};
-
- var testObject = new flowchart.ConnectionViewModel(mockDataModel);
-
- testObject.toggleSelected();
-
- expect(testObject.selected()).toBe(true);
-
- testObject.toggleSelected();
-
- expect(testObject.selected()).toBe(false);
- });
-
- it('construct ChartViewModel with a node', function () {
-
- var mockDataModel = createMockDataModel([1]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
- expect(testObject.nodes.length).toBe(1);
- expect(testObject.nodes[0].data).toBe(mockDataModel.nodes[0]);
-
- });
-
- it('data model with existing connection creates a connection view model', function () {
-
- var mockDataModel = createMockDataModel(
- [ 5, 12 ],
- [
- [[ 5, 0 ], [ 12, 1 ]],
- ]
- );
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(testObject.connections.length).toBe(1);
- expect(testObject.connections[0].data).toBe(mockDataModel.connections[0]);
- expect(testObject.connections[0].source.data).toBe(mockDataModel.nodes[0].outputConnectors[0]);
- expect(testObject.connections[0].dest.data).toBe(mockDataModel.nodes[1].inputConnectors[1]);
- });
-
- it('test can add new node', function () {
-
- var mockDataModel = createMockDataModel();
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var nodeDataModel = {};
- testObject.addNode(nodeDataModel);
-
- expect(testObject.nodes.length).toBe(1);
- expect(testObject.nodes[0].data).toBe(nodeDataModel);
-
- expect(testObject.data.nodes.length).toBe(1);
- expect(testObject.data.nodes[0]).toBe(nodeDataModel);
- });
-
- it('test can select all', function () {
-
- var mockDataModel = createMockDataModel([1, 2], [[[1, 0], [2, 1]]]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var node1 = testObject.nodes[0];
- var node2 = testObject.nodes[1];
- var connection = testObject.connections[0];
-
- testObject.selectAll();
-
- expect(node1.selected()).toBe(true);
- expect(node2.selected()).toBe(true);
- expect(connection.selected()).toBe(true);
- });
-
- it('test can deselect all nodes', function () {
-
- var mockDataModel = createMockDataModel([1, 2]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var node1 = testObject.nodes[0];
- var node2 = testObject.nodes[1];
-
- node1.select();
- node2.select();
-
- testObject.deselectAll();
-
- expect(node1.selected()).toBe(false);
- expect(node2.selected()).toBe(false);
- });
-
- it('test can deselect all connections', function () {
-
- var mockDataModel = createMockDataModel(
- [ 5, 12 ],
- [
- [[ 5, 0 ], [ 12, 1 ]],
- [[ 5, 0 ], [ 12, 1 ]],
- ]
- );
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var connection1 = testObject.connections[0];
- var connection2 = testObject.connections[1];
-
- connection1.select();
- connection2.select();
-
- testObject.deselectAll();
-
- expect(connection1.selected()).toBe(false);
- expect(connection2.selected()).toBe(false);
- });
-
- it('test mouse down deselects nodes other than the one clicked', function () {
-
- var mockDataModel = createMockDataModel([ 1, 2, 3 ]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var node1 = testObject.nodes[0];
- var node2 = testObject.nodes[1];
- var node3 = testObject.nodes[2];
-
- // Fake out the nodes as selected.
- node1.select();
- node2.select();
- node3.select();
-
- testObject.handleNodeClicked(node2); // Doesn't matter which node is actually clicked.
-
- expect(node1.selected()).toBe(false);
- expect(node2.selected()).toBe(true);
- expect(node3.selected()).toBe(false);
- });
-
- it('test mouse down selects the clicked node', function () {
-
- var mockDataModel = createMockDataModel([ 1, 2, 3 ]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var node1 = testObject.nodes[0];
- var node2 = testObject.nodes[1];
- var node3 = testObject.nodes[2];
-
- testObject.handleNodeClicked(node3); // Doesn't matter which node is actually clicked.
-
- expect(node1.selected()).toBe(false);
- expect(node2.selected()).toBe(false);
- expect(node3.selected()).toBe(true);
- });
-
- it('test mouse down brings node to front', function () {
-
- var mockDataModel = createMockDataModel([ 1, 2 ]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var node1 = testObject.nodes[0];
- var node2 = testObject.nodes[1];
-
- testObject.handleNodeClicked(node1);
-
- expect(testObject.nodes[0]).toBe(node2); // Mock node 2 should be bought to front.
- expect(testObject.nodes[1]).toBe(node1);
- });
-
- it('test control + mouse down toggles node selection', function () {
-
- var mockDataModel = createMockDataModel([ 1, 2, 3 ]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var node1 = testObject.nodes[0];
- var node2 = testObject.nodes[1];
- var node3 = testObject.nodes[2];
-
- node1.select(); // Mark node 1 as already selected.
-
- testObject.handleNodeClicked(node2, true);
-
- expect(node1.selected()).toBe(true); // This node remains selected.
- expect(node2.selected()).toBe(true); // This node is being toggled.
- expect(node3.selected()).toBe(false); // This node remains unselected.
-
- testObject.handleNodeClicked(node2, true);
-
- expect(node1.selected()).toBe(true); // This node remains selected.
- expect(node2.selected()).toBe(false); // This node is being toggled.
- expect(node3.selected()).toBe(false); // This node remains unselected.
-
- testObject.handleNodeClicked(node2, true);
-
- expect(node1.selected()).toBe(true); // This node remains selected.
- expect(node2.selected()).toBe(true); // This node is being toggled.
- expect(node3.selected()).toBe(false); // This node remains unselected.
- });
-
- it('test mouse down deselects connections other than the one clicked', function () {
-
- var mockDataModel = createMockDataModel(
- [ 1, 2, 3 ],
- [
- [[ 1, 0 ], [ 3, 0 ]],
- [[ 2, 1 ], [ 3, 2 ]],
- [[ 1, 2 ], [ 3, 0 ]]
- ]
- );
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var connection1 = testObject.connections[0];
- var connection2 = testObject.connections[1];
- var connection3 = testObject.connections[2];
-
- // Fake out the connections as selected.
- connection1.select();
- connection2.select();
- connection3.select();
-
- testObject.handleConnectionMouseDown(connection2);
-
- expect(connection1.selected()).toBe(false);
- expect(connection2.selected()).toBe(true);
- expect(connection3.selected()).toBe(false);
- });
-
- it('test node mouse down selects the clicked connection', function () {
-
- var mockDataModel = createMockDataModel(
- [ 1, 2, 3 ],
- [
- [[ 1, 0 ], [ 3, 0 ]],
- [[ 2, 1 ], [ 3, 2 ]],
- [[ 1, 2 ], [ 3, 0 ]]
- ]
- );
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var connection1 = testObject.connections[0];
- var connection2 = testObject.connections[1];
- var connection3 = testObject.connections[2];
-
- testObject.handleConnectionMouseDown(connection3);
-
- expect(connection1.selected()).toBe(false);
- expect(connection2.selected()).toBe(false);
- expect(connection3.selected()).toBe(true);
- });
-
- it('test control + mouse down toggles connection selection', function () {
-
- var mockDataModel = createMockDataModel(
- [ 1, 2, 3 ],
- [
- [[ 1, 0 ], [ 3, 0 ]],
- [[ 2, 1 ], [ 3, 2 ]],
- [[ 1, 2 ], [ 3, 0 ]]
- ]
- );
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var connection1 = testObject.connections[0];
- var connection2 = testObject.connections[1];
- var connection3 = testObject.connections[2];
-
- connection1.select(); // Mark connection 1 as already selected.
-
- testObject.handleConnectionMouseDown(connection2, true);
-
- expect(connection1.selected()).toBe(true); // This connection remains selected.
- expect(connection2.selected()).toBe(true); // This connection is being toggle.
- expect(connection3.selected()).toBe(false); // This connection remains unselected.
-
- testObject.handleConnectionMouseDown(connection2, true);
-
- expect(connection1.selected()).toBe(true); // This connection remains selected.
- expect(connection2.selected()).toBe(false); // This connection is being toggle.
- expect(connection3.selected()).toBe(false); // This connection remains unselected.
-
- testObject.handleConnectionMouseDown(connection2, true);
-
- expect(connection1.selected()).toBe(true); // This connection remains selected.
- expect(connection2.selected()).toBe(true); // This connection is being toggle.
- expect(connection3.selected()).toBe(false); // This connection remains unselected.
- });
-
- it('test data-model is wrapped in view-model', function () {
-
- var mockDataModel = createMockDataModel([ 1, 2 ], [[[1, 0], [2, 0]]]);
- var mockNode = mockDataModel.nodes[0];
- var mockInputConnector = mockNode.inputConnectors[0];
- var mockOutputConnector = mockNode.outputConnectors[0];
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- // Chart
-
- expect(testObject).toBeDefined();
- expect(testObject).toNotBe(mockDataModel);
- expect(testObject.data).toBe(mockDataModel);
- expect(testObject.nodes).toBeDefined();
- expect(testObject.nodes.length).toBe(2);
-
- // Node
-
- var node = testObject.nodes[0];
-
- expect(node).toNotBe(mockNode);
- expect(node.data).toBe(mockNode);
-
- // Connectors
-
- expect(node.inputConnectors.length).toBe(3);
- expect(node.inputConnectors[0].data).toBe(mockInputConnector);
-
- expect(node.outputConnectors.length).toBe(3);
- expect(node.outputConnectors[0].data).toBe(mockOutputConnector);
-
- // Connection
-
- expect(testObject.connections.length).toBe(1);
- expect(testObject.connections[0].source).toBe(testObject.nodes[0].outputConnectors[0]);
- expect(testObject.connections[0].dest).toBe(testObject.nodes[1].inputConnectors[0]);
- });
-
- it('test can delete 1st selected node', function () {
-
- var mockDataModel = createMockDataModel([ 1, 2 ]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(testObject.nodes.length).toBe(2);
-
- testObject.nodes[0].select();
-
- var mockNode2 = mockDataModel.nodes[1];
-
- testObject.deleteSelected();
-
- expect(testObject.nodes.length).toBe(1);
- expect(mockDataModel.nodes.length).toBe(1);
- expect(testObject.nodes[0].data).toBe(mockNode2);
- });
-
- it('test can delete 2nd selected nodes', function () {
-
- var mockDataModel = createMockDataModel([ 1, 2 ]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(testObject.nodes.length).toBe(2);
-
- testObject.nodes[1].select();
-
- var mockNode1 = mockDataModel.nodes[0];
-
- testObject.deleteSelected();
-
- expect(testObject.nodes.length).toBe(1);
- expect(mockDataModel.nodes.length).toBe(1);
- expect(testObject.nodes[0].data).toBe(mockNode1);
- });
-
- it('test can delete multiple selected nodes', function () {
-
- var mockDataModel = createMockDataModel([ 1, 2, 3, 4 ]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(testObject.nodes.length).toBe(4);
-
- testObject.nodes[1].select();
- testObject.nodes[2].select();
-
- var mockNode1 = mockDataModel.nodes[0];
- var mockNode4 = mockDataModel.nodes[3];
-
- testObject.deleteSelected();
-
- expect(testObject.nodes.length).toBe(2);
- expect(mockDataModel.nodes.length).toBe(2);
- expect(testObject.nodes[0].data).toBe(mockNode1);
- expect(testObject.nodes[1].data).toBe(mockNode4);
- });
-
- it('deleting a node also deletes its connections', function () {
-
- var mockDataModel = createMockDataModel(
- [ 1, 2, 3 ],
- [
- [[ 1, 0 ], [ 2, 0 ]],
- [[ 2, 0 ], [ 3, 0 ]],
- ]
- );
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(testObject.connections.length).toBe(2);
-
- // Select the middle node.
- testObject.nodes[1].select();
-
- testObject.deleteSelected();
-
- expect(testObject.connections.length).toBe(0);
- });
-
- it('deleting a node doesnt delete other connections', function () {
-
- var mockDataModel = createMockDataModel(
- [ 1, 2, 3 ],
- [
- [[ 1, 0 ], [ 3, 0 ],]
- ]
- );
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(testObject.connections.length).toBe(1);
-
- // Select the middle node.
- testObject.nodes[1].select();
-
- testObject.deleteSelected();
-
- expect(testObject.connections.length).toBe(1);
- });
-
- it('test can delete 1st selected connection', function () {
-
- var mockDataModel = createMockDataModel(
- [ 1, 2 ],
- [
- [[ 1, 0 ], [ 2, 0 ]],
- [[ 2, 1 ], [ 1, 2 ]]
- ]
- );
-
- var mockRemainingConnectionDataModel = mockDataModel.connections[1];
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(testObject.connections.length).toBe(2);
-
- testObject.connections[0].select();
-
- testObject.deleteSelected();
-
- expect(testObject.connections.length).toBe(1);
- expect(mockDataModel.connections.length).toBe(1);
- expect(testObject.connections[0].data).toBe(mockRemainingConnectionDataModel);
- });
-
- it('test can delete 2nd selected connection', function () {
-
- var mockDataModel = createMockDataModel(
- [ 1, 2 ],
- [
- [[ 1, 0 ], [ 2, 0 ]],
- [[ 2, 1 ], [ 1, 2 ]]
- ]
- );
-
- var mockRemainingConnectionDataModel = mockDataModel.connections[0];
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(testObject.connections.length).toBe(2);
-
- testObject.connections[1].select();
-
- testObject.deleteSelected();
-
- expect(testObject.connections.length).toBe(1);
- expect(mockDataModel.connections.length).toBe(1);
- expect(testObject.connections[0].data).toBe(mockRemainingConnectionDataModel);
- });
-
-
- it('test can delete multiple selected connections', function () {
-
- var mockDataModel = createMockDataModel(
- [ 1, 2, 3 ],
- [
- [[ 1, 0 ], [ 2, 0 ]],
- [[ 2, 1 ], [ 1, 2 ]],
- [[ 1, 1 ], [ 3, 0 ]],
- [[ 3, 2 ], [ 2, 1 ]]
- ]
- );
-
- var mockRemainingConnectionDataModel1 = mockDataModel.connections[0];
- var mockRemainingConnectionDataModel2 = mockDataModel.connections[3];
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(testObject.connections.length).toBe(4);
-
- testObject.connections[1].select();
- testObject.connections[2].select();
-
- testObject.deleteSelected();
-
- expect(testObject.connections.length).toBe(2);
- expect(mockDataModel.connections.length).toBe(2);
- expect(testObject.connections[0].data).toBe(mockRemainingConnectionDataModel1);
- expect(testObject.connections[1].data).toBe(mockRemainingConnectionDataModel2);
- });
-
- it('can select nodes via selection rect', function () {
-
- var mockDataModel = createMockDataModel([ 1, 2, 3 ]);
- mockDataModel.nodes[0].x = 0;
- mockDataModel.nodes[0].y = 0;
- mockDataModel.nodes[1].x = 1020;
- mockDataModel.nodes[1].y = 1020;
- mockDataModel.nodes[2].x = 3000;
- mockDataModel.nodes[2].y = 3000;
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- testObject.nodes[0].select(); // Select a nodes, to ensure it is correctly deselected.
-
- testObject.applySelectionRect({ x: 1000, y: 1000, width: 1000, height: 1000 });
-
- expect(testObject.nodes[0].selected()).toBe(false);
- expect(testObject.nodes[1].selected()).toBe(true);
- expect(testObject.nodes[2].selected()).toBe(false);
- });
-
- it('can select connections via selection rect', function () {
-
- var mockDataModel = createMockDataModel(
- [ 1, 2, 3, 4 ],
- [
- [[ 1, 0 ], [ 2, 0 ]],
- [[ 2, 1 ], [ 3, 2 ]],
- [[ 3, 2 ], [ 4, 1 ]]
- ]
- );
- mockDataModel.nodes[0].x = 0;
- mockDataModel.nodes[0].y = 0;
- mockDataModel.nodes[1].x = 1020;
- mockDataModel.nodes[1].y = 1020;
- mockDataModel.nodes[2].x = 1500;
- mockDataModel.nodes[2].y = 1500;
- mockDataModel.nodes[3].x = 3000;
- mockDataModel.nodes[3].y = 3000;
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- testObject.connections[0].select(); // Select a connection, to ensure it is correctly deselected.
-
- testObject.applySelectionRect({ x: 1000, y: 1000, width: 1000, height: 1000 });
-
- expect(testObject.connections[0].selected()).toBe(false);
- expect(testObject.connections[1].selected()).toBe(true);
- expect(testObject.connections[2].selected()).toBe(false);
- });
-
- it('test update selected nodes location', function () {
- var mockDataModel = createMockDataModel([1]);
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var node = testObject.nodes[0];
- node.select();
-
- var xInc = 5;
- var yInc = 15;
-
- testObject.updateSelectedNodesLocation(xInc, yInc);
-
- expect(node.x()).toBe(xInc);
- expect(node.y()).toBe(yInc);
- });
-
- it('test update selected nodes location, ignores unselected nodes', function () {
- var mockDataModel = createMockDataModel([1]);
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var node = testObject.nodes[0];
-
- var xInc = 5;
- var yInc = 15;
-
- testObject.updateSelectedNodesLocation(xInc, yInc);
-
- expect(node.x()).toBe(0);
- expect(node.y()).toBe(0);
- });
-
- it('test find node throws when there are no nodes', function () {
- var mockDataModel = createMockDataModel();
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(function () { testObject.findNode(150); }).toThrow();
- });
-
- it('test find node throws when node is not found', function () {
- var mockDataModel = createMockDataModel([5, 25, 15, 30]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(function () { testObject.findNode(150); }).toThrow();
- });
-
- it('test find node retreives correct node', function () {
- var mockDataModel = createMockDataModel([5, 25, 15, 30]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(testObject.findNode(15)).toBe(testObject.nodes[2]);
- });
-
- it('test find input connector throws when there are no nodes', function () {
- var mockDataModel = createMockDataModel();
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(function () { testObject.findInputConnector(150, 1); }).toThrow();
- });
-
- it('test find input connector throws when the node is not found', function () {
- var mockDataModel = createMockDataModel([ 1, 2, 3]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(function () { testObject.findInputConnector(150, 1); }).toThrow();
- });
-
- it('test find input connector throws when there are no connectors', function () {
- var mockDataModel = createMockDataModel([ 1 ]);
-
- mockDataModel.nodes[0].inputConnectors = [];
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(function () { testObject.findInputConnector(1, 1); }).toThrow();
- });
-
- it('test find input connector throws when connector is not found', function () {
- var mockDataModel = createMockDataModel([5]);
-
- mockDataModel.nodes[0].inputConnectors = [
- {} // Only 1 input connector.
- ];
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(function () { testObject.findInputConnector(5, 1); }).toThrow();
- });
-
- it('test find input connector retreives correct connector', function () {
- var mockDataModel = createMockDataModel([5, 25, 15, 30]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(testObject.findInputConnector(15, 1)).toBe(testObject.nodes[2].inputConnectors[1]);
- });
-
- it('test find output connector throws when there are no nodes', function () {
- var mockDataModel = createMockDataModel();
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(function () { testObject.findOutputConnector(150, 1); }).toThrow();
- });
-
- it('test find output connector throws when the node is not found', function () {
- var mockDataModel = createMockDataModel([ 1, 2, 3]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(function () { testObject.findOutputConnector(150, 1); }).toThrow();
- });
-
- it('test find output connector throws when there are no connectors', function () {
- var mockDataModel = createMockDataModel([ 1 ]);
-
- mockDataModel.nodes[0].outputConnectors = [];
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(function () { testObject.findOutputConnector(1, 1); }).toThrow();
- });
-
- it('test find output connector throws when connector is not found', function () {
- var mockDataModel = createMockDataModel([5]);
-
- mockDataModel.nodes[0].outputConnectors = [
- {} // Only 1 input connector.
- ];
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(function () { testObject.findOutputConnector(5, 1); }).toThrow();
- });
-
- it('test find output connector retreives correct connector', function () {
- var mockDataModel = createMockDataModel([5, 25, 15, 30]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- expect(testObject.findOutputConnector(15, 1)).toBe(testObject.nodes[2].outputConnectors[1]);
- });
-
-
- it('test create new connection', function () {
-
- var mockDataModel = createMockDataModel([5, 25]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var startConnector = testObject.nodes[0].outputConnectors[0];
- var endConnector = testObject.nodes[1].inputConnectors[1];
-
- testObject.createNewConnection(startConnector, endConnector);
-
- expect(testObject.connections.length).toBe(1);
- var connection = testObject.connections[0];
- expect(connection.source).toBe(startConnector);
- expect(connection.dest).toBe(endConnector);
-
- expect(testObject.data.connections.length).toBe(1);
- var connectionData = testObject.data.connections[0];
- expect(connection.data).toBe(connectionData);
-
- expect(connectionData.source.nodeID).toBe(5);
- expect(connectionData.source.connectorIndex).toBe(0);
- expect(connectionData.dest.nodeID).toBe(25);
- expect(connectionData.dest.connectorIndex).toBe(1);
- });
-
- it('test create new connection from input to output', function () {
-
- var mockDataModel = createMockDataModel([5, 25]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var startConnector = testObject.nodes[1].inputConnectors[1];
- var endConnector = testObject.nodes[0].outputConnectors[0];
-
- testObject.createNewConnection(startConnector, endConnector);
-
- expect(testObject.connections.length).toBe(1);
- var connection = testObject.connections[0];
- expect(connection.source).toBe(endConnector);
- expect(connection.dest).toBe(startConnector);
-
- expect(testObject.data.connections.length).toBe(1);
- var connectionData = testObject.data.connections[0];
- expect(connection.data).toBe(connectionData);
-
- expect(connectionData.source.nodeID).toBe(5);
- expect(connectionData.source.connectorIndex).toBe(0);
- expect(connectionData.dest.nodeID).toBe(25);
- expect(connectionData.dest.connectorIndex).toBe(1);
- });
-
- it('test get selected nodes results in empty array when there are no nodes', function () {
-
- var mockDataModel = createMockDataModel();
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var selectedNodes = testObject.getSelectedNodes();
-
- expect(selectedNodes.length).toBe(0);
- });
-
- it('test get selected nodes results in empty array when none selected', function () {
-
- var mockDataModel = createMockDataModel([1, 2, 3, 4]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var selectedNodes = testObject.getSelectedNodes();
-
- expect(selectedNodes.length).toBe(0);
- });
-
- it('test can get selected nodes', function () {
-
- var mockDataModel = createMockDataModel([1, 2, 3, 4]);
-
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var node1 = testObject.nodes[0];
- var node2 = testObject.nodes[1];
- var node3 = testObject.nodes[2];
- var node4 = testObject.nodes[3];
-
- node2.select();
- node3.select();
-
- var selectedNodes = testObject.getSelectedNodes();
-
- expect(selectedNodes.length).toBe(2);
- expect(selectedNodes[0]).toBe(node2);
- expect(selectedNodes[1]).toBe(node3);
- });
-
- it('test can get selected connections', function () {
-
- var mockDataModel = createMockDataModel(
- [ 1, 2, 3 ],
- [
- [[ 1, 0 ], [ 2, 0 ]],
- [[ 2, 1 ], [ 1, 2 ]],
- [[ 1, 1 ], [ 3, 0 ]],
- [[ 3, 2 ], [ 2, 1 ]]
- ]
- );
- var testObject = new flowchart.ChartViewModel(mockDataModel);
-
- var connection1 = testObject.connections[0];
- var connection2 = testObject.connections[1];
- var connection3 = testObject.connections[2];
- var connection4 = testObject.connections[3];
-
- connection2.select();
- connection3.select();
-
- var selectedConnections = testObject.getSelectedConnections();
-
- expect(selectedConnections.length).toBe(2);
- expect(selectedConnections[0]).toBe(connection2);
- expect(selectedConnections[1]).toBe(connection3);
- });
-});
diff --git a/icestudio/flowchart/mouse_capture_service.js b/icestudio/flowchart/mouse_capture_service.js
deleted file mode 100644
index 827a166e7..000000000
--- a/icestudio/flowchart/mouse_capture_service.js
+++ /dev/null
@@ -1,124 +0,0 @@
-
-angular.module('mouseCapture', [])
-
-//
-// Service used to acquire 'mouse capture' then receive dragging events while the mouse is captured.
-//
-.factory('mouseCapture', [ '$rootScope', function ($rootScope) {
-
- //
- // Element that the mouse capture applies to, defaults to 'document'
- // unless the 'mouse-capture' directive is used.
- //
- var $element = document;
-
- //
- // Set when mouse capture is acquired to an object that contains
- // handlers for 'mousemove' and 'mouseup' events.
- //
- var mouseCaptureConfig = null;
-
- //
- // Handler for mousemove events while the mouse is 'captured'.
- //
- var mouseMove = function (evt) {
-
- if (mouseCaptureConfig && mouseCaptureConfig.mouseMove) {
-
- mouseCaptureConfig.mouseMove(evt);
-
- $rootScope.$digest();
- }
- };
-
- //
- // Handler for mouseup event while the mouse is 'captured'.
- //
- var mouseUp = function (evt) {
-
- if (mouseCaptureConfig && mouseCaptureConfig.mouseUp) {
-
- mouseCaptureConfig.mouseUp(evt);
-
- $rootScope.$digest();
- }
- };
-
- return {
-
- //
- // Register an element to use as the mouse capture element instead of
- // the default which is the document.
- //
- registerElement: function(element) {
-
- $element = element;
- },
-
- //
- // Acquire the 'mouse capture'.
- // After acquiring the mouse capture mousemove and mouseup events will be
- // forwarded to callbacks in 'config'.
- //
- acquire: function (evt, config) {
-
- //
- // Release any prior mouse capture.
- //
- this.release();
-
- mouseCaptureConfig = config;
-
- //
- // In response to the mousedown event register handlers for mousemove and mouseup
- // during 'mouse capture'.
- //
- $element.mousemove(mouseMove);
- $element.mouseup(mouseUp);
- },
-
- //
- // Release the 'mouse capture'.
- //
- release: function () {
-
- if (mouseCaptureConfig) {
-
- if (mouseCaptureConfig.released) {
- //
- // Let the client know that their 'mouse capture' has been released.
- //
- mouseCaptureConfig.released();
- }
-
- mouseCaptureConfig = null;
- }
-
- $element.unbind("mousemove", mouseMove);
- $element.unbind("mouseup", mouseUp);
- },
- };
-}]
-)
-
-//
-// Directive that marks the mouse capture element.
-//
-.directive('mouseCapture', function () {
- return {
- restrict: 'A',
-
- controller: ['$scope', '$element', '$attrs', 'mouseCapture',
- function($scope, $element, $attrs, mouseCapture) {
-
- //
- // Register the directives element as the mouse capture element.
- //
- mouseCapture.registerElement($element);
-
- }],
-
- };
-})
-;
-
diff --git a/icestudio/flowchart/svg_class.js b/icestudio/flowchart/svg_class.js
deleted file mode 100644
index bcec71715..000000000
--- a/icestudio/flowchart/svg_class.js
+++ /dev/null
@@ -1,50 +0,0 @@
-//
-// http://www.justinmccandless.com/blog/Patching+jQuery's+Lack+of+SVG+Support
-//
-// Functions to add and remove SVG classes because jQuery doesn't support this.
-//
-
-// jQuery's removeClass doesn't work for SVG, but this does!
-// takes the object obj to remove from, and removes class remove
-// returns true if successful, false if remove does not exist in obj
-var removeClassSVG = function(obj, remove) {
- var classes = obj.attr('class');
- if (!classes) {
- return false;
- }
-
- var index = classes.search(remove);
-
- // if the class already doesn't exist, return false now
- if (index == -1) {
- return false;
- }
- else {
- // string manipulation to remove the class
- classes = classes.substring(0, index) + classes.substring((index + remove.length), classes.length);
-
- // set the new string as the object's class
- obj.attr('class', classes);
-
- return true;
- }
-};
-
-// jQuery's hasClass doesn't work for SVG, but this does!
-// takes an object obj and checks for class has
-// returns true if the class exits in obj, false otherwise
-var hasClassSVG = function(obj, has) {
- var classes = obj.attr('class');
- if (!classes) {
- return false;
- }
-
- var index = classes.search(has);
-
- if (index == -1) {
- return false;
- }
- else {
- return true;
- }
-};
\ No newline at end of file
diff --git a/icestudio/flowchart/svg_class.spec.js b/icestudio/flowchart/svg_class.spec.js
deleted file mode 100644
index 7014c4541..000000000
--- a/icestudio/flowchart/svg_class.spec.js
+++ /dev/null
@@ -1,115 +0,0 @@
-
-describe('svg_class', function () {
-
- it('removeClassSVG returns false when there is no classes attr', function () {
-
- var mockElement = {
- attr: function () {
- return null;
- },
- };
- var testClass = 'foo';
-
- expect(removeClassSVG(mockElement, testClass)).toBe(false);
-
- });
-
- it('removeClassSVG returns false when the element doesnt already have the class', function () {
-
- var mockElement = {
- attr: function () {
- return 'smeg';
- },
- };
- var testClass = 'foo';
-
- expect(removeClassSVG(mockElement, testClass)).toBe(false);
-
- });
-
- it('removeClassSVG returns true and removes the class when the element does have the class', function () {
-
- var testClass = 'foo';
-
- var mockElement = {
- attr: function () {
- return testClass;
- },
- };
-
- spyOn(mockElement, 'attr').andCallThrough();
-
- expect(removeClassSVG(mockElement, testClass)).toBe(true);
- expect(mockElement.attr).toHaveBeenCalledWith('class', '');
-
- });
-
- it('hasClassSVG returns false when attr returns null', function () {
-
- var mockElement = {
- attr: function () {
- return null;
- },
- };
-
- var testClass = 'foo';
-
- expect(hasClassSVG(mockElement, testClass)).toBe(false);
-
- });
-
- it('hasClassSVG returns false when element has no class', function () {
-
- var mockElement = {
- attr: function () {
- return '';
- },
- };
-
- var testClass = 'foo';
-
- expect(hasClassSVG(mockElement, testClass)).toBe(false);
-
- });
-
- it('hasClassSVG returns false when element has wrong class', function () {
-
- var mockElement = {
- attr: function () {
- return 'smeg';
- },
- };
-
- var testClass = 'foo';
-
- expect(hasClassSVG(mockElement, testClass)).toBe(false);
-
- });
-
- it('hasClassSVG returns true when element has correct class', function () {
-
- var testClass = 'foo';
-
- var mockElement = {
- attr: function () {
- return testClass;
- },
- };
-
- expect(hasClassSVG(mockElement, testClass)).toBe(true);
-
- });
-
- it('hasClassSVG returns true when element 1 correct class of many ', function () {
-
- var testClass = 'foo';
-
- var mockElement = {
- attr: function () {
- return "whar " + testClass + " smeg";
- },
- };
-
- expect(hasClassSVG(mockElement, testClass)).toBe(true);
- });
-});
\ No newline at end of file
diff --git a/icestudio/gen/main.json b/icestudio/gen/main.json
deleted file mode 100644
index 86edbed9e..000000000
--- a/icestudio/gen/main.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "nodes": [],
- "connections": []
-}
\ No newline at end of file
diff --git a/icestudio/gen/main.pcf b/icestudio/gen/main.pcf
deleted file mode 100644
index e69de29bb..000000000
diff --git a/icestudio/gen/main.v b/icestudio/gen/main.v
deleted file mode 100644
index b5401b52e..000000000
--- a/icestudio/gen/main.v
+++ /dev/null
@@ -1,4 +0,0 @@
-// Generated verilog
-
-module main();
-endmodule
diff --git a/icestudio/icestudio.html b/icestudio/icestudio.html
deleted file mode 100644
index a35ac712b..000000000
--- a/icestudio/icestudio.html
+++ /dev/null
@@ -1,162 +0,0 @@
-
-
- Icestudio
-
-
-
-
-
-
-
-
-
-
-
- Warning: experimental code. Use with caution!
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/icestudio/img/bq-logo.png b/icestudio/img/bq-logo.png
deleted file mode 100644
index e26b37d66..000000000
Binary files a/icestudio/img/bq-logo.png and /dev/null differ
diff --git a/icestudio/img/spinner.gif b/icestudio/img/spinner.gif
deleted file mode 100644
index 99d7e8891..000000000
Binary files a/icestudio/img/spinner.gif and /dev/null differ
diff --git a/icestudio/install/install.py b/icestudio/install/install.py
deleted file mode 100644
index a944f7c21..000000000
--- a/icestudio/install/install.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-# Install icestorm toolchain in Icestudio path using apio
-# March 2016
-# GPLv2
-
-import sys
-import shutil
-import subprocess
-
-from platform import system
-from os.path import isdir, join, expanduser, normpath, dirname, abspath
-
-__author__ = 'Jesús Arroyo Torrens '
-__license__ = 'GNU General Public License v2 http://www.gnu.org/licenses/gpl2.html'
-
-
-VIRTUALENV = join(dirname(abspath(__file__)), 'virtualenv-14.0.1')
-ICESTUDIO_PATH = join(expanduser('~'), '.icestudio')
-if system() == 'Windows':
- ICESTUDIO_BIN = join(ICESTUDIO_PATH, 'Scripts')
-else:
- ICESTUDIO_BIN = join(ICESTUDIO_PATH, 'bin')
-ICESTUDIO_PIP = join(ICESTUDIO_BIN, 'pip')
-ICESTUDIO_APIO = join(ICESTUDIO_BIN, 'apio')
-PYTHON_EXE = normpath(sys.executable)
-
-
-def run(commands):
- result = {
- 'out': None,
- 'err': None,
- 'returncode': None}
-
- p = subprocess.Popen(
- commands,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- shell=system() == 'Windows')
-
- try:
- result['out'], result['err'] = p.communicate()
- result['returncode'] = p.returncode
- except KeyboardInterrupt:
- print('Aborted by user')
- sys.exit(1)
-
- if result['returncode'] != 0:
- print >> sys.stderr, ' '.join(commands)
- sys.exit(1)
-
- return result
-
-run([PYTHON_EXE, '--version'])
-
-# $ curl -O https://pypi.python.org/packages/source/v/virtualenv/virtualenv-X.X.tar.gz
-# $ tar xvfz virtualenv-X.X.tar.gz
-
-if isdir(ICESTUDIO_PATH):
- shutil.rmtree(ICESTUDIO_PATH)
-
-run([PYTHON_EXE, join(VIRTUALENV, 'virtualenv.py'), ICESTUDIO_PATH])
-
-run([ICESTUDIO_PIP, 'install', '-U', 'apio'])
-
-run([ICESTUDIO_APIO, '--version'])
-
-run([ICESTUDIO_APIO, 'install'])
diff --git a/icestudio/install/virtualenv-14.0.1/AUTHORS.txt b/icestudio/install/virtualenv-14.0.1/AUTHORS.txt
deleted file mode 100644
index 272494163..000000000
--- a/icestudio/install/virtualenv-14.0.1/AUTHORS.txt
+++ /dev/null
@@ -1,91 +0,0 @@
-Author
-------
-
-Ian Bicking
-
-Maintainers
------------
-
-Brian Rosner
-Carl Meyer
-Jannis Leidel
-Paul Moore
-Paul Nasrat
-Marcus Smith
-
-Contributors
-------------
-
-Alex Grönholm
-Anatoly Techtonik
-Antonio Cuni
-Antonio Valentino
-Armin Ronacher
-Barry Warsaw
-Benjamin Root
-Bradley Ayers
-Branden Rolston
-Brandon Carl
-Brian Kearns
-Cap Petschulat
-CBWhiz
-Chris Adams
-Chris McDonough
-Christos Kontas
-Christian Hudon
-Christian Stefanescu
-Christopher Nilsson
-Cliff Xuan
-Curt Micol
-Damien Nozay
-Dan Sully
-Daniel Hahler
-Daniel Holth
-David Schoonover
-Denis Costa
-Doug Hellmann
-Doug Napoleone
-Douglas Creager
-Eduard-Cristian Stefan
-Erik M. Bray
-Ethan Jucovy
-Gabriel de Perthuis
-Gunnlaugur Thor Briem
-Graham Dennis
-Greg Haskins
-Jason Penney
-Jason R. Coombs
-Jeff Hammel
-Jeremy Orem
-Jason Penney
-Jason R. Coombs
-John Kleint
-Jonathan Griffin
-Jonathan Hitchcock
-Jorge Vargas
-Josh Bronson
-Kamil Kisiel
-Kyle Gibson
-Konstantin Zemlyak
-Kumar McMillan
-Lars Francke
-Marc Abramowitz
-Mika Laitio
-Mike Hommey
-Miki Tebeka
-Philip Jenvey
-Philippe Ombredanne
-Piotr Dobrogost
-Preston Holmes
-Ralf Schmitt
-Raul Leal
-Ronny Pfannschmidt
-Satrajit Ghosh
-Sergio de Carvalho
-Stefano Rivera
-Tarek Ziadé
-Thomas Aglassinger
-Vinay Sajip
-Vitaly Babiy
-Vladimir Rutsky
-Wang Xuerui
\ No newline at end of file
diff --git a/icestudio/install/virtualenv-14.0.1/LICENSE.txt b/icestudio/install/virtualenv-14.0.1/LICENSE.txt
deleted file mode 100644
index a84d8dd1b..000000000
--- a/icestudio/install/virtualenv-14.0.1/LICENSE.txt
+++ /dev/null
@@ -1,22 +0,0 @@
-Copyright (c) 2007 Ian Bicking and Contributors
-Copyright (c) 2009 Ian Bicking, The Open Planning Project
-Copyright (c) 2011-2015 The virtualenv developers
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/icestudio/install/virtualenv-14.0.1/MANIFEST.in b/icestudio/install/virtualenv-14.0.1/MANIFEST.in
deleted file mode 100644
index 49037ada6..000000000
--- a/icestudio/install/virtualenv-14.0.1/MANIFEST.in
+++ /dev/null
@@ -1,12 +0,0 @@
-recursive-include docs *
-recursive-include tests *.py *.sh *.expected
-recursive-include virtualenv_support *.whl
-recursive-include virtualenv_embedded *
-recursive-exclude docs/_templates *
-recursive-exclude docs/_build *
-include virtualenv_support/__init__.py
-include bin/*
-include scripts/*
-include *.py
-include AUTHORS.txt
-include LICENSE.txt
diff --git a/icestudio/install/virtualenv-14.0.1/PKG-INFO b/icestudio/install/virtualenv-14.0.1/PKG-INFO
deleted file mode 100644
index 7b6a32cb9..000000000
--- a/icestudio/install/virtualenv-14.0.1/PKG-INFO
+++ /dev/null
@@ -1,113 +0,0 @@
-Metadata-Version: 1.1
-Name: virtualenv
-Version: 14.0.1
-Summary: Virtual Python Environment builder
-Home-page: https://virtualenv.pypa.io/
-Author: Jannis Leidel, Carl Meyer and Brian Rosner
-Author-email: python-virtualenv@groups.google.com
-License: MIT
-Description: Virtualenv
- ==========
-
- `Mailing list `_ |
- `Issues `_ |
- `Github `_ |
- `PyPI `_ |
- User IRC: #pypa
- Dev IRC: #pypa-dev
-
- Introduction
- ------------
-
- ``virtualenv`` is a tool to create isolated Python environments.
-
- The basic problem being addressed is one of dependencies and versions,
- and indirectly permissions. Imagine you have an application that
- needs version 1 of LibFoo, but another application requires version
- 2. How can you use both these applications? If you install
- everything into ``/usr/lib/python2.7/site-packages`` (or whatever your
- platform's standard location is), it's easy to end up in a situation
- where you unintentionally upgrade an application that shouldn't be
- upgraded.
-
- Or more generally, what if you want to install an application *and
- leave it be*? If an application works, any change in its libraries or
- the versions of those libraries can break the application.
-
- Also, what if you can't install packages into the global
- ``site-packages`` directory? For instance, on a shared host.
-
- In all these cases, ``virtualenv`` can help you. It creates an
- environment that has its own installation directories, that doesn't
- share libraries with other virtualenv environments (and optionally
- doesn't access the globally installed libraries either).
-
- .. comment:
-
- Release History
- ===============
-
- 14.0.1 (2016-01-21)
- -------------------
-
- * Upgrade from pip 8.0.0 to 8.0.2.
-
- * Fix the default of ``--(no-)download`` to default to downloading.
-
-
- 14.0.0 (2016-01-19)
- -------------------
-
- * **BACKWARDS INCOMPATIBLE** Drop support for Python 3.2.
-
- * Upgrade setuptools to 19.4
-
- * Upgrade wheel to 0.26.0
-
- * Upgrade pip to 8.0.0
-
- * Upgrade argparse to 1.4.0
-
- * Added support for ``python-config`` script (PR #798)
-
- * Updated activate.fish (PR #589) (PR #799)
-
- * Account for a ``site.pyo`` correctly in some python implementations (PR #759)
-
- * Properly restore an empty PS1 (#407)
-
- * Properly remove ``pydoc`` when deactivating
-
- * Remove workaround for very old Mageia / Mandriva linuxes (PR #472)
-
- * Added a space after virtualenv name in the prompt: ``(env) $PS1``
-
- * Make sure not to run a --user install when creating the virtualenv (PR #803)
-
- * Remove virtualenv file's path from directory when executing with a new
- python. Fixes issue #779, #763 (PR #805)
-
- * Remove use of () in .bat files so ``Program Files (x86)`` works #35
-
- * Download new releases of the preinstalled software from PyPI when there are
- new releases available. This behavior can be disabled using
- ``--no-download``.
-
- * Make ``--no-setuptools``, ``--no-pip``, and ``--no-wheel`` independent of
- each other.
-
-
- `Full Changelog `_.
-Keywords: setuptools deployment installation distutils
-Platform: UNKNOWN
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: MIT License
-Classifier: Programming Language :: Python :: 2
-Classifier: Programming Language :: Python :: 2.6
-Classifier: Programming Language :: Python :: 2.7
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3.1
-Classifier: Programming Language :: Python :: 3.2
-Classifier: Programming Language :: Python :: 3.3
-Classifier: Programming Language :: Python :: 3.4
diff --git a/icestudio/install/virtualenv-14.0.1/README.rst b/icestudio/install/virtualenv-14.0.1/README.rst
deleted file mode 100644
index c78222842..000000000
--- a/icestudio/install/virtualenv-14.0.1/README.rst
+++ /dev/null
@@ -1,20 +0,0 @@
-virtualenv
-==========
-
-.. image:: https://img.shields.io/pypi/v/virtualenv.svg
- :target: https://pypi.python.org/pypi/virtualenv
-
-.. image:: https://img.shields.io/travis/pypa/virtualenv/develop.svg
- :target: http://travis-ci.org/pypa/virtualenv
-
-For documentation, see https://virtualenv.pypa.io/
-
-
-Code of Conduct
----------------
-
-Everyone interacting in the virtualenv project's codebases, issue trackers,
-chat rooms, and mailing lists is expected to follow the
-`PyPA Code of Conduct`_.
-
-.. _PyPA Code of Conduct: https://www.pypa.io/en/latest/code-of-conduct/
diff --git a/icestudio/install/virtualenv-14.0.1/bin/rebuild-script.py b/icestudio/install/virtualenv-14.0.1/bin/rebuild-script.py
deleted file mode 100755
index a816af3eb..000000000
--- a/icestudio/install/virtualenv-14.0.1/bin/rebuild-script.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/env python
-"""
-Helper script to rebuild virtualenv.py from virtualenv_support
-"""
-from __future__ import print_function
-
-import os
-import re
-import codecs
-from zlib import crc32
-
-here = os.path.dirname(__file__)
-script = os.path.join(here, '..', 'virtualenv.py')
-
-gzip = codecs.lookup('zlib')
-b64 = codecs.lookup('base64')
-
-file_regex = re.compile(
- br'##file (.*?)\n([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*convert\("""\n(.*?)"""\)',
- re.S)
-file_template = b'##file %(filename)s\n%(varname)s = convert("""\n%(data)s""")'
-
-def rebuild(script_path):
- with open(script_path, 'rb') as f:
- script_content = f.read()
- parts = []
- last_pos = 0
- match = None
- for match in file_regex.finditer(script_content):
- parts += [script_content[last_pos:match.start()]]
- last_pos = match.end()
- filename, fn_decoded = match.group(1), match.group(1).decode()
- varname = match.group(2)
- data = match.group(3)
-
- print('Found file %s' % fn_decoded)
- pathname = os.path.join(here, '..', 'virtualenv_embedded', fn_decoded)
-
- with open(pathname, 'rb') as f:
- embedded = f.read()
- new_crc = crc32(embedded)
- new_data = b64.encode(gzip.encode(embedded)[0])[0]
-
- if new_data == data:
- print(' File up to date (crc: %s)' % new_crc)
- parts += [match.group(0)]
- continue
- # Else: content has changed
- crc = crc32(gzip.decode(b64.decode(data)[0])[0])
- print(' Content changed (crc: %s -> %s)' %
- (crc, new_crc))
- new_match = file_template % {
- b'filename': filename,
- b'varname': varname,
- b'data': new_data
- }
- parts += [new_match]
-
- parts += [script_content[last_pos:]]
- new_content = b''.join(parts)
-
- if new_content != script_content:
- print('Content updated; overwriting... ', end='')
- with open(script_path, 'wb') as f:
- f.write(new_content)
- print('done.')
- else:
- print('No changes in content')
- if match is None:
- print('No variables were matched/found')
-
-if __name__ == '__main__':
- rebuild(script)
diff --git a/icestudio/install/virtualenv-14.0.1/scripts/virtualenv b/icestudio/install/virtualenv-14.0.1/scripts/virtualenv
deleted file mode 100644
index c961dd7db..000000000
--- a/icestudio/install/virtualenv-14.0.1/scripts/virtualenv
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/usr/bin/env python
-import virtualenv
-virtualenv.main()
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv.py b/icestudio/install/virtualenv-14.0.1/virtualenv.py
deleted file mode 100755
index c4f025a1d..000000000
--- a/icestudio/install/virtualenv-14.0.1/virtualenv.py
+++ /dev/null
@@ -1,2282 +0,0 @@
-#!/usr/bin/env python
-"""Create a "virtual" Python installation"""
-
-import os
-import sys
-
-# If we are running in a new interpreter to create a virtualenv,
-# we do NOT want paths from our existing location interfering with anything,
-# So we remove this file's directory from sys.path - most likely to be
-# the previous interpreter's site-packages. Solves #705, #763, #779
-if os.environ.get('VIRTUALENV_INTERPRETER_RUNNING'):
- for path in sys.path[:]:
- if os.path.realpath(os.path.dirname(__file__)) == os.path.realpath(path):
- sys.path.remove(path)
-
-import base64
-import codecs
-import optparse
-import re
-import shutil
-import logging
-import zlib
-import errno
-import glob
-import distutils.sysconfig
-import struct
-import subprocess
-from distutils.util import strtobool
-from os.path import join
-
-try:
- import ConfigParser
-except ImportError:
- import configparser as ConfigParser
-
-__version__ = "14.0.1"
-virtualenv_version = __version__ # legacy
-
-if sys.version_info < (2, 6):
- print('ERROR: %s' % sys.exc_info()[1])
- print('ERROR: this script requires Python 2.6 or greater.')
- sys.exit(101)
-
-try:
- basestring
-except NameError:
- basestring = str
-
-py_version = 'python%s.%s' % (sys.version_info[0], sys.version_info[1])
-
-is_jython = sys.platform.startswith('java')
-is_pypy = hasattr(sys, 'pypy_version_info')
-is_win = (sys.platform == 'win32')
-is_cygwin = (sys.platform == 'cygwin')
-is_darwin = (sys.platform == 'darwin')
-abiflags = getattr(sys, 'abiflags', '')
-
-user_dir = os.path.expanduser('~')
-if is_win:
- default_storage_dir = os.path.join(user_dir, 'virtualenv')
-else:
- default_storage_dir = os.path.join(user_dir, '.virtualenv')
-default_config_file = os.path.join(default_storage_dir, 'virtualenv.ini')
-
-if is_pypy:
- expected_exe = 'pypy'
-elif is_jython:
- expected_exe = 'jython'
-else:
- expected_exe = 'python'
-
-# Return a mapping of version -> Python executable
-# Only provided for Windows, where the information in the registry is used
-if not is_win:
- def get_installed_pythons():
- return {}
-else:
- try:
- import winreg
- except ImportError:
- import _winreg as winreg
-
- def get_installed_pythons():
- try:
- python_core = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE,
- "Software\\Python\\PythonCore")
- except WindowsError:
- # No registered Python installations
- return {}
- i = 0
- versions = []
- while True:
- try:
- versions.append(winreg.EnumKey(python_core, i))
- i = i + 1
- except WindowsError:
- break
- exes = dict()
- for ver in versions:
- try:
- path = winreg.QueryValue(python_core, "%s\\InstallPath" % ver)
- except WindowsError:
- continue
- exes[ver] = join(path, "python.exe")
-
- winreg.CloseKey(python_core)
-
- # Add the major versions
- # Sort the keys, then repeatedly update the major version entry
- # Last executable (i.e., highest version) wins with this approach
- for ver in sorted(exes):
- exes[ver[0]] = exes[ver]
-
- return exes
-
-REQUIRED_MODULES = ['os', 'posix', 'posixpath', 'nt', 'ntpath', 'genericpath',
- 'fnmatch', 'locale', 'encodings', 'codecs',
- 'stat', 'UserDict', 'readline', 'copy_reg', 'types',
- 're', 'sre', 'sre_parse', 'sre_constants', 'sre_compile',
- 'zlib']
-
-REQUIRED_FILES = ['lib-dynload', 'config']
-
-majver, minver = sys.version_info[:2]
-if majver == 2:
- if minver >= 6:
- REQUIRED_MODULES.extend(['warnings', 'linecache', '_abcoll', 'abc'])
- if minver >= 7:
- REQUIRED_MODULES.extend(['_weakrefset'])
-elif majver == 3:
- # Some extra modules are needed for Python 3, but different ones
- # for different versions.
- REQUIRED_MODULES.extend([
- '_abcoll', 'warnings', 'linecache', 'abc', 'io', '_weakrefset',
- 'copyreg', 'tempfile', 'random', '__future__', 'collections',
- 'keyword', 'tarfile', 'shutil', 'struct', 'copy', 'tokenize',
- 'token', 'functools', 'heapq', 'bisect', 'weakref', 'reprlib'
- ])
- if minver >= 2:
- REQUIRED_FILES[-1] = 'config-%s' % majver
- if minver >= 3:
- import sysconfig
- platdir = sysconfig.get_config_var('PLATDIR')
- REQUIRED_FILES.append(platdir)
- REQUIRED_MODULES.extend([
- 'base64', '_dummy_thread', 'hashlib', 'hmac',
- 'imp', 'importlib', 'rlcompleter'
- ])
- if minver >= 4:
- REQUIRED_MODULES.extend([
- 'operator',
- '_collections_abc',
- '_bootlocale',
- ])
-
-if is_pypy:
- # these are needed to correctly display the exceptions that may happen
- # during the bootstrap
- REQUIRED_MODULES.extend(['traceback', 'linecache'])
-
-
-class Logger(object):
-
- """
- Logging object for use in command-line script. Allows ranges of
- levels, to avoid some redundancy of displayed information.
- """
-
- DEBUG = logging.DEBUG
- INFO = logging.INFO
- NOTIFY = (logging.INFO+logging.WARN)/2
- WARN = WARNING = logging.WARN
- ERROR = logging.ERROR
- FATAL = logging.FATAL
-
- LEVELS = [DEBUG, INFO, NOTIFY, WARN, ERROR, FATAL]
-
- def __init__(self, consumers):
- self.consumers = consumers
- self.indent = 0
- self.in_progress = None
- self.in_progress_hanging = False
-
- def debug(self, msg, *args, **kw):
- self.log(self.DEBUG, msg, *args, **kw)
-
- def info(self, msg, *args, **kw):
- self.log(self.INFO, msg, *args, **kw)
-
- def notify(self, msg, *args, **kw):
- self.log(self.NOTIFY, msg, *args, **kw)
-
- def warn(self, msg, *args, **kw):
- self.log(self.WARN, msg, *args, **kw)
-
- def error(self, msg, *args, **kw):
- self.log(self.ERROR, msg, *args, **kw)
-
- def fatal(self, msg, *args, **kw):
- self.log(self.FATAL, msg, *args, **kw)
-
- def log(self, level, msg, *args, **kw):
- if args:
- if kw:
- raise TypeError(
- "You may give positional or keyword arguments, not both")
- args = args or kw
- rendered = None
- for consumer_level, consumer in self.consumers:
- if self.level_matches(level, consumer_level):
- if (self.in_progress_hanging
- and consumer in (sys.stdout, sys.stderr)):
- self.in_progress_hanging = False
- sys.stdout.write('\n')
- sys.stdout.flush()
- if rendered is None:
- if args:
- rendered = msg % args
- else:
- rendered = msg
- rendered = ' '*self.indent + rendered
- if hasattr(consumer, 'write'):
- consumer.write(rendered+'\n')
- else:
- consumer(rendered)
-
- def start_progress(self, msg):
- assert not self.in_progress, (
- "Tried to start_progress(%r) while in_progress %r"
- % (msg, self.in_progress))
- if self.level_matches(self.NOTIFY, self._stdout_level()):
- sys.stdout.write(msg)
- sys.stdout.flush()
- self.in_progress_hanging = True
- else:
- self.in_progress_hanging = False
- self.in_progress = msg
-
- def end_progress(self, msg='done.'):
- assert self.in_progress, (
- "Tried to end_progress without start_progress")
- if self.stdout_level_matches(self.NOTIFY):
- if not self.in_progress_hanging:
- # Some message has been printed out since start_progress
- sys.stdout.write('...' + self.in_progress + msg + '\n')
- sys.stdout.flush()
- else:
- sys.stdout.write(msg + '\n')
- sys.stdout.flush()
- self.in_progress = None
- self.in_progress_hanging = False
-
- def show_progress(self):
- """If we are in a progress scope, and no log messages have been
- shown, write out another '.'"""
- if self.in_progress_hanging:
- sys.stdout.write('.')
- sys.stdout.flush()
-
- def stdout_level_matches(self, level):
- """Returns true if a message at this level will go to stdout"""
- return self.level_matches(level, self._stdout_level())
-
- def _stdout_level(self):
- """Returns the level that stdout runs at"""
- for level, consumer in self.consumers:
- if consumer is sys.stdout:
- return level
- return self.FATAL
-
- def level_matches(self, level, consumer_level):
- """
- >>> l = Logger([])
- >>> l.level_matches(3, 4)
- False
- >>> l.level_matches(3, 2)
- True
- >>> l.level_matches(slice(None, 3), 3)
- False
- >>> l.level_matches(slice(None, 3), 2)
- True
- >>> l.level_matches(slice(1, 3), 1)
- True
- >>> l.level_matches(slice(2, 3), 1)
- False
- """
- if isinstance(level, slice):
- start, stop = level.start, level.stop
- if start is not None and start > consumer_level:
- return False
- if stop is not None and stop <= consumer_level:
- return False
- return True
- else:
- return level >= consumer_level
-
- #@classmethod
- def level_for_integer(cls, level):
- levels = cls.LEVELS
- if level < 0:
- return levels[0]
- if level >= len(levels):
- return levels[-1]
- return levels[level]
-
- level_for_integer = classmethod(level_for_integer)
-
-# create a silent logger just to prevent this from being undefined
-# will be overridden with requested verbosity main() is called.
-logger = Logger([(Logger.LEVELS[-1], sys.stdout)])
-
-def mkdir(path):
- if not os.path.exists(path):
- logger.info('Creating %s', path)
- os.makedirs(path)
- else:
- logger.info('Directory %s already exists', path)
-
-def copyfileordir(src, dest, symlink=True):
- if os.path.isdir(src):
- shutil.copytree(src, dest, symlink)
- else:
- shutil.copy2(src, dest)
-
-def copyfile(src, dest, symlink=True):
- if not os.path.exists(src):
- # Some bad symlink in the src
- logger.warn('Cannot find file %s (bad symlink)', src)
- return
- if os.path.exists(dest):
- logger.debug('File %s already exists', dest)
- return
- if not os.path.exists(os.path.dirname(dest)):
- logger.info('Creating parent directories for %s', os.path.dirname(dest))
- os.makedirs(os.path.dirname(dest))
- if not os.path.islink(src):
- srcpath = os.path.abspath(src)
- else:
- srcpath = os.readlink(src)
- if symlink and hasattr(os, 'symlink') and not is_win:
- logger.info('Symlinking %s', dest)
- try:
- os.symlink(srcpath, dest)
- except (OSError, NotImplementedError):
- logger.info('Symlinking failed, copying to %s', dest)
- copyfileordir(src, dest, symlink)
- else:
- logger.info('Copying to %s', dest)
- copyfileordir(src, dest, symlink)
-
-def writefile(dest, content, overwrite=True):
- if not os.path.exists(dest):
- logger.info('Writing %s', dest)
- f = open(dest, 'wb')
- f.write(content.encode('utf-8'))
- f.close()
- return
- else:
- f = open(dest, 'rb')
- c = f.read()
- f.close()
- if c != content.encode("utf-8"):
- if not overwrite:
- logger.notify('File %s exists with different content; not overwriting', dest)
- return
- logger.notify('Overwriting %s with new content', dest)
- f = open(dest, 'wb')
- f.write(content.encode('utf-8'))
- f.close()
- else:
- logger.info('Content %s already in place', dest)
-
-def rmtree(dir):
- if os.path.exists(dir):
- logger.notify('Deleting tree %s', dir)
- shutil.rmtree(dir)
- else:
- logger.info('Do not need to delete %s; already gone', dir)
-
-def make_exe(fn):
- if hasattr(os, 'chmod'):
- oldmode = os.stat(fn).st_mode & 0xFFF # 0o7777
- newmode = (oldmode | 0x16D) & 0xFFF # 0o555, 0o7777
- os.chmod(fn, newmode)
- logger.info('Changed mode of %s to %s', fn, oct(newmode))
-
-def _find_file(filename, dirs):
- for dir in reversed(dirs):
- files = glob.glob(os.path.join(dir, filename))
- if files and os.path.isfile(files[0]):
- return True, files[0]
- return False, filename
-
-def file_search_dirs():
- here = os.path.dirname(os.path.abspath(__file__))
- dirs = [here, join(here, 'virtualenv_support')]
- if os.path.splitext(os.path.dirname(__file__))[0] != 'virtualenv':
- # Probably some boot script; just in case virtualenv is installed...
- try:
- import virtualenv
- except ImportError:
- pass
- else:
- dirs.append(os.path.join(
- os.path.dirname(virtualenv.__file__), 'virtualenv_support'))
- return [d for d in dirs if os.path.isdir(d)]
-
-
-class UpdatingDefaultsHelpFormatter(optparse.IndentedHelpFormatter):
- """
- Custom help formatter for use in ConfigOptionParser that updates
- the defaults before expanding them, allowing them to show up correctly
- in the help listing
- """
- def expand_default(self, option):
- if self.parser is not None:
- self.parser.update_defaults(self.parser.defaults)
- return optparse.IndentedHelpFormatter.expand_default(self, option)
-
-
-class ConfigOptionParser(optparse.OptionParser):
- """
- Custom option parser which updates its defaults by checking the
- configuration files and environmental variables
- """
- def __init__(self, *args, **kwargs):
- self.config = ConfigParser.RawConfigParser()
- self.files = self.get_config_files()
- self.config.read(self.files)
- optparse.OptionParser.__init__(self, *args, **kwargs)
-
- def get_config_files(self):
- config_file = os.environ.get('VIRTUALENV_CONFIG_FILE', False)
- if config_file and os.path.exists(config_file):
- return [config_file]
- return [default_config_file]
-
- def update_defaults(self, defaults):
- """
- Updates the given defaults with values from the config files and
- the environ. Does a little special handling for certain types of
- options (lists).
- """
- # Then go and look for the other sources of configuration:
- config = {}
- # 1. config files
- config.update(dict(self.get_config_section('virtualenv')))
- # 2. environmental variables
- config.update(dict(self.get_environ_vars()))
- # Then set the options with those values
- for key, val in config.items():
- key = key.replace('_', '-')
- if not key.startswith('--'):
- key = '--%s' % key # only prefer long opts
- option = self.get_option(key)
- if option is not None:
- # ignore empty values
- if not val:
- continue
- # handle multiline configs
- if option.action == 'append':
- val = val.split()
- else:
- option.nargs = 1
- if option.action == 'store_false':
- val = not strtobool(val)
- elif option.action in ('store_true', 'count'):
- val = strtobool(val)
- try:
- val = option.convert_value(key, val)
- except optparse.OptionValueError:
- e = sys.exc_info()[1]
- print("An error occurred during configuration: %s" % e)
- sys.exit(3)
- defaults[option.dest] = val
- return defaults
-
- def get_config_section(self, name):
- """
- Get a section of a configuration
- """
- if self.config.has_section(name):
- return self.config.items(name)
- return []
-
- def get_environ_vars(self, prefix='VIRTUALENV_'):
- """
- Returns a generator with all environmental vars with prefix VIRTUALENV
- """
- for key, val in os.environ.items():
- if key.startswith(prefix):
- yield (key.replace(prefix, '').lower(), val)
-
- def get_default_values(self):
- """
- Overridding to make updating the defaults after instantiation of
- the option parser possible, update_defaults() does the dirty work.
- """
- if not self.process_default_values:
- # Old, pre-Optik 1.5 behaviour.
- return optparse.Values(self.defaults)
-
- defaults = self.update_defaults(self.defaults.copy()) # ours
- for option in self._get_all_options():
- default = defaults.get(option.dest)
- if isinstance(default, basestring):
- opt_str = option.get_opt_string()
- defaults[option.dest] = option.check_value(opt_str, default)
- return optparse.Values(defaults)
-
-
-def main():
- parser = ConfigOptionParser(
- version=virtualenv_version,
- usage="%prog [OPTIONS] DEST_DIR",
- formatter=UpdatingDefaultsHelpFormatter())
-
- parser.add_option(
- '-v', '--verbose',
- action='count',
- dest='verbose',
- default=0,
- help="Increase verbosity.")
-
- parser.add_option(
- '-q', '--quiet',
- action='count',
- dest='quiet',
- default=0,
- help='Decrease verbosity.')
-
- parser.add_option(
- '-p', '--python',
- dest='python',
- metavar='PYTHON_EXE',
- help='The Python interpreter to use, e.g., --python=python2.5 will use the python2.5 '
- 'interpreter to create the new environment. The default is the interpreter that '
- 'virtualenv was installed with (%s)' % sys.executable)
-
- parser.add_option(
- '--clear',
- dest='clear',
- action='store_true',
- help="Clear out the non-root install and start from scratch.")
-
- parser.set_defaults(system_site_packages=False)
- parser.add_option(
- '--no-site-packages',
- dest='system_site_packages',
- action='store_false',
- help="DEPRECATED. Retained only for backward compatibility. "
- "Not having access to global site-packages is now the default behavior.")
-
- parser.add_option(
- '--system-site-packages',
- dest='system_site_packages',
- action='store_true',
- help="Give the virtual environment access to the global site-packages.")
-
- parser.add_option(
- '--always-copy',
- dest='symlink',
- action='store_false',
- default=True,
- help="Always copy files rather than symlinking.")
-
- parser.add_option(
- '--unzip-setuptools',
- dest='unzip_setuptools',
- action='store_true',
- help="Unzip Setuptools when installing it.")
-
- parser.add_option(
- '--relocatable',
- dest='relocatable',
- action='store_true',
- help='Make an EXISTING virtualenv environment relocatable. '
- 'This fixes up scripts and makes all .pth files relative.')
-
- parser.add_option(
- '--no-setuptools',
- dest='no_setuptools',
- action='store_true',
- help='Do not install setuptools in the new virtualenv.')
-
- parser.add_option(
- '--no-pip',
- dest='no_pip',
- action='store_true',
- help='Do not install pip in the new virtualenv.')
-
- parser.add_option(
- '--no-wheel',
- dest='no_wheel',
- action='store_true',
- help='Do not install wheel in the new virtualenv.')
-
- default_search_dirs = file_search_dirs()
- parser.add_option(
- '--extra-search-dir',
- dest="search_dirs",
- action="append",
- metavar='DIR',
- default=default_search_dirs,
- help="Directory to look for setuptools/pip distributions in. "
- "This option can be used multiple times.")
-
- parser.add_option(
- "--download",
- dest="download",
- default=True,
- action="store_true",
- help="Download preinstalled packages from PyPI.",
- )
-
- parser.add_option(
- "--no-download",
- '--never-download',
- dest="download",
- action="store_false",
- help="Do not download preinstalled packages from PyPI.",
- )
-
- parser.add_option(
- '--prompt',
- dest='prompt',
- help='Provides an alternative prompt prefix for this environment.')
-
- parser.add_option(
- '--setuptools',
- dest='setuptools',
- action='store_true',
- help="DEPRECATED. Retained only for backward compatibility. This option has no effect.")
-
- parser.add_option(
- '--distribute',
- dest='distribute',
- action='store_true',
- help="DEPRECATED. Retained only for backward compatibility. This option has no effect.")
-
- if 'extend_parser' in globals():
- extend_parser(parser)
-
- options, args = parser.parse_args()
-
- global logger
-
- if 'adjust_options' in globals():
- adjust_options(options, args)
-
- verbosity = options.verbose - options.quiet
- logger = Logger([(Logger.level_for_integer(2 - verbosity), sys.stdout)])
-
- if options.python and not os.environ.get('VIRTUALENV_INTERPRETER_RUNNING'):
- env = os.environ.copy()
- interpreter = resolve_interpreter(options.python)
- if interpreter == sys.executable:
- logger.warn('Already using interpreter %s' % interpreter)
- else:
- logger.notify('Running virtualenv with interpreter %s' % interpreter)
- env['VIRTUALENV_INTERPRETER_RUNNING'] = 'true'
- file = __file__
- if file.endswith('.pyc'):
- file = file[:-1]
- popen = subprocess.Popen([interpreter, file] + sys.argv[1:], env=env)
- raise SystemExit(popen.wait())
-
- if not args:
- print('You must provide a DEST_DIR')
- parser.print_help()
- sys.exit(2)
- if len(args) > 1:
- print('There must be only one argument: DEST_DIR (you gave %s)' % (
- ' '.join(args)))
- parser.print_help()
- sys.exit(2)
-
- home_dir = args[0]
-
- if os.environ.get('WORKING_ENV'):
- logger.fatal('ERROR: you cannot run virtualenv while in a workingenv')
- logger.fatal('Please deactivate your workingenv, then re-run this script')
- sys.exit(3)
-
- if 'PYTHONHOME' in os.environ:
- logger.warn('PYTHONHOME is set. You *must* activate the virtualenv before using it')
- del os.environ['PYTHONHOME']
-
- if options.relocatable:
- make_environment_relocatable(home_dir)
- return
-
- create_environment(home_dir,
- site_packages=options.system_site_packages,
- clear=options.clear,
- unzip_setuptools=options.unzip_setuptools,
- prompt=options.prompt,
- search_dirs=options.search_dirs,
- download=options.download,
- no_setuptools=options.no_setuptools,
- no_pip=options.no_pip,
- no_wheel=options.no_wheel,
- symlink=options.symlink)
- if 'after_install' in globals():
- after_install(options, home_dir)
-
-def call_subprocess(cmd, show_stdout=True,
- filter_stdout=None, cwd=None,
- raise_on_returncode=True, extra_env=None,
- remove_from_env=None):
- cmd_parts = []
- for part in cmd:
- if len(part) > 45:
- part = part[:20]+"..."+part[-20:]
- if ' ' in part or '\n' in part or '"' in part or "'" in part:
- part = '"%s"' % part.replace('"', '\\"')
- if hasattr(part, 'decode'):
- try:
- part = part.decode(sys.getdefaultencoding())
- except UnicodeDecodeError:
- part = part.decode(sys.getfilesystemencoding())
- cmd_parts.append(part)
- cmd_desc = ' '.join(cmd_parts)
- if show_stdout:
- stdout = None
- else:
- stdout = subprocess.PIPE
- logger.debug("Running command %s" % cmd_desc)
- if extra_env or remove_from_env:
- env = os.environ.copy()
- if extra_env:
- env.update(extra_env)
- if remove_from_env:
- for varname in remove_from_env:
- env.pop(varname, None)
- else:
- env = None
- try:
- proc = subprocess.Popen(
- cmd, stderr=subprocess.STDOUT, stdin=None, stdout=stdout,
- cwd=cwd, env=env)
- except Exception:
- e = sys.exc_info()[1]
- logger.fatal(
- "Error %s while executing command %s" % (e, cmd_desc))
- raise
- all_output = []
- if stdout is not None:
- stdout = proc.stdout
- encoding = sys.getdefaultencoding()
- fs_encoding = sys.getfilesystemencoding()
- while 1:
- line = stdout.readline()
- try:
- line = line.decode(encoding)
- except UnicodeDecodeError:
- line = line.decode(fs_encoding)
- if not line:
- break
- line = line.rstrip()
- all_output.append(line)
- if filter_stdout:
- level = filter_stdout(line)
- if isinstance(level, tuple):
- level, line = level
- logger.log(level, line)
- if not logger.stdout_level_matches(level):
- logger.show_progress()
- else:
- logger.info(line)
- else:
- proc.communicate()
- proc.wait()
- if proc.returncode:
- if raise_on_returncode:
- if all_output:
- logger.notify('Complete output from command %s:' % cmd_desc)
- logger.notify('\n'.join(all_output) + '\n----------------------------------------')
- raise OSError(
- "Command %s failed with error code %s"
- % (cmd_desc, proc.returncode))
- else:
- logger.warn(
- "Command %s had error code %s"
- % (cmd_desc, proc.returncode))
-
-def filter_install_output(line):
- if line.strip().startswith('running'):
- return Logger.INFO
- return Logger.DEBUG
-
-def find_wheels(projects, search_dirs):
- """Find wheels from which we can import PROJECTS.
-
- Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return
- a list of the first wheel found for each PROJECT
- """
-
- wheels = []
-
- # Look through SEARCH_DIRS for the first suitable wheel. Don't bother
- # about version checking here, as this is simply to get something we can
- # then use to install the correct version.
- for project in projects:
- for dirname in search_dirs:
- # This relies on only having "universal" wheels available.
- # The pattern could be tightened to require -py2.py3-none-any.whl.
- files = glob.glob(os.path.join(dirname, project + '-*.whl'))
- if files:
- wheels.append(os.path.abspath(files[0]))
- break
- else:
- # We're out of luck, so quit with a suitable error
- logger.fatal('Cannot find a wheel for %s' % (project,))
-
- return wheels
-
-def install_wheel(project_names, py_executable, search_dirs=None,
- download=False):
- if search_dirs is None:
- search_dirs = file_search_dirs()
-
- wheels = find_wheels(['setuptools', 'pip'], search_dirs)
- pythonpath = os.pathsep.join(wheels)
-
- # PIP_FIND_LINKS uses space as the path separator and thus cannot have paths
- # with spaces in them. Convert any of those to local file:// URL form.
- try:
- from urlparse import urljoin
- from urllib import pathname2url
- except ImportError:
- from urllib.parse import urljoin
- from urllib.request import pathname2url
- def space_path2url(p):
- if ' ' not in p:
- return p
- return urljoin('file:', pathname2url(os.path.abspath(p)))
- findlinks = ' '.join(space_path2url(d) for d in search_dirs)
-
- cmd = [
- py_executable, '-c',
- 'import sys, pip; sys.exit(pip.main(["install", "--ignore-installed"] + sys.argv[1:]))',
- ] + project_names
- logger.start_progress('Installing %s...' % (', '.join(project_names)))
- logger.indent += 2
-
- env = {
- "PYTHONPATH": pythonpath,
- "JYTHONPATH": pythonpath, # for Jython < 3.x
- "PIP_FIND_LINKS": findlinks,
- "PIP_USE_WHEEL": "1",
- "PIP_ONLY_BINARY": ":all:",
- "PIP_PRE": "1",
- "PIP_USER": "0",
- }
-
- if not download:
- env["PIP_NO_INDEX"] = "1"
-
- try:
- call_subprocess(cmd, show_stdout=False, extra_env=env)
- finally:
- logger.indent -= 2
- logger.end_progress()
-
-def create_environment(home_dir, site_packages=False, clear=False,
- unzip_setuptools=False,
- prompt=None, search_dirs=None, download=False,
- no_setuptools=False, no_pip=False, no_wheel=False,
- symlink=True):
- """
- Creates a new environment in ``home_dir``.
-
- If ``site_packages`` is true, then the global ``site-packages/``
- directory will be on the path.
-
- If ``clear`` is true (default False) then the environment will
- first be cleared.
- """
- home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir)
-
- py_executable = os.path.abspath(install_python(
- home_dir, lib_dir, inc_dir, bin_dir,
- site_packages=site_packages, clear=clear, symlink=symlink))
-
- install_distutils(home_dir)
-
- to_install = []
-
- if not no_setuptools:
- to_install.append('setuptools')
-
- if not no_pip:
- to_install.append('pip')
-
- if not no_wheel:
- to_install.append('wheel')
-
- if to_install:
- install_wheel(
- to_install,
- py_executable,
- search_dirs,
- download=download,
- )
-
- install_activate(home_dir, bin_dir, prompt)
-
- install_python_config(home_dir, bin_dir, prompt)
-
-def is_executable_file(fpath):
- return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
-
-def path_locations(home_dir):
- """Return the path locations for the environment (where libraries are,
- where scripts go, etc)"""
- home_dir = os.path.abspath(home_dir)
- # XXX: We'd use distutils.sysconfig.get_python_inc/lib but its
- # prefix arg is broken: http://bugs.python.org/issue3386
- if is_win:
- # Windows has lots of problems with executables with spaces in
- # the name; this function will remove them (using the ~1
- # format):
- mkdir(home_dir)
- if ' ' in home_dir:
- import ctypes
- GetShortPathName = ctypes.windll.kernel32.GetShortPathNameW
- size = max(len(home_dir)+1, 256)
- buf = ctypes.create_unicode_buffer(size)
- try:
- u = unicode
- except NameError:
- u = str
- ret = GetShortPathName(u(home_dir), buf, size)
- if not ret:
- print('Error: the path "%s" has a space in it' % home_dir)
- print('We could not determine the short pathname for it.')
- print('Exiting.')
- sys.exit(3)
- home_dir = str(buf.value)
- lib_dir = join(home_dir, 'Lib')
- inc_dir = join(home_dir, 'Include')
- bin_dir = join(home_dir, 'Scripts')
- if is_jython:
- lib_dir = join(home_dir, 'Lib')
- inc_dir = join(home_dir, 'Include')
- bin_dir = join(home_dir, 'bin')
- elif is_pypy:
- lib_dir = home_dir
- inc_dir = join(home_dir, 'include')
- bin_dir = join(home_dir, 'bin')
- elif not is_win:
- lib_dir = join(home_dir, 'lib', py_version)
- inc_dir = join(home_dir, 'include', py_version + abiflags)
- bin_dir = join(home_dir, 'bin')
- return home_dir, lib_dir, inc_dir, bin_dir
-
-
-def change_prefix(filename, dst_prefix):
- prefixes = [sys.prefix]
-
- if is_darwin:
- prefixes.extend((
- os.path.join("/Library/Python", sys.version[:3], "site-packages"),
- os.path.join(sys.prefix, "Extras", "lib", "python"),
- os.path.join("~", "Library", "Python", sys.version[:3], "site-packages"),
- # Python 2.6 no-frameworks
- os.path.join("~", ".local", "lib","python", sys.version[:3], "site-packages"),
- # System Python 2.7 on OSX Mountain Lion
- os.path.join("~", "Library", "Python", sys.version[:3], "lib", "python", "site-packages")))
-
- if hasattr(sys, 'real_prefix'):
- prefixes.append(sys.real_prefix)
- if hasattr(sys, 'base_prefix'):
- prefixes.append(sys.base_prefix)
- prefixes = list(map(os.path.expanduser, prefixes))
- prefixes = list(map(os.path.abspath, prefixes))
- # Check longer prefixes first so we don't split in the middle of a filename
- prefixes = sorted(prefixes, key=len, reverse=True)
- filename = os.path.abspath(filename)
- for src_prefix in prefixes:
- if filename.startswith(src_prefix):
- _, relpath = filename.split(src_prefix, 1)
- if src_prefix != os.sep: # sys.prefix == "/"
- assert relpath[0] == os.sep
- relpath = relpath[1:]
- return join(dst_prefix, relpath)
- assert False, "Filename %s does not start with any of these prefixes: %s" % \
- (filename, prefixes)
-
-def copy_required_modules(dst_prefix, symlink):
- import imp
-
- for modname in REQUIRED_MODULES:
- if modname in sys.builtin_module_names:
- logger.info("Ignoring built-in bootstrap module: %s" % modname)
- continue
- try:
- f, filename, _ = imp.find_module(modname)
- except ImportError:
- logger.info("Cannot import bootstrap module: %s" % modname)
- else:
- if f is not None:
- f.close()
- # special-case custom readline.so on OS X, but not for pypy:
- if modname == 'readline' and sys.platform == 'darwin' and not (
- is_pypy or filename.endswith(join('lib-dynload', 'readline.so'))):
- dst_filename = join(dst_prefix, 'lib', 'python%s' % sys.version[:3], 'readline.so')
- elif modname == 'readline' and sys.platform == 'win32':
- # special-case for Windows, where readline is not a
- # standard module, though it may have been installed in
- # site-packages by a third-party package
- pass
- else:
- dst_filename = change_prefix(filename, dst_prefix)
- copyfile(filename, dst_filename, symlink)
- if filename.endswith('.pyc'):
- pyfile = filename[:-1]
- if os.path.exists(pyfile):
- copyfile(pyfile, dst_filename[:-1], symlink)
-
-
-def subst_path(prefix_path, prefix, home_dir):
- prefix_path = os.path.normpath(prefix_path)
- prefix = os.path.normpath(prefix)
- home_dir = os.path.normpath(home_dir)
- if not prefix_path.startswith(prefix):
- logger.warn('Path not in prefix %r %r', prefix_path, prefix)
- return
- return prefix_path.replace(prefix, home_dir, 1)
-
-
-def install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages, clear, symlink=True):
- """Install just the base environment, no distutils patches etc"""
- if sys.executable.startswith(bin_dir):
- print('Please use the *system* python to run this script')
- return
-
- if clear:
- rmtree(lib_dir)
- ## FIXME: why not delete it?
- ## Maybe it should delete everything with #!/path/to/venv/python in it
- logger.notify('Not deleting %s', bin_dir)
-
- if hasattr(sys, 'real_prefix'):
- logger.notify('Using real prefix %r' % sys.real_prefix)
- prefix = sys.real_prefix
- elif hasattr(sys, 'base_prefix'):
- logger.notify('Using base prefix %r' % sys.base_prefix)
- prefix = sys.base_prefix
- else:
- prefix = sys.prefix
- mkdir(lib_dir)
- fix_lib64(lib_dir, symlink)
- stdlib_dirs = [os.path.dirname(os.__file__)]
- if is_win:
- stdlib_dirs.append(join(os.path.dirname(stdlib_dirs[0]), 'DLLs'))
- elif is_darwin:
- stdlib_dirs.append(join(stdlib_dirs[0], 'site-packages'))
- if hasattr(os, 'symlink'):
- logger.info('Symlinking Python bootstrap modules')
- else:
- logger.info('Copying Python bootstrap modules')
- logger.indent += 2
- try:
- # copy required files...
- for stdlib_dir in stdlib_dirs:
- if not os.path.isdir(stdlib_dir):
- continue
- for fn in os.listdir(stdlib_dir):
- bn = os.path.splitext(fn)[0]
- if fn != 'site-packages' and bn in REQUIRED_FILES:
- copyfile(join(stdlib_dir, fn), join(lib_dir, fn), symlink)
- # ...and modules
- copy_required_modules(home_dir, symlink)
- finally:
- logger.indent -= 2
- mkdir(join(lib_dir, 'site-packages'))
- import site
- site_filename = site.__file__
- if site_filename.endswith('.pyc') or site_filename.endswith('.pyo'):
- site_filename = site_filename[:-1]
- elif site_filename.endswith('$py.class'):
- site_filename = site_filename.replace('$py.class', '.py')
- site_filename_dst = change_prefix(site_filename, home_dir)
- site_dir = os.path.dirname(site_filename_dst)
- writefile(site_filename_dst, SITE_PY)
- writefile(join(site_dir, 'orig-prefix.txt'), prefix)
- site_packages_filename = join(site_dir, 'no-global-site-packages.txt')
- if not site_packages:
- writefile(site_packages_filename, '')
-
- if is_pypy or is_win:
- stdinc_dir = join(prefix, 'include')
- else:
- stdinc_dir = join(prefix, 'include', py_version + abiflags)
- if os.path.exists(stdinc_dir):
- copyfile(stdinc_dir, inc_dir, symlink)
- else:
- logger.debug('No include dir %s' % stdinc_dir)
-
- platinc_dir = distutils.sysconfig.get_python_inc(plat_specific=1)
- if platinc_dir != stdinc_dir:
- platinc_dest = distutils.sysconfig.get_python_inc(
- plat_specific=1, prefix=home_dir)
- if platinc_dir == platinc_dest:
- # Do platinc_dest manually due to a CPython bug;
- # not http://bugs.python.org/issue3386 but a close cousin
- platinc_dest = subst_path(platinc_dir, prefix, home_dir)
- if platinc_dest:
- # PyPy's stdinc_dir and prefix are relative to the original binary
- # (traversing virtualenvs), whereas the platinc_dir is relative to
- # the inner virtualenv and ignores the prefix argument.
- # This seems more evolved than designed.
- copyfile(platinc_dir, platinc_dest, symlink)
-
- # pypy never uses exec_prefix, just ignore it
- if sys.exec_prefix != prefix and not is_pypy:
- if is_win:
- exec_dir = join(sys.exec_prefix, 'lib')
- elif is_jython:
- exec_dir = join(sys.exec_prefix, 'Lib')
- else:
- exec_dir = join(sys.exec_prefix, 'lib', py_version)
- for fn in os.listdir(exec_dir):
- copyfile(join(exec_dir, fn), join(lib_dir, fn), symlink)
-
- if is_jython:
- # Jython has either jython-dev.jar and javalib/ dir, or just
- # jython.jar
- for name in 'jython-dev.jar', 'javalib', 'jython.jar':
- src = join(prefix, name)
- if os.path.exists(src):
- copyfile(src, join(home_dir, name), symlink)
- # XXX: registry should always exist after Jython 2.5rc1
- src = join(prefix, 'registry')
- if os.path.exists(src):
- copyfile(src, join(home_dir, 'registry'), symlink=False)
- copyfile(join(prefix, 'cachedir'), join(home_dir, 'cachedir'),
- symlink=False)
-
- mkdir(bin_dir)
- py_executable = join(bin_dir, os.path.basename(sys.executable))
- if 'Python.framework' in prefix:
- # OS X framework builds cause validation to break
- # https://github.com/pypa/virtualenv/issues/322
- if os.environ.get('__PYVENV_LAUNCHER__'):
- del os.environ["__PYVENV_LAUNCHER__"]
- if re.search(r'/Python(?:-32|-64)*$', py_executable):
- # The name of the python executable is not quite what
- # we want, rename it.
- py_executable = os.path.join(
- os.path.dirname(py_executable), 'python')
-
- logger.notify('New %s executable in %s', expected_exe, py_executable)
- pcbuild_dir = os.path.dirname(sys.executable)
- pyd_pth = os.path.join(lib_dir, 'site-packages', 'virtualenv_builddir_pyd.pth')
- if is_win and os.path.exists(os.path.join(pcbuild_dir, 'build.bat')):
- logger.notify('Detected python running from build directory %s', pcbuild_dir)
- logger.notify('Writing .pth file linking to build directory for *.pyd files')
- writefile(pyd_pth, pcbuild_dir)
- else:
- pcbuild_dir = None
- if os.path.exists(pyd_pth):
- logger.info('Deleting %s (not Windows env or not build directory python)' % pyd_pth)
- os.unlink(pyd_pth)
-
- if sys.executable != py_executable:
- ## FIXME: could I just hard link?
- executable = sys.executable
- shutil.copyfile(executable, py_executable)
- make_exe(py_executable)
- if is_win or is_cygwin:
- pythonw = os.path.join(os.path.dirname(sys.executable), 'pythonw.exe')
- if os.path.exists(pythonw):
- logger.info('Also created pythonw.exe')
- shutil.copyfile(pythonw, os.path.join(os.path.dirname(py_executable), 'pythonw.exe'))
- python_d = os.path.join(os.path.dirname(sys.executable), 'python_d.exe')
- python_d_dest = os.path.join(os.path.dirname(py_executable), 'python_d.exe')
- if os.path.exists(python_d):
- logger.info('Also created python_d.exe')
- shutil.copyfile(python_d, python_d_dest)
- elif os.path.exists(python_d_dest):
- logger.info('Removed python_d.exe as it is no longer at the source')
- os.unlink(python_d_dest)
- # we need to copy the DLL to enforce that windows will load the correct one.
- # may not exist if we are cygwin.
- py_executable_dll = 'python%s%s.dll' % (
- sys.version_info[0], sys.version_info[1])
- py_executable_dll_d = 'python%s%s_d.dll' % (
- sys.version_info[0], sys.version_info[1])
- pythondll = os.path.join(os.path.dirname(sys.executable), py_executable_dll)
- pythondll_d = os.path.join(os.path.dirname(sys.executable), py_executable_dll_d)
- pythondll_d_dest = os.path.join(os.path.dirname(py_executable), py_executable_dll_d)
- if os.path.exists(pythondll):
- logger.info('Also created %s' % py_executable_dll)
- shutil.copyfile(pythondll, os.path.join(os.path.dirname(py_executable), py_executable_dll))
- if os.path.exists(pythondll_d):
- logger.info('Also created %s' % py_executable_dll_d)
- shutil.copyfile(pythondll_d, pythondll_d_dest)
- elif os.path.exists(pythondll_d_dest):
- logger.info('Removed %s as the source does not exist' % pythondll_d_dest)
- os.unlink(pythondll_d_dest)
- if is_pypy:
- # make a symlink python --> pypy-c
- python_executable = os.path.join(os.path.dirname(py_executable), 'python')
- if sys.platform in ('win32', 'cygwin'):
- python_executable += '.exe'
- logger.info('Also created executable %s' % python_executable)
- copyfile(py_executable, python_executable, symlink)
-
- if is_win:
- for name in ['libexpat.dll', 'libpypy.dll', 'libpypy-c.dll',
- 'libeay32.dll', 'ssleay32.dll', 'sqlite3.dll',
- 'tcl85.dll', 'tk85.dll']:
- src = join(prefix, name)
- if os.path.exists(src):
- copyfile(src, join(bin_dir, name), symlink)
-
- for d in sys.path:
- if d.endswith('lib_pypy'):
- break
- else:
- logger.fatal('Could not find lib_pypy in sys.path')
- raise SystemExit(3)
- logger.info('Copying lib_pypy')
- copyfile(d, os.path.join(home_dir, 'lib_pypy'), symlink)
-
- if os.path.splitext(os.path.basename(py_executable))[0] != expected_exe:
- secondary_exe = os.path.join(os.path.dirname(py_executable),
- expected_exe)
- py_executable_ext = os.path.splitext(py_executable)[1]
- if py_executable_ext.lower() == '.exe':
- # python2.4 gives an extension of '.4' :P
- secondary_exe += py_executable_ext
- if os.path.exists(secondary_exe):
- logger.warn('Not overwriting existing %s script %s (you must use %s)'
- % (expected_exe, secondary_exe, py_executable))
- else:
- logger.notify('Also creating executable in %s' % secondary_exe)
- shutil.copyfile(sys.executable, secondary_exe)
- make_exe(secondary_exe)
-
- if '.framework' in prefix:
- if 'Python.framework' in prefix:
- logger.debug('MacOSX Python framework detected')
- # Make sure we use the embedded interpreter inside
- # the framework, even if sys.executable points to
- # the stub executable in ${sys.prefix}/bin
- # See http://groups.google.com/group/python-virtualenv/
- # browse_thread/thread/17cab2f85da75951
- original_python = os.path.join(
- prefix, 'Resources/Python.app/Contents/MacOS/Python')
- if 'EPD' in prefix:
- logger.debug('EPD framework detected')
- original_python = os.path.join(prefix, 'bin/python')
- shutil.copy(original_python, py_executable)
-
- # Copy the framework's dylib into the virtual
- # environment
- virtual_lib = os.path.join(home_dir, '.Python')
-
- if os.path.exists(virtual_lib):
- os.unlink(virtual_lib)
- copyfile(
- os.path.join(prefix, 'Python'),
- virtual_lib,
- symlink)
-
- # And then change the install_name of the copied python executable
- try:
- mach_o_change(py_executable,
- os.path.join(prefix, 'Python'),
- '@executable_path/../.Python')
- except:
- e = sys.exc_info()[1]
- logger.warn("Could not call mach_o_change: %s. "
- "Trying to call install_name_tool instead." % e)
- try:
- call_subprocess(
- ["install_name_tool", "-change",
- os.path.join(prefix, 'Python'),
- '@executable_path/../.Python',
- py_executable])
- except:
- logger.fatal("Could not call install_name_tool -- you must "
- "have Apple's development tools installed")
- raise
-
- if not is_win:
- # Ensure that 'python', 'pythonX' and 'pythonX.Y' all exist
- py_exe_version_major = 'python%s' % sys.version_info[0]
- py_exe_version_major_minor = 'python%s.%s' % (
- sys.version_info[0], sys.version_info[1])
- py_exe_no_version = 'python'
- required_symlinks = [ py_exe_no_version, py_exe_version_major,
- py_exe_version_major_minor ]
-
- py_executable_base = os.path.basename(py_executable)
-
- if py_executable_base in required_symlinks:
- # Don't try to symlink to yourself.
- required_symlinks.remove(py_executable_base)
-
- for pth in required_symlinks:
- full_pth = join(bin_dir, pth)
- if os.path.exists(full_pth):
- os.unlink(full_pth)
- if symlink:
- os.symlink(py_executable_base, full_pth)
- else:
- copyfile(py_executable, full_pth, symlink)
-
- if is_win and ' ' in py_executable:
- # There's a bug with subprocess on Windows when using a first
- # argument that has a space in it. Instead we have to quote
- # the value:
- py_executable = '"%s"' % py_executable
- # NOTE: keep this check as one line, cmd.exe doesn't cope with line breaks
- cmd = [py_executable, '-c', 'import sys;out=sys.stdout;'
- 'getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))']
- logger.info('Testing executable with %s %s "%s"' % tuple(cmd))
- try:
- proc = subprocess.Popen(cmd,
- stdout=subprocess.PIPE)
- proc_stdout, proc_stderr = proc.communicate()
- except OSError:
- e = sys.exc_info()[1]
- if e.errno == errno.EACCES:
- logger.fatal('ERROR: The executable %s could not be run: %s' % (py_executable, e))
- sys.exit(100)
- else:
- raise e
-
- proc_stdout = proc_stdout.strip().decode("utf-8")
- proc_stdout = os.path.normcase(os.path.abspath(proc_stdout))
- norm_home_dir = os.path.normcase(os.path.abspath(home_dir))
- if hasattr(norm_home_dir, 'decode'):
- norm_home_dir = norm_home_dir.decode(sys.getfilesystemencoding())
- if proc_stdout != norm_home_dir:
- logger.fatal(
- 'ERROR: The executable %s is not functioning' % py_executable)
- logger.fatal(
- 'ERROR: It thinks sys.prefix is %r (should be %r)'
- % (proc_stdout, norm_home_dir))
- logger.fatal(
- 'ERROR: virtualenv is not compatible with this system or executable')
- if is_win:
- logger.fatal(
- 'Note: some Windows users have reported this error when they '
- 'installed Python for "Only this user" or have multiple '
- 'versions of Python installed. Copying the appropriate '
- 'PythonXX.dll to the virtualenv Scripts/ directory may fix '
- 'this problem.')
- sys.exit(100)
- else:
- logger.info('Got sys.prefix result: %r' % proc_stdout)
-
- pydistutils = os.path.expanduser('~/.pydistutils.cfg')
- if os.path.exists(pydistutils):
- logger.notify('Please make sure you remove any previous custom paths from '
- 'your %s file.' % pydistutils)
- ## FIXME: really this should be calculated earlier
-
- fix_local_scheme(home_dir, symlink)
-
- if site_packages:
- if os.path.exists(site_packages_filename):
- logger.info('Deleting %s' % site_packages_filename)
- os.unlink(site_packages_filename)
-
- return py_executable
-
-
-def install_activate(home_dir, bin_dir, prompt=None):
- if is_win or is_jython and os._name == 'nt':
- files = {
- 'activate.bat': ACTIVATE_BAT,
- 'deactivate.bat': DEACTIVATE_BAT,
- 'activate.ps1': ACTIVATE_PS,
- }
-
- # MSYS needs paths of the form /c/path/to/file
- drive, tail = os.path.splitdrive(home_dir.replace(os.sep, '/'))
- home_dir_msys = (drive and "/%s%s" or "%s%s") % (drive[:1], tail)
-
- # Run-time conditional enables (basic) Cygwin compatibility
- home_dir_sh = ("""$(if [ "$OSTYPE" "==" "cygwin" ]; then cygpath -u '%s'; else echo '%s'; fi;)""" %
- (home_dir, home_dir_msys))
- files['activate'] = ACTIVATE_SH.replace('__VIRTUAL_ENV__', home_dir_sh)
-
- else:
- files = {'activate': ACTIVATE_SH}
-
- # suppling activate.fish in addition to, not instead of, the
- # bash script support.
- files['activate.fish'] = ACTIVATE_FISH
-
- # same for csh/tcsh support...
- files['activate.csh'] = ACTIVATE_CSH
-
- files['activate_this.py'] = ACTIVATE_THIS
-
- install_files(home_dir, bin_dir, prompt, files)
-
-def install_files(home_dir, bin_dir, prompt, files):
- if hasattr(home_dir, 'decode'):
- home_dir = home_dir.decode(sys.getfilesystemencoding())
- vname = os.path.basename(home_dir)
- for name, content in files.items():
- content = content.replace('__VIRTUAL_PROMPT__', prompt or '')
- content = content.replace('__VIRTUAL_WINPROMPT__', prompt or '(%s)' % vname)
- content = content.replace('__VIRTUAL_ENV__', home_dir)
- content = content.replace('__VIRTUAL_NAME__', vname)
- content = content.replace('__BIN_NAME__', os.path.basename(bin_dir))
- writefile(os.path.join(bin_dir, name), content)
-
-def install_python_config(home_dir, bin_dir, prompt=None):
- if sys.platform == 'win32' or is_jython and os._name == 'nt':
- files = {}
- else:
- files = {'python-config': PYTHON_CONFIG}
- install_files(home_dir, bin_dir, prompt, files)
- for name, content in files.items():
- make_exe(os.path.join(bin_dir, name))
-
-def install_distutils(home_dir):
- distutils_path = change_prefix(distutils.__path__[0], home_dir)
- mkdir(distutils_path)
- ## FIXME: maybe this prefix setting should only be put in place if
- ## there's a local distutils.cfg with a prefix setting?
- home_dir = os.path.abspath(home_dir)
- ## FIXME: this is breaking things, removing for now:
- #distutils_cfg = DISTUTILS_CFG + "\n[install]\nprefix=%s\n" % home_dir
- writefile(os.path.join(distutils_path, '__init__.py'), DISTUTILS_INIT)
- writefile(os.path.join(distutils_path, 'distutils.cfg'), DISTUTILS_CFG, overwrite=False)
-
-def fix_local_scheme(home_dir, symlink=True):
- """
- Platforms that use the "posix_local" install scheme (like Ubuntu with
- Python 2.7) need to be given an additional "local" location, sigh.
- """
- try:
- import sysconfig
- except ImportError:
- pass
- else:
- if sysconfig._get_default_scheme() == 'posix_local':
- local_path = os.path.join(home_dir, 'local')
- if not os.path.exists(local_path):
- os.mkdir(local_path)
- for subdir_name in os.listdir(home_dir):
- if subdir_name == 'local':
- continue
- copyfile(os.path.abspath(os.path.join(home_dir, subdir_name)), \
- os.path.join(local_path, subdir_name), symlink)
-
-def fix_lib64(lib_dir, symlink=True):
- """
- Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y
- instead of lib/pythonX.Y. If this is such a platform we'll just create a
- symlink so lib64 points to lib
- """
- # PyPy's library path scheme is not affected by this.
- # Return early or we will die on the following assert.
- if is_pypy:
- logger.debug('PyPy detected, skipping lib64 symlinking')
- return
- # Check we have a lib64 library path
- if not [p for p in distutils.sysconfig.get_config_vars().values()
- if isinstance(p, basestring) and 'lib64' in p]:
- return
-
- logger.debug('This system uses lib64; symlinking lib64 to lib')
-
- assert os.path.basename(lib_dir) == 'python%s' % sys.version[:3], (
- "Unexpected python lib dir: %r" % lib_dir)
- lib_parent = os.path.dirname(lib_dir)
- top_level = os.path.dirname(lib_parent)
- lib_dir = os.path.join(top_level, 'lib')
- lib64_link = os.path.join(top_level, 'lib64')
- assert os.path.basename(lib_parent) == 'lib', (
- "Unexpected parent dir: %r" % lib_parent)
- if os.path.lexists(lib64_link):
- return
- if symlink:
- os.symlink('lib', lib64_link)
- else:
- copyfile('lib', lib64_link)
-
-def resolve_interpreter(exe):
- """
- If the executable given isn't an absolute path, search $PATH for the interpreter
- """
- # If the "executable" is a version number, get the installed executable for
- # that version
- python_versions = get_installed_pythons()
- if exe in python_versions:
- exe = python_versions[exe]
-
- if os.path.abspath(exe) != exe:
- paths = os.environ.get('PATH', '').split(os.pathsep)
- for path in paths:
- if os.path.exists(join(path, exe)):
- exe = join(path, exe)
- break
- if not os.path.exists(exe):
- logger.fatal('The executable %s (from --python=%s) does not exist' % (exe, exe))
- raise SystemExit(3)
- if not is_executable(exe):
- logger.fatal('The executable %s (from --python=%s) is not executable' % (exe, exe))
- raise SystemExit(3)
- return exe
-
-def is_executable(exe):
- """Checks a file is executable"""
- return os.access(exe, os.X_OK)
-
-############################################################
-## Relocating the environment:
-
-def make_environment_relocatable(home_dir):
- """
- Makes the already-existing environment use relative paths, and takes out
- the #!-based environment selection in scripts.
- """
- home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir)
- activate_this = os.path.join(bin_dir, 'activate_this.py')
- if not os.path.exists(activate_this):
- logger.fatal(
- 'The environment doesn\'t have a file %s -- please re-run virtualenv '
- 'on this environment to update it' % activate_this)
- fixup_scripts(home_dir, bin_dir)
- fixup_pth_and_egg_link(home_dir)
- ## FIXME: need to fix up distutils.cfg
-
-OK_ABS_SCRIPTS = ['python', 'python%s' % sys.version[:3],
- 'activate', 'activate.bat', 'activate_this.py',
- 'activate.fish', 'activate.csh']
-
-def fixup_scripts(home_dir, bin_dir):
- if is_win:
- new_shebang_args = (
- '%s /c' % os.path.normcase(os.environ.get('COMSPEC', 'cmd.exe')),
- '', '.exe')
- else:
- new_shebang_args = ('/usr/bin/env', sys.version[:3], '')
-
- # This is what we expect at the top of scripts:
- shebang = '#!%s' % os.path.normcase(os.path.join(
- os.path.abspath(bin_dir), 'python%s' % new_shebang_args[2]))
- # This is what we'll put:
- new_shebang = '#!%s python%s%s' % new_shebang_args
-
- for filename in os.listdir(bin_dir):
- filename = os.path.join(bin_dir, filename)
- if not os.path.isfile(filename):
- # ignore subdirs, e.g. .svn ones.
- continue
- f = open(filename, 'rb')
- try:
- try:
- lines = f.read().decode('utf-8').splitlines()
- except UnicodeDecodeError:
- # This is probably a binary program instead
- # of a script, so just ignore it.
- continue
- finally:
- f.close()
- if not lines:
- logger.warn('Script %s is an empty file' % filename)
- continue
-
- old_shebang = lines[0].strip()
- old_shebang = old_shebang[0:2] + os.path.normcase(old_shebang[2:])
-
- if not old_shebang.startswith(shebang):
- if os.path.basename(filename) in OK_ABS_SCRIPTS:
- logger.debug('Cannot make script %s relative' % filename)
- elif lines[0].strip() == new_shebang:
- logger.info('Script %s has already been made relative' % filename)
- else:
- logger.warn('Script %s cannot be made relative (it\'s not a normal script that starts with %s)'
- % (filename, shebang))
- continue
- logger.notify('Making script %s relative' % filename)
- script = relative_script([new_shebang] + lines[1:])
- f = open(filename, 'wb')
- f.write('\n'.join(script).encode('utf-8'))
- f.close()
-
-def relative_script(lines):
- "Return a script that'll work in a relocatable environment."
- activate = "import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); exec(compile(open(activate_this).read(), activate_this, 'exec'), dict(__file__=activate_this)); del os, activate_this"
- # Find the last future statement in the script. If we insert the activation
- # line before a future statement, Python will raise a SyntaxError.
- activate_at = None
- for idx, line in reversed(list(enumerate(lines))):
- if line.split()[:3] == ['from', '__future__', 'import']:
- activate_at = idx + 1
- break
- if activate_at is None:
- # Activate after the shebang.
- activate_at = 1
- return lines[:activate_at] + ['', activate, ''] + lines[activate_at:]
-
-def fixup_pth_and_egg_link(home_dir, sys_path=None):
- """Makes .pth and .egg-link files use relative paths"""
- home_dir = os.path.normcase(os.path.abspath(home_dir))
- if sys_path is None:
- sys_path = sys.path
- for path in sys_path:
- if not path:
- path = '.'
- if not os.path.isdir(path):
- continue
- path = os.path.normcase(os.path.abspath(path))
- if not path.startswith(home_dir):
- logger.debug('Skipping system (non-environment) directory %s' % path)
- continue
- for filename in os.listdir(path):
- filename = os.path.join(path, filename)
- if filename.endswith('.pth'):
- if not os.access(filename, os.W_OK):
- logger.warn('Cannot write .pth file %s, skipping' % filename)
- else:
- fixup_pth_file(filename)
- if filename.endswith('.egg-link'):
- if not os.access(filename, os.W_OK):
- logger.warn('Cannot write .egg-link file %s, skipping' % filename)
- else:
- fixup_egg_link(filename)
-
-def fixup_pth_file(filename):
- lines = []
- prev_lines = []
- f = open(filename)
- prev_lines = f.readlines()
- f.close()
- for line in prev_lines:
- line = line.strip()
- if (not line or line.startswith('#') or line.startswith('import ')
- or os.path.abspath(line) != line):
- lines.append(line)
- else:
- new_value = make_relative_path(filename, line)
- if line != new_value:
- logger.debug('Rewriting path %s as %s (in %s)' % (line, new_value, filename))
- lines.append(new_value)
- if lines == prev_lines:
- logger.info('No changes to .pth file %s' % filename)
- return
- logger.notify('Making paths in .pth file %s relative' % filename)
- f = open(filename, 'w')
- f.write('\n'.join(lines) + '\n')
- f.close()
-
-def fixup_egg_link(filename):
- f = open(filename)
- link = f.readline().strip()
- f.close()
- if os.path.abspath(link) != link:
- logger.debug('Link in %s already relative' % filename)
- return
- new_link = make_relative_path(filename, link)
- logger.notify('Rewriting link %s in %s as %s' % (link, filename, new_link))
- f = open(filename, 'w')
- f.write(new_link)
- f.close()
-
-def make_relative_path(source, dest, dest_is_directory=True):
- """
- Make a filename relative, where the filename is dest, and it is
- being referred to from the filename source.
-
- >>> make_relative_path('/usr/share/something/a-file.pth',
- ... '/usr/share/another-place/src/Directory')
- '../another-place/src/Directory'
- >>> make_relative_path('/usr/share/something/a-file.pth',
- ... '/home/user/src/Directory')
- '../../../home/user/src/Directory'
- >>> make_relative_path('/usr/share/a-file.pth', '/usr/share/')
- './'
- """
- source = os.path.dirname(source)
- if not dest_is_directory:
- dest_filename = os.path.basename(dest)
- dest = os.path.dirname(dest)
- dest = os.path.normpath(os.path.abspath(dest))
- source = os.path.normpath(os.path.abspath(source))
- dest_parts = dest.strip(os.path.sep).split(os.path.sep)
- source_parts = source.strip(os.path.sep).split(os.path.sep)
- while dest_parts and source_parts and dest_parts[0] == source_parts[0]:
- dest_parts.pop(0)
- source_parts.pop(0)
- full_parts = ['..']*len(source_parts) + dest_parts
- if not dest_is_directory:
- full_parts.append(dest_filename)
- if not full_parts:
- # Special case for the current directory (otherwise it'd be '')
- return './'
- return os.path.sep.join(full_parts)
-
-
-
-############################################################
-## Bootstrap script creation:
-
-def create_bootstrap_script(extra_text, python_version=''):
- """
- Creates a bootstrap script, which is like this script but with
- extend_parser, adjust_options, and after_install hooks.
-
- This returns a string that (written to disk of course) can be used
- as a bootstrap script with your own customizations. The script
- will be the standard virtualenv.py script, with your extra text
- added (your extra text should be Python code).
-
- If you include these functions, they will be called:
-
- ``extend_parser(optparse_parser)``:
- You can add or remove options from the parser here.
-
- ``adjust_options(options, args)``:
- You can change options here, or change the args (if you accept
- different kinds of arguments, be sure you modify ``args`` so it is
- only ``[DEST_DIR]``).
-
- ``after_install(options, home_dir)``:
-
- After everything is installed, this function is called. This
- is probably the function you are most likely to use. An
- example would be::
-
- def after_install(options, home_dir):
- subprocess.call([join(home_dir, 'bin', 'easy_install'),
- 'MyPackage'])
- subprocess.call([join(home_dir, 'bin', 'my-package-script'),
- 'setup', home_dir])
-
- This example immediately installs a package, and runs a setup
- script from that package.
-
- If you provide something like ``python_version='2.5'`` then the
- script will start with ``#!/usr/bin/env python2.5`` instead of
- ``#!/usr/bin/env python``. You can use this when the script must
- be run with a particular Python version.
- """
- filename = __file__
- if filename.endswith('.pyc'):
- filename = filename[:-1]
- f = codecs.open(filename, 'r', encoding='utf-8')
- content = f.read()
- f.close()
- py_exe = 'python%s' % python_version
- content = (('#!/usr/bin/env %s\n' % py_exe)
- + '## WARNING: This file is generated\n'
- + content)
- return content.replace('##EXT' 'END##', extra_text)
-
-##EXTEND##
-
-def convert(s):
- b = base64.b64decode(s.encode('ascii'))
- return zlib.decompress(b).decode('utf-8')
-
-##file site.py
-SITE_PY = convert("""
-eJzFPf1z2zaWv/OvwMqToZTKdOJ0e3tO3RsncVrfuYm3yc7m1vXoKAmyWFMkS5C2tTd3f/u9DwAE
-+CHb2+6cphNLJPDw8PC+8PAeOhqNTopCZkuxyZd1KoWScblYiyKu1kqs8lJU66Rc7hdxWW3h6eIm
-vpZKVLlQWxVhqygInv/GT/BcfF4nyqAA3+K6yjdxlSziNN2KZFPkZSWXYlmXSXYtkiypkjhN/g4t
-8iwSz387BsFZJmDmaSJLcStLBXCVyFfiYlut80yM6wLn/DL6Y/xqMhVqUSZFBQ1KjTNQZB1XQSbl
-EtCElrUCUiaV3FeFXCSrZGEb3uV1uhRFGi+k+K//4qlR0zAMVL6Rd2tZSpEBMgBTAqwC8YCvSSkW
-+VJGQryRixgH4OcNsQKGNsU1U0jGLBdpnl3DnDK5kErF5VaM53VFgAhlscwBpwQwqJI0De7y8kZN
-YElpPe7gkYiZPfzJMHvAPHH8LucAjh+z4C9Zcj9l2MA9CK5aM9uUcpXcixjBwk95Lxcz/WycrMQy
-Wa2ABlk1wSYBI6BEmswPClqOb/UKfXdAWFmujGEMiShzY35JPaLgrBJxqoBt6wJppAjzd3KexBlQ
-I7uF4QAikDToG2eZqMqOQ7MTOQAocR0rkJKNEuNNnGTArD/GC0L7r0m2zO/UhCgAq6XEL7Wq3PmP
-ewgArR0CTANcLLOadZYmNzLdTgCBz4B9KVWdVigQy6SUiyovE6kIAKC2FfIekJ6KuJSahMyZRm6n
-RH+iSZLhwqKAocDjSyTJKrmuS5IwsUqAc4Er3n/8Sbw7fXN28kHzmAHGMnu9AZwBCi20gxMMIA5q
-VR6kOQh0FJzjHxEvlyhk1zg+4NU0OHhwpYMxzL2I2n2cBQey68XVw8AcK1AmNFZA/f4bukzVGujz
-Pw+sdxCcDFGFJs7f7tY5yGQWb6RYx8xfyBnBtxrOd1FRrV8DNyiEUwGpFC4OIpggPCCJS7NxnklR
-AIulSSYnAVBoTm39VQRW+JBn+7TWLU4ACGWQwUvn2YRGzCRMtAvrNeoL03hLM9NNArvOm7wkxQH8
-ny1IF6VxdkM4KmIo/jaX10mWIULIC0G4F9LA6iYBTlxG4pxakV4wjUTI2otbokjUwEvIdMCT8j7e
-FKmcsviibt2tRmgwWQmz1ilzHLSsSL3SqjVT7eW9w+hLi+sIzWpdSgBezz2hW+X5VMxBZxM2Rbxh
-8arucuKcoEeeqBPyBLWEvvgdKHqiVL2R9iXyCmgWYqhgladpfgckOwoCIfawkTHKPnPCW3gH/wJc
-/DeV1WIdBM5IFrAGhcgPgUIgYBJkprlaI+Fxm2bltpJJMtYUebmUJQ31OGIfMOKPbIxzDT7klTZq
-PF1c5XyTVKiS5tpkJmzxsrBi/fia5w3TAMutiGamaUOnDU4vLdbxXBqXZC5XKAl6kV7bZYcxg54x
-yRZXYsNWBt4BWWTCFqRfsaDSWVWSnACAwcIXZ0lRp9RIIYOJGAbaFAR/E6NJz7WzBOzNZjlAhcTm
-ewH2B3D7O4jR3ToB+iwAAmgY1FKwfPOkKtFBaPRR4Bt905/HB049W2nbxEOu4iTVVj7OgjN6eFqW
-JL4LWWCvqSaGghlmFbp21xnQEcV8NBoFgXGHtsp8zVVQldsjYAVhxpnN5nWChm82Q1Ovf6iARxHO
-wF43287CAw1hOn0AKjldVmW+wdd2bp9AmcBY2CPYExekZSQ7yB4nvkbyuSq9ME3RdjvsLFAPBRc/
-nb4/+3L6SRyLy0alTdv67ArGPM1iYGuyCMBUrWEbXQYtUfElqPvEezDvxBRgz6g3ia+Mqxp4F1D/
-XNb0Gqax8F4Gpx9O3pyfzv7y6fSn2aezz6eAINgZGezRlNE81uAwqgiEA7hyqSJtX4NOD3rw5uST
-fRDMEjX75mtgN3gyvpYVMHE5hhlPRbiJ7xUwaDilphPEsdMALHg4mYjvxOHz568OCVqxLbYADMyu
-0xQfzrRFnyXZKg8n1PgXdumPWUlp/+3y6OsrcXwswl/i2zgMwIdqmjJL/Eji9HlbSOhawZ9xriZB
-sJQrEL0biQI6fk5+8YQ7wJJAy1zb6V/yJDPvmSvdIUh/jKkH4DCbLdJYKWw8m4VABOrQ84EOETvX
-KHVj6Fhs3a4TjQp+SgkLm2GXKf7Tg2I8p36IBqPodjGNQFw3i1hJbkXTh36zGeqs2WysBwRhJokB
-h4vVUChME9RZZQJ+LXEe6rC5ylP8ifBRC5AA4tYKtSQukt46RbdxWks1diYFRByPW2RERZso4kdw
-UcZgiZulm0za1DQ8A82AfGkOWrRsUQ4/e+DvgLoymzjc6PHei2mGmP477zQIB3A5Q1T3SrWgsHYU
-F6cX4tWLw310Z2DPubTU8ZqjhU6yWtqHK1gtIw+MMPcy8uLSZYV6Fp8e7Ya5iezKdFlhpZe4lJv8
-Vi4BW2RgZ5XFT/QGduYwj0UMqwh6nfwBVqHGb4xxH8qzB2lB3wGotyEoZv3N0u9xMEBmChQRb6yJ
-1HrXz6awKPPbBJ2N+Va/BFsJyhItpnFsAmfhPCZDkwgaArzgDCl1J0NQh2XNDivhjSDRXiwbxRoR
-uHPU1Ff09SbL77IZ74SPUemOJ5Z1UbA082KDZgn2xHuwQoBkDhu7hmgMBVx+gbK1D8jD9GG6QFna
-WwAgMPSKtmsOLLPVoynyrhGHRRiT14KEt5ToL9yaIWirZYjhQKK3kX1gtARCgslZBWdVg2YylDXT
-DAZ2SOJz3XnEW1AfQIuKEZjNsYbGjQz9Lo9AOYtzVyk5/dAif/nyhdlGrSm+gojNcdLoQqzIWEbF
-FgxrAjrBeGQcrSE2uAPnFsDUSrOm2P8k8oK9MVjPCy3b4AfA7q6qiqODg7u7u0hHF/Ly+kCtDv74
-p2+++dML1onLJfEPTMeRFh1qiw7oHXq00bfGAn1nVq7Fj0nmcyPBGkvyysgVRfy+r5NlLo72J1Z/
-Ihc3Zhr/Na4MKJCZGZSpDLQdNRg9U/vPoldqJJ6RdbZtxxP2S7RJtVbMt7rQo8rBEwC/ZZHXaKob
-TlDiK7BusENfynl9HdrBPRtpfsBUUU7Hlgf2X14hBj5nGL4ypniGWoLYAi2+Q/qfmG1i8o60hkDy
-oonq7J63/VrMEHf5eHm3vqYjNGaGiULuQInwmzxaAG3jruTgR7u2aPcc19Z8PENgLH1gmFc7lmMU
-HMIF12LqSp3D1ejxgjTdsWoGBeOqRlDQ4CTOmdoaHNnIEEGid2M2+7ywugXQqRU5NPEBswrQwh2n
-Y+3arOB4QsgDx+IlPZHgIh913r3gpa3TlAI6LR71qMKAvYVGO50DX44NgKkYlX8ZcUuzTfnYWhRe
-gx5gOceAkMFWHWbCN64PONob9bBTx+oP9WYa94HARRpzLOpR0AnlYx6hVCBNxdjvOcTilrjdwXZa
-HGIqs0wk0mpAuNrKo1eodhqmVZKh7nUWKVqkOXjFVisSIzXvfWeB9kH4uM+YaQnUZGjI4TQ6Jm/P
-E8BQt8Pw2XWNgQY3DoMYbRJF1g3JtIZ/wK2g+AYFo4CWBM2CeayU+RP7HWTOzld/GWAPS2hkCLfp
-kBvSsRgajnm/J5CMOhoDUpABCbvCSK4jq4MUOMxZIE+44bUclG6CESmQM8eCkJoB3Omlt8HBJxGe
-gJCEIuT7SslCfCVGsHxtUX2c7v5dudQEIcZOA3IVdPTi2I1sOFGN41aUw2doP75BZyVFDhw8B5fH
-DfS7bG6Y1gZdwFn3FbdFCjQyxWFGExfVK0MYN5j8h2OnRUMsM4hhKG8g70jHjDQJ7HJr0LDgBoy3
-5u2x9GM3YoF9x2GuDuXmHvZ/YZmoRa5Cipm0YxfuR3NFlzYW2/NkPoI/3gKMJlceJJnq+AVGWf6B
-QUIPetgH3ZsshkWWcXmXZCEpME2/Y39pOnhYUnpG7uATbacOYKIY8Tx4X4KA0NHnAYgTagLYlctQ
-abe/C3bnFEcWLncfeW7z5dGrqy5xp0MRHvvpX6rT+6qMFa5WyovGQoGr1TXgqHRhcnG21YeX+nAb
-twllrmAXKT5++iKQEBzXvYu3T5t6w/CIzYNz8j4GddBrD5KrNTtiF0AEtSIyykH4dI58PLJPndyO
-iT0ByJMYZseiGEiaT/4ROLsWCsbYX24zjKO1VQZ+4PU3X896IqMukt98PXpglBYx+sR+3PIE7cic
-VLBrtqWMU3I1nD4UVMwa1rFtignrc9r+aR676vE5NVo29t3fAj8GCobUJfgIL6YN2bpTxY/vTg3C
-03ZqB7DObtV89mgRYG+fz3+BHbLSQbXbOEnpXAEmv7+PytVs7jle0a89PEg7FYxDgr79l7p8AdwQ
-cjRh0p2OdsZOTMC5ZxdsPkWsuqjs6RyC5gjMywtwjz+HFU6ve+B7Bge/r7p8IiBvTqMeMmpbbIZ4
-wQclhz1K9gnzfvqMf9dZP27mw4L1/zHLF/+cST5hKgaaNh4+rH5iuXbXAHuEeRpwO3e4hd2h+axy
-ZZw7VklKPEfd9VzcUboCxVbxpAigLNnv64GDUqoPvd/WZclH16QCC1nu43HsVGCmlvH8ek3Mnjj4
-ICvExDZbUKzayevJ+4Qv1NFnO5Ow2Tf0c+c6NzErmd0mJfQFhTsOf/j442nYb0IwjgudHm9FHu83
-INwnMG6oiRM+pQ9T6Cld/nH10d66+AQ1GQEmIqzJ1iVsJxBs4gj9a/BARMg7sOVjdtyhL9ZycTOT
-lDqAbIpdnaD4W3yNmNiMAj//S8UrSmKDmSzSGmnFjjdmH67qbEHnI5UE/0qnCmPqECUEcPhvlcbX
-Ykydlxh60txI0anbuNTeZ1HmmJwq6mR5cJ0shfy1jlPc1svVCnDBwyv9KuLhKQIl3nFOAyctKrmo
-y6TaAglileuzP0p/cBrOtzzRsYckH/MwATEh4kh8wmnjeybc0pDLBAf8Ew+cJO67sYOTrBDRc3if
-5TMcdUY5vlNGqnsuT4+D9gg5ABgBUJj/aKIjd/4bSa/cA0Zac5eoqCU9UrqRhpycMYQynmCkg3/T
-T58RXd4awPJ6GMvr3Vhet7G87sXy2sfyejeWrkjgwtqglZGEvsBV+1ijN9/GjTnxMKfxYs3tMPcT
-czwBoijMBtvIFKdAe5EtPt8jIKS2nQNnetjkzyScVFrmHALXIJH78RBLb+ZN8rrTmbJxdGeeinFn
-h3KI/L4HUUSpYnPqzvK2jKs48uTiOs3nILYW3WkDYCra6UQcK81uZ3OO7rYs1ejiPz//8PEDNkdQ
-I5PeQN1wEdGw4FTGz+PyWnWlqdn8FcCO1NJPxKFuGuDeIyNrPMoe//OOMjyQccQdZSjkogAPgLK6
-bDM39ykMW891kpR+zkzOh03HYpRVo2ZSA0Q6ubh4d/L5ZEQhv9H/jlyBMbT1pcPFx7SwDbr+m9vc
-Uhz7gFDr2FZj/Nw5ebRuOOJhG2vAdjzf1oPDxxjs3jCBP8t/KqVgSYBQkQ7+PoVQj945/Kb9UIc+
-hhE7yX/uyRo7K/adI3uOi+KIft+xQ3sA/7AT9xgzIIB2ocZmZ9DslVtK35rXHRR1gD7S1/vNe832
-1qu9k/EpaifR4wA6lLXNht0/75yGjZ6S1ZvT788+nJ+9uTj5/IPjAqIr9/HTwaE4/fGLoPwQNGDs
-E8WYGlFhJhIYFrfQSSxz+K/GyM+yrjhIDL3enZ/rk5oNlrpg7jPanAiecxqThcZBM45C24c6/wgx
-SvUGyakponQdqjnC/dKG61lUrvOjqVRpjs5qrbdeulbM1JTRuXYE0geNXVIwCE4xg1eUxV6ZXWHJ
-J4C6zqoHKW2jbWJISkHBTrqAc/5lTle8QCl1hidNZ63oL0MX1/AqUkWawE7udWhlSXfD9JiGcfRD
-e8DNePVpQKc7jKwb8qwHsUCr9Trkuen+k4bRfq0Bw4bB3sG8M0npIZSBjcltIsRGfJITynv4apde
-r4GCBcODvgoX0TBdArOPYXMt1glsIIAn12B9cZ8AEFor4R8IHDnRAZljdkb4drPc/3OoCeK3/vnn
-nuZVme7/TRSwCxKcShT2ENNt/A42PpGMxOnH95OQkaPUXPHnGssDwCGhAKgj7ZS/xCfos7GS6Urn
-l/j6AF9oP4Fet7qXsih1937XOEQJeKbG5DU8U4Z+IaZ7WdhTnMqkBRorHyxmWEHopiGYz574tJZp
-qvPdz96dn4LviMUYKEF87nYKw3G8BI/QdfIdVzi2QOEBO7wukY1LdGEpyWIZec16g9YoctTby8uw
-60SB4W6vThS4jBPloj3GaTMsU04QISvDWphlZdZutUEKu22I4igzzBKzi5ISWH2eAF6mpzFviWCv
-hKUeJgLPp8hJVpmMxTRZgB4FlQsKdQpCgsTFekbivDzjGHheKlMGBQ+LbZlcrys83YDOEZVgYPMf
-T76cn32gsoTDV43X3cOcU9oJTDmJ5BhTBDHaAV/ctD/kqtmsj2f1K4SB2gf+tF9xdsoxD9Dpx4FF
-/NN+xXVox85OkGcACqou2uKBGwCnW5/cNLLAuNp9MH7cFMAGMx8MxSKx7EUnerjz63KibdkyJRT3
-MS+fcICzKmxKmu7spqS1P3qOqwLPuZbj/kbwtk+2zGcOXW86b4aS39xPRwqxJBYw6rb2xzDZYZ2m
-ejoOsw1xC21rtY39OXNipU67RYaiDEQcu50nLpP1K2HdnDnQS6PuABPfanSNJPaq8tHP2Uh7GB4m
-ltidfYrpSGUsZAQwkiF17U8NPhRaBFAglP07diR3Onl+6M3RsQYPz1HrLrCNP4Ai1Lm4VOORl8CJ
-8OVXdhz5FaGFevRIhI6nkskst3li+Llbo1f50p9jrwxQEBPFroyzazlmWFMD8yuf2AMhWNK2Hqkv
-k6s+wyLOwDm9H+Dwrlz0H5wY1FqM0Gl3I7dtdeSTBxv0loLsJJgPvozvQPcXdTXmlRw4h+6tpRuG
-+jBEzD6Epvr0fRxiOObXcGB9GsC91NCw0MP7deDsktfGOLLWPraqmkL7QnuwixK2ZpWiYxmnONH4
-otYLaAzucWPyR/apThSyv3vqxJyYkAXKg7sgvbmNdINWOGHE5UpcOZpQOnxTTaPfLeWtTMFogJEd
-Y7XDL7baYRLZcEpvHthvxu5ie7Htx43eNJgdmXIMRIAKMXoDPbsQanDAFf5Z70Ti7Iac47d/PZuK
-tx9+gn/fyI9gQbHmcSr+BqOLt3kJ20ou2qXbFLCAo+L9Yl4rLIwkaHRCwRdPoLd24ZEXT0N0ZYlf
-UmIVpMBk2nLDt50AijxBKmRv3ANTLwG/TUFXywk1DmLfWoz0S6TBcI0L1oUc6JbRutqkaCac4Eiz
-iJej87O3px8+nUbVPTK2+Tlygid+HhZORx8Nl3gMNhX2yaLGJ1eOv/yDTIsed1nvNU29DO41RQjb
-kcLuL/kmjdjuKeISAwai2C7zRYQtgdO5RK+6A/954mwrH7TvnnFFWOOJPjxrnHh8DNQQP7f1zwga
-Uh89J+pJCMVzrBXjx9Go3wJPBUW04c/zm7ulGxDXRT80wTamzazHfnerAtdMZw3PchLhdWyXwdSB
-pkmsNvOFWx/4MRP6IhRQbnS8IVdxnVZCZrCVor093UgBCt4t6WMJYVZhK0Z1bhSdSe/irXJyj2Il
-RjjqiIrq8RyGAoWw9f4xvmEzgLWGouYSaIBOiNK2KXe6qnqxZgnmnRBRryff4C7JXrnJL5rCPChv
-jBeN/wrzRG+RMbqWlZ4/PxhPLl82CQ4UjF54Bb2LAoydyyZ7oDGL58+fj8S/Pez0MCpRmuc34I0B
-7F5n5ZxeDxhsPTm7Wl2H3ryJgB8Xa3kJD64oaG6f1xlFJHd0pQWR9q+BEeLahJYZTfuWOeZYXcnn
-y9yCz6m0wfhLltB1RxhRkqhs9a1RGG0y0kQsCYohjNUiSUKOTsB6bPMaa/Ewuqj5Rd4DxycIZopv
-8WCMd9hrdCwpb9Zyj0XnWIwI8IhSyng0KmamajTAc3ax1WjOzrKkaspIXrhnpvoKgMreYqT5SsR3
-KBlmHi1iOGWdHqs2jnW+k0W9jUq+uHTjjK1Z8uuHcAfWBknLVyuDKTw0i7TIZbkw5hRXLFkklQPG
-tEM43JkubyLrEwU9KI1AvZNVWFqJtm//YNfFxfQjHR/vm5F01lBlL8TimFCctfIKo6gZn6JPlpCW
-b82XCYzygaLZ2hPwxhJ/0LFUrCHw7u1wyxnrTN/HwWkbzSUdAIfugLIK0rKjpyOci8csfGbagVs0
-8EM7c8LtNimrOk5n+tqHGfppM3uervG0ZXA7CzyttwK+fQ6O777O2AfHwSTXID0x49ZUZByLlY5M
-RG5lmV+EVeTo5R2yrwQ+BVJmOTP10CZ2dGnZ1Raa6gRHR8UjqK9M8dKAQ26qZjoFJy7mU0pvMuUO
-A86zn29JV1eI78T41VQctnY+i2KLNzkBss+Woe+KUTeYihMMMHNs34shvjsW45dT8ccd0KOBAY4O
-3RHa+9gWhEEgr66eTMY0mRPZwr4U9of76hxG0PSM4+SqTf4umb4lKv1ri0pcIagTlV+2E5VbYw/u
-WzsfH8lwA4pjlcjl/jOFJNRIN7p5mMEJPyyg37M5Wrp2vKmoocK5OWxG7ho96GhE4zbbQUxRulZf
-XL+LuoYNp71zwKTJtFIV7S1zmMao0WsRFQDM+o7S8Bve7QLvNSlc/2zwiFUXAViwPREEXenJB2ZN
-w0ZQH3QEn6QBHmAUEeJhaqMoXMl6goiEdA8OMdFXrUNsh+N/d+bhEoOho9AOlt98vQtPVzB7izp6
-FnR3pYUnsra8ollu8+kPzHmM0tf1NwmMA6URHXBWzVWV5GYeYfYy30GT2yzmDV4GSSfTaBJT6bpN
-vJXmW7/Qj6HYASWTwVqAJ1Wv8CD5lu62PFGU9IZX1Hx9+HJqKoMZkJ7Aq+jVV/oKSOpmLj/wfeyp
-3rvBS93vMPoXB1hS+b3tq85uhqZ13LoLyh8spOjZJJpZOjSG6eE6kGbNYoF3JjbEZN/aXgDyHryd
-Ofg55vLTHBw22JBGfei6GqOR3iHVNiDAD5uMIcl5VNdGkSLSu4RtSHnuUpxPFgXdq9+CYAgBOX8d
-8xt0BeviyIbYjE3Bk8+xm82Jn+qmt+6M7Qka2+om3DV97r9r7rpFYGdukhk6c/frS10a6L7DVrSP
-Bhze0IR4VIlEo/H7jYlrB6Y6h6Y/Qq8/SH63E850wKw8BMZk7GC8n9hTY2/M/iZeuN8xIWyfL2R2
-y4l7nY3WtDs2o83xj/EUOPkFn9sbBiijaak5kPdLdMPejHNkZ/L6Ws1ivN1xRptsyufq7J7Mtu09
-Xc4nY7U1uy28tAhAGG7Smbducj0wBuhKvmWa06Gc22kEDU1Jw04WskqWbBL01g7ARRwxpf4mEM9p
-xKNUYqBb1WVRwm54pO8i5jydvtTmBqgJ4G1idWNQNz2m+mpaUqyUHGZKkDlO20ryASKwEe+YhtnM
-vgNeedFcs5BMLTPIrN7IMq6aK4b8jIAENl3NCFR0jovrhOcaqWxxiYtYYnnDQQoDZPb7V7Cx9DbV
-O+5VmFht93h2oh465PuUKxscY2S4OLm31wu611ot6Wpr1zu0zRqus1cqwTKYu/JIR+pYGb/V93fx
-HbMcyUf/0uEfkHe38tLPQrfqjL1bi4bzzFUI3Qub8MYAMs599zB2OKB742JrA2zH9/WFZZSOhznQ
-2FJR++S9CqcZbdJEkDBh9IEIkl8U8MQIkgf/kREkfWsmGBqNj9YDvWUCD4SaWD24V1A2jAB9ZkAk
-PMBuXWBoTOXYTbovcpXcj+yF0qwrnUo+Yx6QI7t3kxEIvmpSuRnK3lVwuyJIvnTR4+/PP745OSda
-zC5O3v7HyfeUlIXHJS1b9egQW5bvM7X3vfRvN9ymE2n6Bm+w7bkhlmuYNITO+04OQg+E/nq1vgVt
-KzL39VCHTt1PtxMgvnvaLahDKrsXcscv0zUmbvpMK0870E85qdb8cjITzCNzUsfi0JzEmffN4YmW
-0U5seWjhnPTWrjrR/qq+BXQg7j2xSda0Anhmgvxlj0xMxYwNzLOD0v7ffFBmOFYbmht0QAoX0rnJ
-kS5xZFCV//8TKUHZxbi3Y0dxau/mpnZ8PKTspfN49ruQkSGIV+436s7PFfalTAeoEASs8PQ9hYyI
-0X/6QNWmHzxT4nKfCov3Udlc2V+4Ztq5/WuCSQaVve9LcYISH7NC41WduokDtk+nAzl9dBqVr5xK
-FtB8B0DnRjwVsDf6S6wQ51sRwsZRu2SYHEt01Jf1Ocij3XSwN7R6IfaHyk7dskshXg43XLYqO3WP
-Q+6hHuihalPc51hgzNIcqicV3xFkPs4UdMGX53zgGbre9sPX28uXR/ZwAfkdXzuKhLLJRo5hv3Sy
-MXdeKul0J2Ypp5Suh3s1JySsW1w5UNknGNrbdEpSBvY/Js+BIY289/0hM9PDu3p/1MbUst4RTEmM
-n6kJTcsp4tG42yeT7nQbtdUFwgVJjwDSUYEAC8F0dKOTILrlLO/xC70bnNd0Ha97whQ6UkHJYj5H
-cA/j+zX4tbtTIfGjujOKpj83aHOgXnIQbvYduNXEC4UMm4T21Bs+GHABuCa7v//LR/TvpjHa7oe7
-/Grb6lVvHSD7spj5iplBLRKZxxEYGdCbY9LWWC5hBB2voWno6DJUMzfkC3T8KJsWL9umDQY5szPt
-AVijEPwfucjncQ==
-""")
-
-##file activate.sh
-ACTIVATE_SH = convert("""
-eJytVdtu2kAQffdXDAalSVqK6GMrqhIFCaQEIkyp2qZyFnuIVzVrtLsmIZd/76wvYONAHxI/gHdn
-dvbMnDPjOkwCrmDOQ4RFrDTMEGKFPtxxHYCtolh6CDMuWszTfMU02nA6l9ECZkwFp1Yd1lEMHhMi
-0iBjAVyDzyV6Olxblo/5KTg+gUcL6ImFQg3NOSzXfuRZyV4dJJrdKPQBxYrLSCxQaFgxydksRJV5
-1eA3NB+g8Tjtjt+7z/CHzulYCgVaxgh8DmQAysdHL2SS0mAaWBgmx8manbcbj+7o4tydDsaT790L
-96o76VM4m+J9AR2gSPzNYywdu1HxtjceeL+MpE4cN3tpipVDiX3O/wfm56Q/GvZHl709kDb2CrCN
-pQpvYzoIsuxFULO6JxpRQRQTPz5qYjehH5jw4UEFH+Au4F4AAVshMPojkxctFsasA6LAKCsLRfry
-iBGiRkdwSwhIMPQ2j6RZLBlJMDuqPgL8IBVGsc7MmovbLEzJ0RQIGqbE4AVM3KKCO5Iz883PGow0
-6VqS2JKQo58TQOUXpvxnXaffTEr99LTZ/OX03Wlv7AxGw+ZLNCRJNiV8+trycdUScaayvGgHCHba
-e5h12hVKnXaVS6d9kMTMnANJXXJrbzjdpl8z2NomvQ7YIhI+Kuoj07G4A68ODoZzyB1qOwCaxpS3
-en77s0XTIbVzKTHEFSu1dGE4lO+2rALaju26haXr2lZWh2JKVqXZqJJpo2aLgnfLdc8GQ3fYvey5
-7ufMrdjHG9zbhjAFox2rROuhVt3TWAbWTpvuXmUZ5lJ5JrcUsz8fON2zi557NR5dXk0qwtwVgrkt
-V1AS0b7fVjONQQWFWgfu98ix6r6NiKHCsvfxDY0FFGyBcF0q+bV9cwLbk9kQLAja5FyHS/YXQcUS
-zUiIBQs5U+l3wsDn+p2iaS6R+WsDVaJV9Ch0IhRej47KkSwrdd98kJZrmjECmossjt34ZqfifZOx
-9wYj75Xj7jWj7qUxR1z9A7WjbI8=
-""")
-
-##file activate.fish
-ACTIVATE_FISH = convert("""
-eJyFVVFv0zAQfs+vONJO3RDNxCsSQoMVrdK2Vl03CSHkesllMXLsYDvZivjx2GmTOG0YfWhV+7u7
-73z33Y1gnTENKeMIeakNPCKUGhP7xcQTbCJ4ZOKcxoZV1GCUMp1t4O0zMxkTQEGVQjicO4dTyIwp
-Ppyfu386Q86jWOZwBhq1ZlK8jYIRXEoQ0jhDYAYSpjA2fBsFQVoKG0UKSLAJB9MEJrMXi6uYMiXl
-KCrIZYJARQIKTakEGAkmQ+tU5ZSDRTAlRY7CRJMA7GdkgRoNSJ74t1BRxegjR12jWAoGbfpTAeGY
-LK4vycN8tb6/uCbLi/VVWGPcx3maPr2AO4VjYB+HMAxAkQT/i/ptfbW4vVrczAZit3eHDNqL13n0
-Ya+w+Tq/uyLL1eJmuSaLh9lqNb/0+IzgznqnAjAvzBa4jG0BNmNXfdJUkxTU2I6xRaKcy+e6VApz
-WVmoTGFTgwslrYdN03ONrbbMN1E/FQ7H7gOP0UxRjV67TPRBjF3naCMV1mSkYk9MUN7F8cODZzsE
-iIHYviIe6n8WeGQxWKuhl+9Xa49uijq7fehXMRxT9VR9f/8jhDcfYSKkSOyxKp22cNIrIk+nzd2b
-Yc7FNpHx8FUn15ZfzXEE98JxZEohx4r6kosCT+R9ZkHQtLmXGYSEeH8JCTvYkcRgXAutp9Rw7Jmf
-E/J5fktuL25m1tMe3vLdjDt9bNxr2sMo2P3C9BccqGeYhqfQITz6XurXaqdf99LF1mT2YJrvzqCu
-5w7dKvV3PzNyOb+7+Hw923dOuB+AX2SxrZs9Lm0xbCH6kmhjUyuWw+7cC7DX8367H3VzDz6oBtty
-tMIeobE21JT6HaRS+TbaoqhbE7rgdGs3xtE4cOF3xo0TfxwsdyRlhUoxuzes18r+Jp88zDx1G+kd
-/HTrr1BY2CeuyfnbQtAcu9j+pOw6cy9X0k3IuoyKCZPC5ESf6MkgHE5tLiSW3Oa+W2NnrQfkGv/h
-7tR5PNFnMBlw4B9NJTxnzKA9fLTT0aXSb5vw7FUKzcTZPddqYHi2T9/axJmEEN3qHncVCuEPaFmq
-uEtpcBj2Z1wjrqGReJBHrY6/go21NA==
-""")
-
-##file activate.csh
-ACTIVATE_CSH = convert("""
-eJx1U2FP2zAQ/e5f8TAV3Soo+0zXbYUiDQkKQgVp2ibjJNfFUuIg22nVf885SVFLO3+I7Lt3fr6X
-d8eY58ZjYQpCWfuAhFB7yrAyIYf0Ve1SQmLsuU6DWepAw9TnEoOFq0rwdjAUx/hV1Ui1tVWAqy1M
-QGYcpaFYx+yVI67LkKwx1UuTEaYGl4X2Bl+zJpAlP/6V2hTDtCq/DYXQhdEeGW040Q/Eb+t9V/e3
-U/V88zh/mtyqh8n8J47G+IKTE3gKZJdoYrK3h5MRU1tGYS83gqNc+3yEgyyP93cP820evHLvr2H8
-kaYB/peoyY7aVHzpJnE9e+6I5Z+ji4GMTNJWNuOQq6MA1N25p8pW9HWdVWlfsNpPDbdxjgpaahuw
-1M7opCA/FFu1uwxC7L8KUqmto1KyQe3rx0I0Eovdf7BVe67U5c1MzSZ310pddGheZoFPWyytRkzU
-aCA/I+RkBXhFXr5aWV0SxjhUI6jwdAj8kmhPzX7nTfJFkM3MImp2VdVFFq1vLHSU5szYQK4Ri+Jd
-xlW2JBtOGcyYVW7SnB3v6RS91g3gKapZ0oWxbHVteYIIq3iv7QeuSrUj6KSqQ+yqsxDj1ivNQxKF
-YON10Q+NH/ARS95i5Tuqq2Vxfvc23f/FO6zrtXXmJr+ZtMY9/A15ZXFWtmch2rEQ4g1ryVHH
-""")
-
-##file activate.bat
-ACTIVATE_BAT = convert("""
-eJx9Ul9LhEAQfxf8DoOclI/dYyFkaCmcq4gZQTBUrincuZFbff12T133TM+nnd35/Zvxlr7XDFhV
-mUZHOVhFlOWP3g4DUriIWoVomYZpNBWUtGpaWgImO191pFkSpzlcmgaI70jVX7n2Qp8tuByg+46O
-CMHbMq64T+nmlJt082D1T44muCDk2prgEHF4mdI9RaS/QwSt3zSyIAaftRccvqVTBziD1x/WlPD5
-xd729NDBb8Nr4DU9QNMKsJeH9pkhPedhQsIkDuCDCa6A+NF9IevVFAohkqizdHetg/tkWvPoftWJ
-MCqnOxv7/x7Np6yv9P2Ker5dmX8yNyCkkWnbZy3N5LarczlqL8htx2EM9rQ/2H5BvIsIEi8OEG8U
-+g8CsNTr
-""")
-
-##file deactivate.bat
-DEACTIVATE_BAT = convert("""
-eJyFkN0KgkAUhO8F32EQpHqFQEjQUPAPMaErqVxzId3IrV6/XST/UDx3c86c4WMO5FYysKJQFVVp
-CEfqxsnJ9DI7SA25i20fFqs3HO+GYLsDZ7h8GM3xfLHrg1QNvpSX4CWpQGvokZk4uqrQAjXjyElB
-a5IjCz0r+2dHcehHCe5MZNmB5R7TdqMqECMptHZh6DN/utb7Zs6Cej8OXYE5J04YOKFvD4GkHuJ0
-pilSd1jG6n87tDZ+BUwUOepI6CGSkFMYWf0ihvT33Qj1A+tCkSI=
-""")
-
-##file activate.ps1
-ACTIVATE_PS = convert("""
-eJylWdmO41hyfW+g/0FTU7C7IXeJIqmtB/3AnZRIStxF2kaBm7gv4ipyMF/mB3+Sf8GXVGVl1tLT
-43ECSqR4b5wbETeWE8z/+a///vNCDaN6cYtSf5G1dbNw/IVXNIu6aCvX9xa3qsgWl0IJ/7IYinbh
-2nkOVqs2X0TNjz/8eeFFle826fBhQRaLBkD9uviw+LCy3Sbq7Mb/UNbrH3+YNtLcVaB+Xbipb+eL
-tly0eVsD/M6u6g8//vC+dquobH5VWU75eMFUdvHb4n02RHlXuHYTFfmHbHCLLLNz70NpN+GrBI4p
-1EeSk4FAXaZR88u0vPip8usi7fznt3fvP+OuPnx49/Pil4td+XnzigIAPoqYQH2J8v4z+C+8b98m
-Q25t7k76LIK0cOz0V89/MXXx0+Lf6z5q3PA/F+/FIif9uqnaadFf/PzXSXYBfqIb2NeApecJwPzI
-dlL/149nnvyoc7KqYfzTAT8v/voUmX7e+3n364tffl/oVaDyswKY/7J18e6bve8Wv9RuUfqfLHmK
-/u139Hwx+9ePRep97KKqae30YwmCo2y+0vTz1k+rv7159B3pb1SOGj97Pe8/flfkC1Vn/7xYR4n6
-lypNEGDDV5f7lcjil3S+4++p881Wv6qKyn5GQg1yJwcp4BZ5E+Wt/z1P/umbiHir4J8Xip/eFt6n
-9T/9gU9eY+7zUX97Jlmb136ziKrKT/3OzpvP8VX/+MObSP0lL3LvVZlJ9v1b8357jXyw8rXxYPXN
-11n4UzJ8G8S/vUbuJ6RPj999DbtS5kys//JusXwrNLnvT99cFlBNwXCe+niRz8JF/ezNr9Pze+H6
-18W7d5PPvozW7+387Zto/v4pL8BvbxTzvIW9KCv/Fj0WzVQb/YXbVlPZWTz3/9vCaRtQbPN/Bb+j
-2rUrDxTVD68gfQXu/ZewAFX53U/vf/rD2P3558W7+W79Po1y/xXoX/6RFHyNIoVjgAG4H0RTcAe5
-3bSVv3DSwk2mZYHjFB8zj6fC4sLOFTHJJQrwzFYJgso0ApOoBzFiRzzQKjIQCCbQMIFJGCKqGUyS
-8AkjiF2wTwmMEbcEUvq8Nj+X0f4YcCQmYRiOY7eRbAJDqzm1chOoNstbJ8oTBhZQ2NcfgaB6QjLp
-U4+SWFjQGCZpyqby8V4JkPGs9eH1BscXIrTG24QxXLIgCLYNsIlxSYLA6SjAeg7HAg4/kpiIB8k9
-TCLm0EM4gKIxEj8IUj2dQeqSxEwYVH88qiRlCLjEYGuNIkJB1BA5dHOZdGAoUFk54WOqEojkuf4Q
-Ig3WY+96TDlKLicMC04h0+gDCdYHj0kz2xBDj9ECDU5zJ0tba6RKgXBneewhBG/xJ5m5FX+WSzsn
-wnHvKhcOciw9NunZ0BUF0n0IJAcJMdcLqgQb0zP19dl8t9PzmMBjkuIF7KkvHgqEovUPOsY0PBB1
-HCtUUhch83qEJPjQcNQDsgj0cRqx2ZbnnlrlUjE1EX2wFJyyDa/0GLrmKDEFepdWlsbmVU45Wiwt
-eFM6mfs4kxg8yc4YmKDy67dniLV5FUeO5AKNPZaOQQ++gh+dXE7dbJ1aTDr7S4WPd8sQoQkDyODg
-XnEu/voeKRAXZxB/e2xaJ4LTFLPYEJ15Ltb87I45l+P6OGFA5F5Ix8A4ORV6M1NH1uMuZMnmFtLi
-VpYed+gSq9JDBoHc05J4OhKetrk1p0LYiKipxLMe3tYS7c5V7O1KcPU8BJGdLfcswhoFCSGQqJ8f
-ThyQKy5EWFtHVuNhvTnkeTc8JMpN5li3buURh0+3ZGuzdwM55kon+8urbintjdQJf9U1D0ah+hNh
-i1XNu4fSKbTC5AikGEaj0CYM1dpuli7EoqUt7929f1plxGGNZnixFSFP2qzhlZMonu2bB9OWSqYx
-VuHKWNGJI8kqUhMTRtk0vJ5ycZ60JlodlmN3D9XiEj/cG2lSt+WV3OtMgt1Tf4/Z+1BaCus740kx
-Nvj78+jMd9tq537Xz/mNFyiHb0HdwHytJ3uQUzKkYhK7wjGtx3oKX43YeYoJVtqDSrCnQFzMemCS
-2bPSvP+M4yZFi/iZhAjL4UOeMfa7Ex8HKBqw4umOCPh+imOP6yVTwG2MplB+wtg97olEtykNZ6wg
-FJBNXSTJ3g0CCTEEMdUjjcaBDjhJ9fyINXgQVHhA0bjk9lhhhhOGzcqQSxYdj3iIN2xGEOODx4qj
-Q2xikJudC1ujCVOtiRwhga5nPdhe1gSa649bLJ0wCuLMcEYIeSy25YcDQHJb95nfowv3rQnin0fE
-zIXFkM/EwSGxvCCMgEPNcDp/wph1gMEa8Xd1qAWOwWZ/KhjlqzgisBpDDDXz9Cmov46GYBKHC4zZ
-84HJnXoTxyWNBbXV4LK/r+OEwSN45zBp7Cub3gIYIvYlxon5BzDgtPUYfXAMPbENGrI+YVGSeTQ5
-i8NMB5UCcC+YRGIBhgs0xhAGwSgYwywpbu4vpCSTdEKrsy8osXMUnHQYenQHbOBofLCNNTg3CRRj
-A1nXY2MZcjnXI+oQ2Zk+561H4CqoW61tbPKv65Y7fqc3TDUF9CA3F3gM0e0JQ0TPADJFJXVzphpr
-2FzwAY8apGCju1QGOiUVO5KV6/hKbtgVN6hRVwpRYtu+/OC6w2bCcGzZQ8NCc4WejNEjFxOIgR3o
-QqR1ZK0IaUxZ9nbL7GWJIjxBARUhAMnYrq/S0tVOjzlOSYRqeIZxaSaOBX5HSR3MFekOXVdUPbjX
-nru61fDwI8HRYPUS7a6Inzq9JLjokU6P6OzT4UCH+Nha+JrU4VqEo4rRHQJhVuulAnvFhYz5NWFT
-aS/bKxW6J3e46y4PLagGrCDKcq5B9EmP+s1QMCaxHNeM7deGEV3WPn3CeKjndlygdPyoIcNaL3dd
-bdqPs47frcZ3aNWQ2Tk+rjFR01Ul4XnQQB6CSKA+cZusD0CP3F2Ph0e78baybgioepG12luSpFXi
-bHbI6rGLDsGEodMObDG7uyxfCeU+1OiyXYk8fnGu0SpbpRoEuWdSUlNi5bd9nBxYqZGrq7Qa7zV+
-VLazLcelzzP9+n6+xUtWx9OVJZW3gk92XGGkstTJ/LreFVFF2feLpXGGuQqq6/1QbWPyhJXIXIMs
-7ySVlzMYqoPmnmrobbeauMIxrCr3sM+qs5HpwmmFt7SM3aRNQWpCrmeAXY28EJ9uc966urGKBL9H
-18MtDE5OX97GDOHxam11y5LCAzcwtkUu8wqWI1dWgHyxGZdY8mC3lXzbzncLZ2bIUxTD2yW7l9eY
-gBUo7uj02ZI3ydUViL7oAVFag37JsjYG8o4Csc5R7SeONGF8yZP+7xxi9scnHvHPcogJ44VH/LMc
-Yu6Vn3jEzCFw9Eqq1ENQAW8aqbUwSiAqi+nZ+OkZJKpBL66Bj8z+ATqb/8qDIJUeNRTwrI0YrVmb
-9FArKVEbCWUNSi8ipfVv+STgkpSsUhcBg541eeKLoBpLGaiHTNoK0r4nn3tZqrcIULtq20Df+FVQ
-Sa0MnWxTugMuzD410sQygF4qdntbswiJMqjs014Irz/tm+pd5oygJ0fcdNbMg165Pqi7EkYGAXcB
-dwxioCDA3+BY9+JjuOmJu/xyX2GJtaKSQcOZxyqFzTaa6/ot21sez0BtKjirROKRm2zuai02L0N+
-ULaX8H5P6VwsGPbYOY7sAy5FHBROMrMzFVPYhFHZ7M3ZCZa2hsT4jGow6TGtG8Nje9405uMUjdF4
-PtKQjw6yZOmPUmO8LjFWS4aPCfE011N+l3EdYq09O3iQJ9a01B3KXiMF1WmtZ+l1gmyJ/ibAHZil
-vQzdOl6g9PoSJ4TM4ghTnTndEVMOmsSSu+SCVlGCOLQRaw9oLzamSWP62VuxPZ77mZYdfTRGuNBi
-KyhZL32S2YckO/tU7y4Bf+QKKibQSKCTDWPUwWaE8yCBeL5FjpbQuAlb53mGX1jptLeRotREbx96
-gnicYz0496dYauCjpTCA4VA0cdLJewzRmZeTwuXWD0talJsSF9J1Pe72nkaHSpULgNeK1+o+9yi0
-YpYwXZyvaZatK2eL0U0ZY6ekZkFPdC8JTF4Yo1ytawNfepqUKEhwznp6HO6+2l7L2R9Q3N49JMIe
-Z+ax1mVaWussz98QbNTRPo1xu4W33LJpd9H14dd66ype7UktfEDi3oUTccJ4nODjwBKFxS7lYWiq
-XoHu/b7ZVcK5TbRD0F/2GShg2ywwUl07k4LLqhofKxFBNd1grWY+Zt/cPtacBpV9ys2z1moMLrT3
-W0Elrjtt5y/dvDQYtObYS97pqj0eqmwvD3jCPRqamGthLiF0XkgB6IdHLBBwDGPiIDh7oPaRmTrN
-tYA/yQKFxRiok+jM6ciJq/ZgiOi5+W4DEmufPEubeSuYJaM3/JHEevM08yJAXUQwb9LS2+8FOfds
-FfOe3Bel6EDSjIEIKs4o9tyt67L1ylQlzhe0Q+7ue/bJnWMcD3q6wDSIQi8ThnRM65aqLWesi/ZM
-xhHmQvfKBbWcC194IPjbBLYR9JTPITbzwRcu+OSFHDHNSYCLt29sAHO6Gf0h/2UO9Xwvhrjhczyx
-Ygz6CqP4IwxQj5694Q1Pe2IR+KF/yy+5PvCL/vgwv5mPp9n4kx7fnY/nmV++410qF/ZVCMyv5nAP
-pkeOSce53yJ6ahF4aMJi52by1HcCj9mDT5i+7TF6RoPaLL+cN1hXem2DmX/mdIbeeqwQOLD5lKO/
-6FM4x77w6D5wMx3g0IAfa2D/pgY9a7bFQbinLDPz5dZi9ATIrd0cB5xfC0BfCCZO7TKP0jQ2Meih
-nRXhkA3smTAnDN9IW2vA++lsgNuZ2QP0UhqyjUPrDmgfWP2bWWiKA+YiEK7xou8cY0+d3/bk0oHR
-QLrq4KzDYF/ljQDmNhBHtkVNuoDey6TTeaD3SHO/Bf4d3IwGdqQp6FuhmwFbmbQBssDXVKDBYOpk
-Jy7wxOaSRwr0rDmGbsFdCM+7XU/84JPu3D/gW7QXgzlvbjixn99/8CpWFUQWHFEz/RyXvzNXTTOd
-OXLNNFc957Jn/YikNzEpUdRNxXcC6b76ccTwMGoKj5X7c7TvHFgc3Tf4892+5A+iR+D8OaaE6ACe
-gdgHcyCoPm/xiDCWP+OZRjpzfj5/2u0i4qQfmIEOsTV9Hw6jZ3Agnh6hiwjDtGYxWvt5TiWEuabN
-77YCyRXwO8P8wdzG/8489KwfFBZWI6Vvx76gmlOc03JI1HEfXYZEL4sNFQ3+bqf7e2hdSWQknwKF
-ICJjGyDs3fdmnnxubKXebpQYLjPgEt9GTzKkUgTvOoQa1J7N3nv4sR6uvYFLhkXZ+pbCoU3K9bfq
-gF7W82tNutRRZExad+k4GYYsCfmEbvizS4jsRr3fdzqjEthpEwm7pmN7OgVzRbrktjrFw1lc0vM8
-V7dyTJ71qlsd7v3KhmHzeJB35pqEOk2pEe5uPeCToNkmedmxcKbIj+MZzjFSsvCmimaMQB1uJJKa
-+hoWUi7aEFLvIxKxJavqpggXBIk2hr0608dIgnfG5ZEprqmH0b0YSy6jVXTCuIB+WER4d5BPVy9Q
-M4taX0RIlDYxQ2CjBuq78AAcHQf5qoKP8BXHnDnd/+ed5fS+csL4g3eWqECaL+8suy9r8hx7c+4L
-EegEWdqAWN1w1NezP34xsxLkvRRI0DRzKOg0U+BKfQY128YlYsbwSczEg2LqKxRmcgiwHdhc9MQJ
-IwKQHlgBejWeMGDYYxTOQUiJOmIjJbzIzHH6lAMP+y/fR0v1g4wx4St8fcqTt3gz5wc+xXFZZ3qI
-JpXI5iJk7xmNL2tYsDpcqu0375Snd5EKsIvg8u5szTOyZ4v06Ny2TZXRpHUSinh4IFp8Eoi7GINJ
-02lPJnS/9jSxolJwp2slPMIEbjleWw3eec4XaetyEnSSqTPRZ9fVA0cPXMqzrPYQQyrRux3LaAh1
-wujbgcObg1nt4iiJ5IMbc/WNPc280I2T4nTkdwG8H6iS5xO2WfsFsruBwf2QkgZlb6w7om2G65Lr
-r2Gl4dk63F8rCEHoUJ3fW+pU2Srjlmcbp+JXY3DMifEI22HcHAvT7zzXiMTr7VbUR5a2lZtJkk4k
-1heZZFdru8ucCWMTr3Z4eNnjLm7LW7rcN7QjMpxrsCzjxndeyFUX7deIs3PQkgyH8k6luI0uUyLr
-va47TBjM4JmNHFzGPcP6BV6cYgQy8VQYZe5GmzZHMxyBYhGiUdekZQ/qwyxC3WGylQGdUpSf9ZCP
-a7qPdJd31fPRC0TOgzupO7nLuBGr2A02yuUQwt2KQG31sW8Gd9tQiHq+hPDt4OzJuY4pS8XRsepY
-tsd7dVEfJFmc15IYqwHverrpWyS1rFZibDPW1hUUb+85CGUzSBSTK8hpvee/ZxonW51TUXekMy3L
-uy25tMTg4mqbSLQQJ+skiQu2toIfBFYrOWql+EQipgfT15P1aq6FDK3xgSjIGWde0BPftYchDTdM
-i4QdudHFkN0u6fSKiT09QLv2mtSblt5nNzBR6UReePNs+khE4rHcXuoK21igUKHl1c3MXMgPu7y8
-rKQDxR6N/rffXv+lROXet/9Q+l9I4D1U
-""")
-
-##file distutils-init.py
-DISTUTILS_INIT = convert("""
-eJytV1uL4zYUfvevOE0ottuMW9q3gVDa3aUMXXbLMlDKMBiNrSTqOJKRlMxkf33PkXyRbGe7Dw2E
-UXTu37lpxLFV2oIyifAncxmOL0xLIfcG+gv80x9VW6maw7o/CANSWWBwFtqeWMPlGY6qPjV8A0bB
-C4eKSTgZ5LRgFeyErMEeOBhbN+Ipgeizhjtnhkn7DdyjuNLPoCS0l/ayQTG0djwZC08cLXozeMss
-aG5EzQ0IScpnWtHSTXuxByV/QCmxE7y+eS0uxWeoheaVVfqSJHiU7Mhhi6gULbOHorshkrEnKxpT
-0n3A8Y8SMpuwZx6aoix3ouFlmW8gHRSkeSJ2g7hU+kiHLDaQw3bmRDaTGfTnty7gPm0FHbIBg9U9
-oh1kZzAFLaue2R6htPCtAda2nGlDSUJ4PZBgCJBGVcwKTAMz/vJiLD+Oin5Z5QlvDPdulC6EsiyE
-NFzb7McNTKJzbJqzphx92VKRFY1idenzmq3K0emRcbWBD0ryqc4NZGmKOOOX9Pz5x+/l27tP797c
-f/z0d+4NruGNai8uAM0bfsYaw8itFk8ny41jsfpyO+BWlpqfhcG4yxLdi/0tQqoT4a8Vby382mt8
-p7XSo7aWGdPBc+b6utaBmCQ7rQKQoWtAuthQCiold2KfJIPTT8xwg9blPumc+YDZC/wYGdAyHpJk
-vUbHbHWAp5No6pK/WhhLEWrFjUwtPEv1Agf8YmnsuXUQYkeZoHm8ogP16gt2uHoxcEMdf2C6pmbw
-hUMsWGhanboh4IzzmsIpWs134jVPqD/c74bZHdY69UKKSn/+KfVhxLgUlToemayLMYQOqfEC61bh
-cbhwaqoGUzIyZRFHPmau5juaWqwRn3mpWmoEA5nhzS5gog/5jbcFQqOZvmBasZtwYlG93k5GEiyw
-buHhMWLjDarEGpMGB2LFs5nIJkhp/nUmZneFaRth++lieJtHepIvKgx6PJqIlD9X2j6pG1i9x3pZ
-5bHuCPFiirGHeO7McvoXkz786GaKVzC9DSpnOxJdc4xm6NSVq7lNEnKdVlnpu9BNYoKX2Iq3wvgh
-gGEUM66kK6j4NiyoneuPLSwaCWDxczgaolEWpiMyDVDb7dNuLAbriL8ig8mmeju31oNvQdpnvEPC
-1vAXbWacGRVrGt/uXN/gU0CDDwgooKRrHfTBb1/s9lYZ8ZqOBU0yLvpuP6+K9hLFsvIjeNhBi0KL
-MlOuWRn3FRwx5oHXjl0YImUx0+gLzjGchrgzca026ETmYJzPD+IpuKzNi8AFn048Thd63OdD86M6
-84zE8yQm0VqXdbbgvub2pKVnS76icBGdeTHHXTKspUmr4NYo/furFLKiMdQzFjHJNcdAnMhltBJK
-0/IKX3DVFqvPJ2dLE7bDBkH0l/PJ29074+F0CsGYOxsb7U3myTUncYfXqnLLfa6sJybX4g+hmcjO
-kMRBfA1JellfRRKJcyRpxdS4rIl6FdmQCWjo/o9Qz7yKffoP4JHjOvABcRn4CZIT2RH4jnxmfpVG
-qgLaAvQBNfuO6X0/Ux02nb4FKx3vgP+XnkX0QW9pLy/NsXgdN24dD3LxO2Nwil7Zlc1dqtP3d7/h
-kzp1/+7hGBuY4pk0XD/0Ao/oTe/XGrfyM773aB7iUhgkpy+dwAMalxMP0DrBcsVw/6p25+/hobP9
-GBknrWExDhLJ1bwt1NcCNblaFbMKCyvmX0PeRaQ=
-""")
-
-##file distutils.cfg
-DISTUTILS_CFG = convert("""
-eJxNj00KwkAMhfc9xYNuxe4Ft57AjYiUtDO1wXSmNJnK3N5pdSEEAu8nH6lxHVlRhtDHMPATA4uH
-xJ4EFmGbvfJiicSHFRzUSISMY6hq3GLCRLnIvSTnEefN0FIjw5tF0Hkk9Q5dRunBsVoyFi24aaLg
-9FDOlL0FPGluf4QjcInLlxd6f6rqkgPu/5nHLg0cXCscXoozRrP51DRT3j9QNl99AP53T2Q=
-""")
-
-##file activate_this.py
-ACTIVATE_THIS = convert("""
-eJyNU01v2zAMvetXEB4K21jnDOstQA4dMGCHbeihlyEIDMWmE62yJEiKE//7kXKdpEWLzYBt8evx
-kRSzLPs6wiEoswM8YdMpjUXcq1Dz6RZa1cSiTkJdr86GsoTRHuCotBayiWqQEYGtMCgfD1KjGYBe
-5a3p0cRKiEe2NtLAFikftnDco0ko/SFEVgEZ8aRCZDIPY9xbA8pE9M4jfW/B2CjiHq9zbJVZuOQq
-siwTIvpxKYCembPAU4Muwi/Z4zfvrZ/MXipKeB8C+qisSZYiWfjJfs+0/MFMdWn1hJcO5U7G/SLa
-xVx8zU6VG/PXLXvfsyyzUqjeWR8hjGE+2iCE1W1tQ82hsCJN9dzKaoexyB/uH79TnjwvxcW0ntSb
-yZ8jq1Z5Q1UXsyy3gf9nbjTEj7NzQMfCJa/YSmrQ+2D/BqfiOi6sclrGzvoeVivIj8rcfcmnIQRF
-7XCyeZI7DFe5/lhlCs5PRf5QW66VXT/NrlQ46oD/D6InkOmi3IQcbhKxAX2g4a+Xd5s3UtCtG2py
-m8eg6WYWqR6SL5OjKMGfSrYt/6kxxQtOpeAgj1LXBNmpE2ElmCSIy5H0zFd8gJ924HWijWhb2hRC
-6wNEm1QdDZtuSZcEprIUBo/XRNcbQe1OUbQ/r3hPTaPJJDNtFLu8KHV5XoNr3Eo6h6YtOKw8e8yw
-VF5PnJ+ts3a9/Mz38RpG/AUSzYUW
-""")
-
-##file python-config
-PYTHON_CONFIG = convert("""
-eJyNVV1P2zAUfc+v8ODBiSABxlulTipbO6p1LWqBgVhlhcZpPYUkctzSivHfd6+dpGloGH2Ja/ue
-e+65Hz78xNhtf3x90xmw7vCWsRPGLvpDNuz87MKfdKMWSWxZ4ilNpCLZJiuWc66SVFUOZkkcirll
-rfxIBAzOMtImDzSVPBRrekwoX/OZu/0r4lm0DHiG60g86u8sjPw5rCyy86NRkB8QuuBRSqfAKESn
-3orLTCQxE3GYkC9tYp8fk89OSwNsmXgizrhUtnumeSgeo5GbLUMk49Rv+2nK48Cm/qMwfp333J2/
-dVcAGE0CIQHBsgIeEr4Wij0LtWDLzJ9ze5YEvH2WI6CHTAVcSu9ZCsXtgxu81CIvp6/k4eXsdfo7
-PvDCRD75yi41QitfzlcPp1OI7i/1/iQitqnr0iMgQ+A6wa+IKwwdxyk9IiXNAzgquTFU8NIxAVjM
-osm1Zz526e+shQ4hKRVci69nPC3Kw4NQEmkQ65E7OodxorSvxjvpBjQHDmWFIQ1mlmzlS5vedseT
-/mgIEsMJ7Lxz2bLAF9M5xeLEhdbHxpWOw0GdkJApMVBRF1y+a0z3c9WZPAXGFcFrJgCIB+024uad
-0CrzmEoRa3Ub4swNIHPGf7QDV+2uj2OiFWsChgCwjKqN6rp5izpbH6Wc1O1TclQTP/XVwi6anTr1
-1sbubjZLI1+VptPSdCfwnFBrB1jvebrTA9uUhU2/9gad7xPqeFkaQcnnLbCViZK8d7R1kxzFrIJV
-8EaLYmKYpvGVkig+3C5HCXbM1jGCGekiM2pRCVPyRyXYdPf6kcbWEQ36F5V4Gq9N7icNNw+JHwRE
-LTgxRXACpvnQv/PuT0xCCAywY/K4hE6Now2qDwaSE5FB+1agsoUveYDepS83qFcF1NufvULD3fTl
-g6Hgf7WBt6lzMeiyyWVn3P1WVbwaczHmTzE9A5SyItTVgFYyvs/L/fXlaNgbw8v3azT+0eikVlWD
-/vBHbzQumP23uBCjsYdrL9OWARwxs/nuLOzeXbPJTa/Xv6sUmQir5pC1YRLz3eA+CD8Z0XpcW8v9
-MZWF36ryyXXf3yBIz6nzqz8Muyz0m5Qj7OexfYo/Ph3LqvkHUg7AuA==
-""")
-
-MH_MAGIC = 0xfeedface
-MH_CIGAM = 0xcefaedfe
-MH_MAGIC_64 = 0xfeedfacf
-MH_CIGAM_64 = 0xcffaedfe
-FAT_MAGIC = 0xcafebabe
-BIG_ENDIAN = '>'
-LITTLE_ENDIAN = '<'
-LC_LOAD_DYLIB = 0xc
-maxint = majver == 3 and getattr(sys, 'maxsize') or getattr(sys, 'maxint')
-
-
-class fileview(object):
- """
- A proxy for file-like objects that exposes a given view of a file.
- Modified from macholib.
- """
-
- def __init__(self, fileobj, start=0, size=maxint):
- if isinstance(fileobj, fileview):
- self._fileobj = fileobj._fileobj
- else:
- self._fileobj = fileobj
- self._start = start
- self._end = start + size
- self._pos = 0
-
- def __repr__(self):
- return '' % (
- self._start, self._end, self._fileobj)
-
- def tell(self):
- return self._pos
-
- def _checkwindow(self, seekto, op):
- if not (self._start <= seekto <= self._end):
- raise IOError("%s to offset %d is outside window [%d, %d]" % (
- op, seekto, self._start, self._end))
-
- def seek(self, offset, whence=0):
- seekto = offset
- if whence == os.SEEK_SET:
- seekto += self._start
- elif whence == os.SEEK_CUR:
- seekto += self._start + self._pos
- elif whence == os.SEEK_END:
- seekto += self._end
- else:
- raise IOError("Invalid whence argument to seek: %r" % (whence,))
- self._checkwindow(seekto, 'seek')
- self._fileobj.seek(seekto)
- self._pos = seekto - self._start
-
- def write(self, bytes):
- here = self._start + self._pos
- self._checkwindow(here, 'write')
- self._checkwindow(here + len(bytes), 'write')
- self._fileobj.seek(here, os.SEEK_SET)
- self._fileobj.write(bytes)
- self._pos += len(bytes)
-
- def read(self, size=maxint):
- assert size >= 0
- here = self._start + self._pos
- self._checkwindow(here, 'read')
- size = min(size, self._end - here)
- self._fileobj.seek(here, os.SEEK_SET)
- bytes = self._fileobj.read(size)
- self._pos += len(bytes)
- return bytes
-
-
-def read_data(file, endian, num=1):
- """
- Read a given number of 32-bits unsigned integers from the given file
- with the given endianness.
- """
- res = struct.unpack(endian + 'L' * num, file.read(num * 4))
- if len(res) == 1:
- return res[0]
- return res
-
-
-def mach_o_change(path, what, value):
- """
- Replace a given name (what) in any LC_LOAD_DYLIB command found in
- the given binary with a new name (value), provided it's shorter.
- """
-
- def do_macho(file, bits, endian):
- # Read Mach-O header (the magic number is assumed read by the caller)
- cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags = read_data(file, endian, 6)
- # 64-bits header has one more field.
- if bits == 64:
- read_data(file, endian)
- # The header is followed by ncmds commands
- for n in range(ncmds):
- where = file.tell()
- # Read command header
- cmd, cmdsize = read_data(file, endian, 2)
- if cmd == LC_LOAD_DYLIB:
- # The first data field in LC_LOAD_DYLIB commands is the
- # offset of the name, starting from the beginning of the
- # command.
- name_offset = read_data(file, endian)
- file.seek(where + name_offset, os.SEEK_SET)
- # Read the NUL terminated string
- load = file.read(cmdsize - name_offset).decode()
- load = load[:load.index('\0')]
- # If the string is what is being replaced, overwrite it.
- if load == what:
- file.seek(where + name_offset, os.SEEK_SET)
- file.write(value.encode() + '\0'.encode())
- # Seek to the next command
- file.seek(where + cmdsize, os.SEEK_SET)
-
- def do_file(file, offset=0, size=maxint):
- file = fileview(file, offset, size)
- # Read magic number
- magic = read_data(file, BIG_ENDIAN)
- if magic == FAT_MAGIC:
- # Fat binaries contain nfat_arch Mach-O binaries
- nfat_arch = read_data(file, BIG_ENDIAN)
- for n in range(nfat_arch):
- # Read arch header
- cputype, cpusubtype, offset, size, align = read_data(file, BIG_ENDIAN, 5)
- do_file(file, offset, size)
- elif magic == MH_MAGIC:
- do_macho(file, 32, BIG_ENDIAN)
- elif magic == MH_CIGAM:
- do_macho(file, 32, LITTLE_ENDIAN)
- elif magic == MH_MAGIC_64:
- do_macho(file, 64, BIG_ENDIAN)
- elif magic == MH_CIGAM_64:
- do_macho(file, 64, LITTLE_ENDIAN)
-
- assert(len(what) >= len(value))
- do_file(open(path, 'r+b'))
-
-
-if __name__ == '__main__':
- main()
-
-# TODO:
-# Copy python.exe.manifest
-# Monkeypatch distutils.sysconfig
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate.bat b/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate.bat
deleted file mode 100644
index 529b9733c..000000000
--- a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate.bat
+++ /dev/null
@@ -1,30 +0,0 @@
-@echo off
-set "VIRTUAL_ENV=__VIRTUAL_ENV__"
-
-if defined _OLD_VIRTUAL_PROMPT (
- set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
-) else (
- if not defined PROMPT (
- set "PROMPT=$P$G"
- )
- set "_OLD_VIRTUAL_PROMPT=%PROMPT%"
-)
-set "PROMPT=__VIRTUAL_WINPROMPT__ %PROMPT%"
-
-REM Don't use () to avoid problems with them in %PATH%
-if defined _OLD_VIRTUAL_PYTHONHOME goto ENDIFVHOME
- set "_OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%"
-:ENDIFVHOME
-
-set PYTHONHOME=
-
-REM if defined _OLD_VIRTUAL_PATH (
-if not defined _OLD_VIRTUAL_PATH goto ENDIFVPATH1
- set "PATH=%_OLD_VIRTUAL_PATH%"
-:ENDIFVPATH1
-REM ) else (
-if defined _OLD_VIRTUAL_PATH goto ENDIFVPATH2
- set "_OLD_VIRTUAL_PATH=%PATH%"
-:ENDIFVPATH2
-
-set "PATH=%VIRTUAL_ENV%\__BIN_NAME__;%PATH%"
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate.csh b/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate.csh
deleted file mode 100644
index 864865b17..000000000
--- a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate.csh
+++ /dev/null
@@ -1,36 +0,0 @@
-# This file must be used with "source bin/activate.csh" *from csh*.
-# You cannot run it directly.
-# Created by Davide Di Blasi .
-
-alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; test "\!:*" != "nondestructive" && unalias deactivate && unalias pydoc'
-
-# Unset irrelevant variables.
-deactivate nondestructive
-
-setenv VIRTUAL_ENV "__VIRTUAL_ENV__"
-
-set _OLD_VIRTUAL_PATH="$PATH"
-setenv PATH "$VIRTUAL_ENV/__BIN_NAME__:$PATH"
-
-
-
-if ("__VIRTUAL_PROMPT__" != "") then
- set env_name = "__VIRTUAL_PROMPT__"
-else
- set env_name = `basename "$VIRTUAL_ENV"`
-endif
-
-# Could be in a non-interactive environment,
-# in which case, $prompt is undefined and we wouldn't
-# care about the prompt anyway.
-if ( $?prompt ) then
- set _OLD_VIRTUAL_PROMPT="$prompt"
- set prompt = "[$env_name] $prompt"
-endif
-
-unset env_name
-
-alias pydoc python -m pydoc
-
-rehash
-
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate.fish b/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate.fish
deleted file mode 100644
index f3d1797a3..000000000
--- a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate.fish
+++ /dev/null
@@ -1,76 +0,0 @@
-# This file must be used using `. bin/activate.fish` *within a running fish ( http://fishshell.com ) session*.
-# Do not run it directly.
-
-function deactivate -d 'Exit virtualenv mode and return to the normal environment.'
- # reset old environment variables
- if test -n "$_OLD_VIRTUAL_PATH"
- set -gx PATH $_OLD_VIRTUAL_PATH
- set -e _OLD_VIRTUAL_PATH
- end
-
- if test -n "$_OLD_VIRTUAL_PYTHONHOME"
- set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
- set -e _OLD_VIRTUAL_PYTHONHOME
- end
-
- if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
- # Set an empty local `$fish_function_path` to allow the removal of `fish_prompt` using `functions -e`.
- set -l fish_function_path
-
- # Erase virtualenv's `fish_prompt` and restore the original.
- functions -e fish_prompt
- functions -c _old_fish_prompt fish_prompt
- functions -e _old_fish_prompt
- set -e _OLD_FISH_PROMPT_OVERRIDE
- end
-
- set -e VIRTUAL_ENV
-
- if test "$argv[1]" != 'nondestructive'
- # Self-destruct!
- functions -e pydoc
- functions -e deactivate
- end
-end
-
-# Unset irrelevant variables.
-deactivate nondestructive
-
-set -gx VIRTUAL_ENV "__VIRTUAL_ENV__"
-
-set -gx _OLD_VIRTUAL_PATH $PATH
-set -gx PATH "$VIRTUAL_ENV/__BIN_NAME__" $PATH
-
-# Unset `$PYTHONHOME` if set.
-if set -q PYTHONHOME
- set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
- set -e PYTHONHOME
-end
-
-function pydoc
- python -m pydoc $argv
-end
-
-if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
- # Copy the current `fish_prompt` function as `_old_fish_prompt`.
- functions -c fish_prompt _old_fish_prompt
-
- function fish_prompt
- # Save the current $status, for fish_prompts that display it.
- set -l old_status $status
-
- # Prompt override provided?
- # If not, just prepend the environment name.
- if test -n "__VIRTUAL_PROMPT__"
- printf '%s%s' "__VIRTUAL_PROMPT__" (set_color normal)
- else
- printf '%s(%s%s%s) ' (set_color normal) (set_color -o white) (basename "$VIRTUAL_ENV") (set_color normal)
- end
-
- # Restore the original $status
- echo "exit $old_status" | source
- _old_fish_prompt
- end
-
- set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
-end
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate.ps1 b/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate.ps1
deleted file mode 100644
index 0f4adf19f..000000000
--- a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-# This file must be dot sourced from PoSh; you cannot run it
-# directly. Do this: . ./activate.ps1
-
-# FIXME: clean up unused vars.
-$script:THIS_PATH = $myinvocation.mycommand.path
-$script:BASE_DIR = split-path (resolve-path "$THIS_PATH/..") -Parent
-$script:DIR_NAME = split-path $BASE_DIR -Leaf
-
-function global:deactivate ( [switch] $NonDestructive ){
-
- if ( test-path variable:_OLD_VIRTUAL_PATH ) {
- $env:PATH = $variable:_OLD_VIRTUAL_PATH
- remove-variable "_OLD_VIRTUAL_PATH" -scope global
- }
-
- if ( test-path function:_old_virtual_prompt ) {
- $function:prompt = $function:_old_virtual_prompt
- remove-item function:\_old_virtual_prompt
- }
-
- if ($env:VIRTUAL_ENV) {
- $old_env = split-path $env:VIRTUAL_ENV -leaf
- remove-item env:VIRTUAL_ENV -erroraction silentlycontinue
- }
-
- if ( !$NonDestructive ) {
- # Self destruct!
- remove-item function:deactivate
- }
-}
-
-# unset irrelevant variables
-deactivate -nondestructive
-
-$VIRTUAL_ENV = $BASE_DIR
-$env:VIRTUAL_ENV = $VIRTUAL_ENV
-
-$global:_OLD_VIRTUAL_PATH = $env:PATH
-$env:PATH = "$env:VIRTUAL_ENV/Scripts;" + $env:PATH
-if (! $env:VIRTUAL_ENV_DISABLE_PROMPT) {
- function global:_old_virtual_prompt { "" }
- $function:_old_virtual_prompt = $function:prompt
- function global:prompt {
- # Add a prefix to the current prompt, but don't discard it.
- write-host "($(split-path $env:VIRTUAL_ENV -leaf)) " -nonewline
- & $function:_old_virtual_prompt
- }
-}
-
-# SIG # Begin signature block
-# MIISeAYJKoZIhvcNAQcCoIISaTCCEmUCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
-# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
-# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUS5reBwSg3zOUwhXf2jPChZzf
-# yPmggg6tMIIGcDCCBFigAwIBAgIBJDANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG
-# EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp
-# Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy
-# dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ2WhcNMTcxMDI0MjIw
-# MTQ2WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp
-# BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV
-# BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0
-# IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyiOLIjUemqAbPJ1J
-# 0D8MlzgWKbr4fYlbRVjvhHDtfhFN6RQxq0PjTQxRgWzwFQNKJCdU5ftKoM5N4YSj
-# Id6ZNavcSa6/McVnhDAQm+8H3HWoD030NVOxbjgD/Ih3HaV3/z9159nnvyxQEckR
-# ZfpJB2Kfk6aHqW3JnSvRe+XVZSufDVCe/vtxGSEwKCaNrsLc9pboUoYIC3oyzWoU
-# TZ65+c0H4paR8c8eK/mC914mBo6N0dQ512/bkSdaeY9YaQpGtW/h/W/FkbQRT3sC
-# pttLVlIjnkuY4r9+zvqhToPjxcfDYEf+XD8VGkAqle8Aa8hQ+M1qGdQjAye8OzbV
-# uUOw7wIDAQABo4IB6TCCAeUwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC
-# AQYwHQYDVR0OBBYEFNBOD0CZbLhLGW87KLjg44gHNKq3MB8GA1UdIwQYMBaAFE4L
-# 7xqkQFulF2mHMMo0aEPQQa7yMD0GCCsGAQUFBwEBBDEwLzAtBggrBgEFBQcwAoYh
-# aHR0cDovL3d3dy5zdGFydHNzbC5jb20vc2ZzY2EuY3J0MFsGA1UdHwRUMFIwJ6Al
-# oCOGIWh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL3Nmc2NhLmNybDAnoCWgI4YhaHR0
-# cDovL2NybC5zdGFydHNzbC5jb20vc2ZzY2EuY3JsMIGABgNVHSAEeTB3MHUGCysG
-# AQQBgbU3AQIBMGYwLgYIKwYBBQUHAgEWImh0dHA6Ly93d3cuc3RhcnRzc2wuY29t
-# L3BvbGljeS5wZGYwNAYIKwYBBQUHAgEWKGh0dHA6Ly93d3cuc3RhcnRzc2wuY29t
-# L2ludGVybWVkaWF0ZS5wZGYwEQYJYIZIAYb4QgEBBAQDAgABMFAGCWCGSAGG+EIB
-# DQRDFkFTdGFydENvbSBDbGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRlIE9iamVj
-# dCBTaWduaW5nIENlcnRpZmljYXRlczANBgkqhkiG9w0BAQUFAAOCAgEAcnMLA3Va
-# N4OIE9l4QT5OEtZy5PByBit3oHiqQpgVEQo7DHRsjXD5H/IyTivpMikaaeRxIv95
-# baRd4hoUcMwDj4JIjC3WA9FoNFV31SMljEZa66G8RQECdMSSufgfDYu1XQ+cUKxh
-# D3EtLGGcFGjjML7EQv2Iol741rEsycXwIXcryxeiMbU2TPi7X3elbwQMc4JFlJ4B
-# y9FhBzuZB1DV2sN2irGVbC3G/1+S2doPDjL1CaElwRa/T0qkq2vvPxUgryAoCppU
-# FKViw5yoGYC+z1GaesWWiP1eFKAL0wI7IgSvLzU3y1Vp7vsYaxOVBqZtebFTWRHt
-# XjCsFrrQBngt0d33QbQRI5mwgzEp7XJ9xu5d6RVWM4TPRUsd+DDZpBHm9mszvi9g
-# VFb2ZG7qRRXCSqys4+u/NLBPbXi/m/lU00cODQTlC/euwjk9HQtRrXQ/zqsBJS6U
-# J+eLGw1qOfj+HVBl/ZQpfoLk7IoWlRQvRL1s7oirEaqPZUIWY/grXq9r6jDKAp3L
-# ZdKQpPOnnogtqlU4f7/kLjEJhrrc98mrOWmVMK/BuFRAfQ5oDUMnVmCzAzLMjKfG
-# cVW/iMew41yfhgKbwpfzm3LBr1Zv+pEBgcgW6onRLSAn3XHM0eNtz+AkxH6rRf6B
-# 2mYhLEEGLapH8R1AMAo4BbVFOZR5kXcMCwowggg1MIIHHaADAgECAgIEuDANBgkq
-# hkiG9w0BAQUFADCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0
-# ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcx
-# ODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUg
-# T2JqZWN0IENBMB4XDTExMTIwMzE1MzQxOVoXDTEzMTIwMzE0NTgwN1owgYwxIDAe
-# BgNVBA0TFzU4MTc5Ni1HaDd4Zkp4a3hRU0lPNEUwMQswCQYDVQQGEwJERTEPMA0G
-# A1UECBMGQmVybGluMQ8wDQYDVQQHEwZCZXJsaW4xFjAUBgNVBAMTDUphbm5pcyBM
-# ZWlkZWwxITAfBgkqhkiG9w0BCQEWEmphbm5pc0BsZWlkZWwuaW5mbzCCAiIwDQYJ
-# KoZIhvcNAQEBBQADggIPADCCAgoCggIBAMcPeABYdN7nPq/AkZ/EkyUBGx/l2Yui
-# Lfm8ZdLG0ulMb/kQL3fRY7sUjYPyn9S6PhqqlFnNoGHJvbbReCdUC9SIQYmOEjEA
-# raHfb7MZU10NjO4U2DdGucj2zuO5tYxKizizOJF0e4yRQZVxpUGdvkW/+GLjCNK5
-# L7mIv3Z1dagxDKHYZT74HXiS4VFUwHF1k36CwfM2vsetdm46bdgSwV+BCMmZICYT
-# IJAS9UQHD7kP4rik3bFWjUx08NtYYFAVOd/HwBnemUmJe4j3IhZHr0k1+eDG8hDH
-# KVvPgLJIoEjC4iMFk5GWsg5z2ngk0LLu3JZMtckHsnnmBPHQK8a3opUNd8hdMNJx
-# gOwKjQt2JZSGUdIEFCKVDqj0FmdnDMPfwy+FNRtpBMl1sz78dUFhSrnM0D8NXrqa
-# 4rG+2FoOXlmm1rb6AFtpjAKksHRpYcPk2DPGWp/1sWB+dUQkS3gOmwFzyqeTuXpT
-# 0juqd3iAxOGx1VRFQ1VHLLf3AzV4wljBau26I+tu7iXxesVucSdsdQu293jwc2kN
-# xK2JyHCoZH+RyytrwS0qw8t7rMOukU9gwP8mn3X6mgWlVUODMcHTULjSiCEtvyZ/
-# aafcwjUbt4ReEcnmuZtWIha86MTCX7U7e+cnpWG4sIHPnvVTaz9rm8RyBkIxtFCB
-# nQ3FnoQgyxeJAgMBAAGjggOdMIIDmTAJBgNVHRMEAjAAMA4GA1UdDwEB/wQEAwIH
-# gDAuBgNVHSUBAf8EJDAiBggrBgEFBQcDAwYKKwYBBAGCNwIBFQYKKwYBBAGCNwoD
-# DTAdBgNVHQ4EFgQUWyCgrIWo8Ifvvm1/YTQIeMU9nc8wHwYDVR0jBBgwFoAU0E4P
-# QJlsuEsZbzsouODjiAc0qrcwggIhBgNVHSAEggIYMIICFDCCAhAGCysGAQQBgbU3
-# AQICMIIB/zAuBggrBgEFBQcCARYiaHR0cDovL3d3dy5zdGFydHNzbC5jb20vcG9s
-# aWN5LnBkZjA0BggrBgEFBQcCARYoaHR0cDovL3d3dy5zdGFydHNzbC5jb20vaW50
-# ZXJtZWRpYXRlLnBkZjCB9wYIKwYBBQUHAgIwgeowJxYgU3RhcnRDb20gQ2VydGlm
-# aWNhdGlvbiBBdXRob3JpdHkwAwIBARqBvlRoaXMgY2VydGlmaWNhdGUgd2FzIGlz
-# c3VlZCBhY2NvcmRpbmcgdG8gdGhlIENsYXNzIDIgVmFsaWRhdGlvbiByZXF1aXJl
-# bWVudHMgb2YgdGhlIFN0YXJ0Q29tIENBIHBvbGljeSwgcmVsaWFuY2Ugb25seSBm
-# b3IgdGhlIGludGVuZGVkIHB1cnBvc2UgaW4gY29tcGxpYW5jZSBvZiB0aGUgcmVs
-# eWluZyBwYXJ0eSBvYmxpZ2F0aW9ucy4wgZwGCCsGAQUFBwICMIGPMCcWIFN0YXJ0
-# Q29tIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MAMCAQIaZExpYWJpbGl0eSBhbmQg
-# d2FycmFudGllcyBhcmUgbGltaXRlZCEgU2VlIHNlY3Rpb24gIkxlZ2FsIGFuZCBM
-# aW1pdGF0aW9ucyIgb2YgdGhlIFN0YXJ0Q29tIENBIHBvbGljeS4wNgYDVR0fBC8w
-# LTAroCmgJ4YlaHR0cDovL2NybC5zdGFydHNzbC5jb20vY3J0YzItY3JsLmNybDCB
-# iQYIKwYBBQUHAQEEfTB7MDcGCCsGAQUFBzABhitodHRwOi8vb2NzcC5zdGFydHNz
-# bC5jb20vc3ViL2NsYXNzMi9jb2RlL2NhMEAGCCsGAQUFBzAChjRodHRwOi8vYWlh
-# LnN0YXJ0c3NsLmNvbS9jZXJ0cy9zdWIuY2xhc3MyLmNvZGUuY2EuY3J0MCMGA1Ud
-# EgQcMBqGGGh0dHA6Ly93d3cuc3RhcnRzc2wuY29tLzANBgkqhkiG9w0BAQUFAAOC
-# AQEAhrzEV6zwoEtKjnFRhCsjwiPykVpo5Eiye77Ve801rQDiRKgSCCiW6g3HqedL
-# OtaSs65Sj2pm3Viea4KR0TECLcbCTgsdaHqw2x1yXwWBQWZEaV6EB05lIwfr94P1
-# SFpV43zkuc+bbmA3+CRK45LOcCNH5Tqq7VGTCAK5iM7tvHwFlbQRl+I6VEL2mjpF
-# NsuRjDOVrv/9qw/a22YJ9R7Y1D0vUSs3IqZx2KMUaYDP7H2mSRxJO2nADQZBtriF
-# gTyfD3lYV12MlIi5CQwe3QC6DrrfSMP33i5Wa/OFJiQ27WPxmScYVhiqozpImFT4
-# PU9goiBv9RKXdgTmZE1PN0NQ5jGCAzUwggMxAgEBMIGTMIGMMQswCQYDVQQGEwJJ
-# TDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0
-# YWwgQ2VydGlmaWNhdGUgU2lnbmluZzE4MDYGA1UEAxMvU3RhcnRDb20gQ2xhc3Mg
-# MiBQcmltYXJ5IEludGVybWVkaWF0ZSBPYmplY3QgQ0ECAgS4MAkGBSsOAwIaBQCg
-# eDAYBgorBgEEAYI3AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEE
-# AYI3AgEEMBwGCisGAQQBgjcCAQsxDjAMBgorBgEEAYI3AgEVMCMGCSqGSIb3DQEJ
-# BDEWBBRVGw0FDSiaIi38dWteRUAg/9Pr6DANBgkqhkiG9w0BAQEFAASCAgCInvOZ
-# FdaNFzbf6trmFDZKMojyx3UjKMCqNjHVBbuKY0qXwFC/ElYDV1ShJ2CBZbdurydO
-# OQ6cIQ0KREOCwmX/xB49IlLHHUxNhEkVv7HGU3EKAFf9IBt9Yr7jikiR9cjIsfHK
-# 4cjkoKJL7g28yEpLLkHt1eo37f1Ga9lDWEa5Zq3U5yX+IwXhrUBm1h8Xr033FhTR
-# VEpuSz6LHtbrL/zgJnCzJ2ahjtJoYevdcWiNXffosJHFaSfYDDbiNsPRDH/1avmb
-# 5j/7BhP8BcBaR6Fp8tFbNGIcWHHGcjqLMnTc4w13b7b4pDhypqElBa4+lCmwdvv9
-# GydYtRgPz8GHeoBoKj30YBlMzRIfFYaIFGIC4Ai3UEXkuH9TxYohVbGm/W0Kl4Lb
-# RJ1FwiVcLcTOJdgNId2vQvKc+jtNrjcg5SP9h2v/C4aTx8tyc6tE3TOPh2f9b8DL
-# S+SbVArJpuJqrPTxDDoO1QNjTgLcdVYeZDE+r/NjaGZ6cMSd8db3EaG3ijD/0bud
-# SItbm/OlNVbQOFRR76D+ZNgPcU5iNZ3bmvQQIg6aSB9MHUpIE/SeCkNl9YeVk1/1
-# GFULgNMRmIYP4KLvu9ylh5Gu3hvD5VNhH6+FlXANwFy07uXks5uF8mfZVxVCnodG
-# xkNCx+6PsrA5Z7WP4pXcmYnMn97npP/Q9EHJWw==
-# SIG # End signature block
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate.sh b/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate.sh
deleted file mode 100644
index ecf30a768..000000000
--- a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate.sh
+++ /dev/null
@@ -1,78 +0,0 @@
-# This file must be used with "source bin/activate" *from bash*
-# you cannot run it directly
-
-deactivate () {
- unset -f pydoc
-
- # reset old environment variables
- # ! [ -z ${VAR+_} ] returns true if VAR is declared at all
- if ! [ -z "${_OLD_VIRTUAL_PATH+_}" ] ; then
- PATH="$_OLD_VIRTUAL_PATH"
- export PATH
- unset _OLD_VIRTUAL_PATH
- fi
- if ! [ -z "${_OLD_VIRTUAL_PYTHONHOME+_}" ] ; then
- PYTHONHOME="$_OLD_VIRTUAL_PYTHONHOME"
- export PYTHONHOME
- unset _OLD_VIRTUAL_PYTHONHOME
- fi
-
- # This should detect bash and zsh, which have a hash command that must
- # be called to get it to forget past commands. Without forgetting
- # past commands the $PATH changes we made may not be respected
- if [ -n "${BASH-}" ] || [ -n "${ZSH_VERSION-}" ] ; then
- hash -r 2>/dev/null
- fi
-
- if ! [ -z "${_OLD_VIRTUAL_PS1+_}" ] ; then
- PS1="$_OLD_VIRTUAL_PS1"
- export PS1
- unset _OLD_VIRTUAL_PS1
- fi
-
- unset VIRTUAL_ENV
- if [ ! "${1-}" = "nondestructive" ] ; then
- # Self destruct!
- unset -f deactivate
- fi
-}
-
-# unset irrelevant variables
-deactivate nondestructive
-
-VIRTUAL_ENV="__VIRTUAL_ENV__"
-export VIRTUAL_ENV
-
-_OLD_VIRTUAL_PATH="$PATH"
-PATH="$VIRTUAL_ENV/__BIN_NAME__:$PATH"
-export PATH
-
-# unset PYTHONHOME if set
-if ! [ -z "${PYTHONHOME+_}" ] ; then
- _OLD_VIRTUAL_PYTHONHOME="$PYTHONHOME"
- unset PYTHONHOME
-fi
-
-if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then
- _OLD_VIRTUAL_PS1="$PS1"
- if [ "x__VIRTUAL_PROMPT__" != x ] ; then
- PS1="__VIRTUAL_PROMPT__$PS1"
- else
- PS1="(`basename \"$VIRTUAL_ENV\"`) $PS1"
- fi
- export PS1
-fi
-
-# Make sure to unalias pydoc if it's already there
-alias pydoc 2>/dev/null >/dev/null && unalias pydoc
-
-pydoc () {
- python -m pydoc "$@"
-}
-
-# This should detect bash and zsh, which have a hash command that must
-# be called to get it to forget past commands. Without forgetting
-# past commands the $PATH changes we made may not be respected
-if [ -n "${BASH-}" ] || [ -n "${ZSH_VERSION-}" ] ; then
- hash -r 2>/dev/null
-fi
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate_this.py b/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate_this.py
deleted file mode 100644
index f18193bf8..000000000
--- a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/activate_this.py
+++ /dev/null
@@ -1,34 +0,0 @@
-"""By using execfile(this_file, dict(__file__=this_file)) you will
-activate this virtualenv environment.
-
-This can be used when you must use an existing Python interpreter, not
-the virtualenv bin/python
-"""
-
-try:
- __file__
-except NameError:
- raise AssertionError(
- "You must run this like execfile('path/to/activate_this.py', dict(__file__='path/to/activate_this.py'))")
-import sys
-import os
-
-old_os_path = os.environ.get('PATH', '')
-os.environ['PATH'] = os.path.dirname(os.path.abspath(__file__)) + os.pathsep + old_os_path
-base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
-if sys.platform == 'win32':
- site_packages = os.path.join(base, 'Lib', 'site-packages')
-else:
- site_packages = os.path.join(base, 'lib', 'python%s' % sys.version[:3], 'site-packages')
-prev_sys_path = list(sys.path)
-import site
-site.addsitedir(site_packages)
-sys.real_prefix = sys.prefix
-sys.prefix = base
-# Move the added items to the front of the path:
-new_sys_path = []
-for item in list(sys.path):
- if item not in prev_sys_path:
- new_sys_path.append(item)
- sys.path.remove(item)
-sys.path[:0] = new_sys_path
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/deactivate.bat b/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/deactivate.bat
deleted file mode 100644
index 9228d3171..000000000
--- a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/deactivate.bat
+++ /dev/null
@@ -1,19 +0,0 @@
-@echo off
-
-set VIRTUAL_ENV=
-
-REM Don't use () to avoid problems with them in %PATH%
-if not defined _OLD_VIRTUAL_PROMPT goto ENDIFVPROMPT
- set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
- set _OLD_VIRTUAL_PROMPT=
-:ENDIFVPROMPT
-
-if not defined _OLD_VIRTUAL_PYTHONHOME goto ENDIFVHOME
- set "PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%"
- set _OLD_VIRTUAL_PYTHONHOME=
-:ENDIFVHOME
-
-if not defined _OLD_VIRTUAL_PATH goto ENDIFVPATH
- set "PATH=%_OLD_VIRTUAL_PATH%"
- set _OLD_VIRTUAL_PATH=
-:ENDIFVPATH
\ No newline at end of file
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/distutils-init.py b/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/distutils-init.py
deleted file mode 100644
index 29fc1da45..000000000
--- a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/distutils-init.py
+++ /dev/null
@@ -1,101 +0,0 @@
-import os
-import sys
-import warnings
-import imp
-import opcode # opcode is not a virtualenv module, so we can use it to find the stdlib
- # Important! To work on pypy, this must be a module that resides in the
- # lib-python/modified-x.y.z directory
-
-dirname = os.path.dirname
-
-distutils_path = os.path.join(os.path.dirname(opcode.__file__), 'distutils')
-if os.path.normpath(distutils_path) == os.path.dirname(os.path.normpath(__file__)):
- warnings.warn(
- "The virtualenv distutils package at %s appears to be in the same location as the system distutils?")
-else:
- __path__.insert(0, distutils_path)
- real_distutils = imp.load_module("_virtualenv_distutils", None, distutils_path, ('', '', imp.PKG_DIRECTORY))
- # Copy the relevant attributes
- try:
- __revision__ = real_distutils.__revision__
- except AttributeError:
- pass
- __version__ = real_distutils.__version__
-
-from distutils import dist, sysconfig
-
-try:
- basestring
-except NameError:
- basestring = str
-
-## patch build_ext (distutils doesn't know how to get the libs directory
-## path on windows - it hardcodes the paths around the patched sys.prefix)
-
-if sys.platform == 'win32':
- from distutils.command.build_ext import build_ext as old_build_ext
- class build_ext(old_build_ext):
- def finalize_options (self):
- if self.library_dirs is None:
- self.library_dirs = []
- elif isinstance(self.library_dirs, basestring):
- self.library_dirs = self.library_dirs.split(os.pathsep)
-
- self.library_dirs.insert(0, os.path.join(sys.real_prefix, "Libs"))
- old_build_ext.finalize_options(self)
-
- from distutils.command import build_ext as build_ext_module
- build_ext_module.build_ext = build_ext
-
-## distutils.dist patches:
-
-old_find_config_files = dist.Distribution.find_config_files
-def find_config_files(self):
- found = old_find_config_files(self)
- system_distutils = os.path.join(distutils_path, 'distutils.cfg')
- #if os.path.exists(system_distutils):
- # found.insert(0, system_distutils)
- # What to call the per-user config file
- if os.name == 'posix':
- user_filename = ".pydistutils.cfg"
- else:
- user_filename = "pydistutils.cfg"
- user_filename = os.path.join(sys.prefix, user_filename)
- if os.path.isfile(user_filename):
- for item in list(found):
- if item.endswith('pydistutils.cfg'):
- found.remove(item)
- found.append(user_filename)
- return found
-dist.Distribution.find_config_files = find_config_files
-
-## distutils.sysconfig patches:
-
-old_get_python_inc = sysconfig.get_python_inc
-def sysconfig_get_python_inc(plat_specific=0, prefix=None):
- if prefix is None:
- prefix = sys.real_prefix
- return old_get_python_inc(plat_specific, prefix)
-sysconfig_get_python_inc.__doc__ = old_get_python_inc.__doc__
-sysconfig.get_python_inc = sysconfig_get_python_inc
-
-old_get_python_lib = sysconfig.get_python_lib
-def sysconfig_get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
- if standard_lib and prefix is None:
- prefix = sys.real_prefix
- return old_get_python_lib(plat_specific, standard_lib, prefix)
-sysconfig_get_python_lib.__doc__ = old_get_python_lib.__doc__
-sysconfig.get_python_lib = sysconfig_get_python_lib
-
-old_get_config_vars = sysconfig.get_config_vars
-def sysconfig_get_config_vars(*args):
- real_vars = old_get_config_vars(*args)
- if sys.platform == 'win32':
- lib_dir = os.path.join(sys.real_prefix, "libs")
- if isinstance(real_vars, dict) and 'LIBDIR' not in real_vars:
- real_vars['LIBDIR'] = lib_dir # asked for all
- elif isinstance(real_vars, list) and 'LIBDIR' in args:
- real_vars = real_vars + [lib_dir] # asked for list
- return real_vars
-sysconfig_get_config_vars.__doc__ = old_get_config_vars.__doc__
-sysconfig.get_config_vars = sysconfig_get_config_vars
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/distutils.cfg b/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/distutils.cfg
deleted file mode 100644
index 1af230ec9..000000000
--- a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/distutils.cfg
+++ /dev/null
@@ -1,6 +0,0 @@
-# This is a config file local to this virtualenv installation
-# You may include options that will be used by all distutils commands,
-# and by easy_install. For instance:
-#
-# [easy_install]
-# find_links = http://mylocalsite
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/python-config b/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/python-config
deleted file mode 100644
index 5e7a7c901..000000000
--- a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/python-config
+++ /dev/null
@@ -1,78 +0,0 @@
-#!__VIRTUAL_ENV__/__BIN_NAME__/python
-
-import sys
-import getopt
-import sysconfig
-
-valid_opts = ['prefix', 'exec-prefix', 'includes', 'libs', 'cflags',
- 'ldflags', 'help']
-
-if sys.version_info >= (3, 2):
- valid_opts.insert(-1, 'extension-suffix')
- valid_opts.append('abiflags')
-if sys.version_info >= (3, 3):
- valid_opts.append('configdir')
-
-
-def exit_with_usage(code=1):
- sys.stderr.write("Usage: {0} [{1}]\n".format(
- sys.argv[0], '|'.join('--'+opt for opt in valid_opts)))
- sys.exit(code)
-
-try:
- opts, args = getopt.getopt(sys.argv[1:], '', valid_opts)
-except getopt.error:
- exit_with_usage()
-
-if not opts:
- exit_with_usage()
-
-pyver = sysconfig.get_config_var('VERSION')
-getvar = sysconfig.get_config_var
-
-opt_flags = [flag for (flag, val) in opts]
-
-if '--help' in opt_flags:
- exit_with_usage(code=0)
-
-for opt in opt_flags:
- if opt == '--prefix':
- print(sysconfig.get_config_var('prefix'))
-
- elif opt == '--exec-prefix':
- print(sysconfig.get_config_var('exec_prefix'))
-
- elif opt in ('--includes', '--cflags'):
- flags = ['-I' + sysconfig.get_path('include'),
- '-I' + sysconfig.get_path('platinclude')]
- if opt == '--cflags':
- flags.extend(getvar('CFLAGS').split())
- print(' '.join(flags))
-
- elif opt in ('--libs', '--ldflags'):
- abiflags = getattr(sys, 'abiflags', '')
- libs = ['-lpython' + pyver + abiflags]
- libs += getvar('LIBS').split()
- libs += getvar('SYSLIBS').split()
- # add the prefix/lib/pythonX.Y/config dir, but only if there is no
- # shared library in prefix/lib/.
- if opt == '--ldflags':
- if not getvar('Py_ENABLE_SHARED'):
- libs.insert(0, '-L' + getvar('LIBPL'))
- if not getvar('PYTHONFRAMEWORK'):
- libs.extend(getvar('LINKFORSHARED').split())
- print(' '.join(libs))
-
- elif opt == '--extension-suffix':
- ext_suffix = sysconfig.get_config_var('EXT_SUFFIX')
- if ext_suffix is None:
- ext_suffix = sysconfig.get_config_var('SO')
- print(ext_suffix)
-
- elif opt == '--abiflags':
- if not getattr(sys, 'abiflags', None):
- exit_with_usage()
- print(sys.abiflags)
-
- elif opt == '--configdir':
- print(sysconfig.get_config_var('LIBPL'))
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/site.py b/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/site.py
deleted file mode 100644
index 7969769c3..000000000
--- a/icestudio/install/virtualenv-14.0.1/virtualenv_embedded/site.py
+++ /dev/null
@@ -1,758 +0,0 @@
-"""Append module search paths for third-party packages to sys.path.
-
-****************************************************************
-* This module is automatically imported during initialization. *
-****************************************************************
-
-In earlier versions of Python (up to 1.5a3), scripts or modules that
-needed to use site-specific modules would place ``import site''
-somewhere near the top of their code. Because of the automatic
-import, this is no longer necessary (but code that does it still
-works).
-
-This will append site-specific paths to the module search path. On
-Unix, it starts with sys.prefix and sys.exec_prefix (if different) and
-appends lib/python/site-packages as well as lib/site-python.
-It also supports the Debian convention of
-lib/python/dist-packages. On other platforms (mainly Mac and
-Windows), it uses just sys.prefix (and sys.exec_prefix, if different,
-but this is unlikely). The resulting directories, if they exist, are
-appended to sys.path, and also inspected for path configuration files.
-
-FOR DEBIAN, this sys.path is augmented with directories in /usr/local.
-Local addons go into /usr/local/lib/python/site-packages
-(resp. /usr/local/lib/site-python), Debian addons install into
-/usr/{lib,share}/python/dist-packages.
-
-A path configuration file is a file whose name has the form
-.pth; its contents are additional directories (one per line)
-to be added to sys.path. Non-existing directories (or
-non-directories) are never added to sys.path; no directory is added to
-sys.path more than once. Blank lines and lines beginning with
-'#' are skipped. Lines starting with 'import' are executed.
-
-For example, suppose sys.prefix and sys.exec_prefix are set to
-/usr/local and there is a directory /usr/local/lib/python2.X/site-packages
-with three subdirectories, foo, bar and spam, and two path
-configuration files, foo.pth and bar.pth. Assume foo.pth contains the
-following:
-
- # foo package configuration
- foo
- bar
- bletch
-
-and bar.pth contains:
-
- # bar package configuration
- bar
-
-Then the following directories are added to sys.path, in this order:
-
- /usr/local/lib/python2.X/site-packages/bar
- /usr/local/lib/python2.X/site-packages/foo
-
-Note that bletch is omitted because it doesn't exist; bar precedes foo
-because bar.pth comes alphabetically before foo.pth; and spam is
-omitted because it is not mentioned in either path configuration file.
-
-After these path manipulations, an attempt is made to import a module
-named sitecustomize, which can perform arbitrary additional
-site-specific customizations. If this import fails with an
-ImportError exception, it is silently ignored.
-
-"""
-
-import sys
-import os
-try:
- import __builtin__ as builtins
-except ImportError:
- import builtins
-try:
- set
-except NameError:
- from sets import Set as set
-
-# Prefixes for site-packages; add additional prefixes like /usr/local here
-PREFIXES = [sys.prefix, sys.exec_prefix]
-# Enable per user site-packages directory
-# set it to False to disable the feature or True to force the feature
-ENABLE_USER_SITE = None
-# for distutils.commands.install
-USER_SITE = None
-USER_BASE = None
-
-_is_64bit = (getattr(sys, 'maxsize', None) or getattr(sys, 'maxint')) > 2**32
-_is_pypy = hasattr(sys, 'pypy_version_info')
-_is_jython = sys.platform[:4] == 'java'
-if _is_jython:
- ModuleType = type(os)
-
-def makepath(*paths):
- dir = os.path.join(*paths)
- if _is_jython and (dir == '__classpath__' or
- dir.startswith('__pyclasspath__')):
- return dir, dir
- dir = os.path.abspath(dir)
- return dir, os.path.normcase(dir)
-
-def abs__file__():
- """Set all module' __file__ attribute to an absolute path"""
- for m in sys.modules.values():
- if ((_is_jython and not isinstance(m, ModuleType)) or
- hasattr(m, '__loader__')):
- # only modules need the abspath in Jython. and don't mess
- # with a PEP 302-supplied __file__
- continue
- f = getattr(m, '__file__', None)
- if f is None:
- continue
- m.__file__ = os.path.abspath(f)
-
-def removeduppaths():
- """ Remove duplicate entries from sys.path along with making them
- absolute"""
- # This ensures that the initial path provided by the interpreter contains
- # only absolute pathnames, even if we're running from the build directory.
- L = []
- known_paths = set()
- for dir in sys.path:
- # Filter out duplicate paths (on case-insensitive file systems also
- # if they only differ in case); turn relative paths into absolute
- # paths.
- dir, dircase = makepath(dir)
- if not dircase in known_paths:
- L.append(dir)
- known_paths.add(dircase)
- sys.path[:] = L
- return known_paths
-
-# XXX This should not be part of site.py, since it is needed even when
-# using the -S option for Python. See http://www.python.org/sf/586680
-def addbuilddir():
- """Append ./build/lib. in case we're running in the build dir
- (especially for Guido :-)"""
- from distutils.util import get_platform
- s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
- if hasattr(sys, 'gettotalrefcount'):
- s += '-pydebug'
- s = os.path.join(os.path.dirname(sys.path[-1]), s)
- sys.path.append(s)
-
-def _init_pathinfo():
- """Return a set containing all existing directory entries from sys.path"""
- d = set()
- for dir in sys.path:
- try:
- if os.path.isdir(dir):
- dir, dircase = makepath(dir)
- d.add(dircase)
- except TypeError:
- continue
- return d
-
-def addpackage(sitedir, name, known_paths):
- """Add a new path to known_paths by combining sitedir and 'name' or execute
- sitedir if it starts with 'import'"""
- if known_paths is None:
- _init_pathinfo()
- reset = 1
- else:
- reset = 0
- fullname = os.path.join(sitedir, name)
- try:
- f = open(fullname, "rU")
- except IOError:
- return
- try:
- for line in f:
- if line.startswith("#"):
- continue
- if line.startswith("import"):
- exec(line)
- continue
- line = line.rstrip()
- dir, dircase = makepath(sitedir, line)
- if not dircase in known_paths and os.path.exists(dir):
- sys.path.append(dir)
- known_paths.add(dircase)
- finally:
- f.close()
- if reset:
- known_paths = None
- return known_paths
-
-def addsitedir(sitedir, known_paths=None):
- """Add 'sitedir' argument to sys.path if missing and handle .pth files in
- 'sitedir'"""
- if known_paths is None:
- known_paths = _init_pathinfo()
- reset = 1
- else:
- reset = 0
- sitedir, sitedircase = makepath(sitedir)
- if not sitedircase in known_paths:
- sys.path.append(sitedir) # Add path component
- try:
- names = os.listdir(sitedir)
- except os.error:
- return
- names.sort()
- for name in names:
- if name.endswith(os.extsep + "pth"):
- addpackage(sitedir, name, known_paths)
- if reset:
- known_paths = None
- return known_paths
-
-def addsitepackages(known_paths, sys_prefix=sys.prefix, exec_prefix=sys.exec_prefix):
- """Add site-packages (and possibly site-python) to sys.path"""
- prefixes = [os.path.join(sys_prefix, "local"), sys_prefix]
- if exec_prefix != sys_prefix:
- prefixes.append(os.path.join(exec_prefix, "local"))
-
- for prefix in prefixes:
- if prefix:
- if sys.platform in ('os2emx', 'riscos') or _is_jython:
- sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
- elif _is_pypy:
- sitedirs = [os.path.join(prefix, 'site-packages')]
- elif sys.platform == 'darwin' and prefix == sys_prefix:
-
- if prefix.startswith("/System/Library/Frameworks/"): # Apple's Python
-
- sitedirs = [os.path.join("/Library/Python", sys.version[:3], "site-packages"),
- os.path.join(prefix, "Extras", "lib", "python")]
-
- else: # any other Python distros on OSX work this way
- sitedirs = [os.path.join(prefix, "lib",
- "python" + sys.version[:3], "site-packages")]
-
- elif os.sep == '/':
- sitedirs = [os.path.join(prefix,
- "lib",
- "python" + sys.version[:3],
- "site-packages"),
- os.path.join(prefix, "lib", "site-python"),
- os.path.join(prefix, "python" + sys.version[:3], "lib-dynload")]
- lib64_dir = os.path.join(prefix, "lib64", "python" + sys.version[:3], "site-packages")
- if (os.path.exists(lib64_dir) and
- os.path.realpath(lib64_dir) not in [os.path.realpath(p) for p in sitedirs]):
- if _is_64bit:
- sitedirs.insert(0, lib64_dir)
- else:
- sitedirs.append(lib64_dir)
- try:
- # sys.getobjects only available in --with-pydebug build
- sys.getobjects
- sitedirs.insert(0, os.path.join(sitedirs[0], 'debug'))
- except AttributeError:
- pass
- # Debian-specific dist-packages directories:
- sitedirs.append(os.path.join(prefix, "local/lib",
- "python" + sys.version[:3],
- "dist-packages"))
- if sys.version[0] == '2':
- sitedirs.append(os.path.join(prefix, "lib",
- "python" + sys.version[:3],
- "dist-packages"))
- else:
- sitedirs.append(os.path.join(prefix, "lib",
- "python" + sys.version[0],
- "dist-packages"))
- sitedirs.append(os.path.join(prefix, "lib", "dist-python"))
- else:
- sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
- if sys.platform == 'darwin':
- # for framework builds *only* we add the standard Apple
- # locations. Currently only per-user, but /Library and
- # /Network/Library could be added too
- if 'Python.framework' in prefix:
- home = os.environ.get('HOME')
- if home:
- sitedirs.append(
- os.path.join(home,
- 'Library',
- 'Python',
- sys.version[:3],
- 'site-packages'))
- for sitedir in sitedirs:
- if os.path.isdir(sitedir):
- addsitedir(sitedir, known_paths)
- return None
-
-def check_enableusersite():
- """Check if user site directory is safe for inclusion
-
- The function tests for the command line flag (including environment var),
- process uid/gid equal to effective uid/gid.
-
- None: Disabled for security reasons
- False: Disabled by user (command line option)
- True: Safe and enabled
- """
- if hasattr(sys, 'flags') and getattr(sys.flags, 'no_user_site', False):
- return False
-
- if hasattr(os, "getuid") and hasattr(os, "geteuid"):
- # check process uid == effective uid
- if os.geteuid() != os.getuid():
- return None
- if hasattr(os, "getgid") and hasattr(os, "getegid"):
- # check process gid == effective gid
- if os.getegid() != os.getgid():
- return None
-
- return True
-
-def addusersitepackages(known_paths):
- """Add a per user site-package to sys.path
-
- Each user has its own python directory with site-packages in the
- home directory.
-
- USER_BASE is the root directory for all Python versions
-
- USER_SITE is the user specific site-packages directory
-
- USER_SITE/.. can be used for data.
- """
- global USER_BASE, USER_SITE, ENABLE_USER_SITE
- env_base = os.environ.get("PYTHONUSERBASE", None)
-
- def joinuser(*args):
- return os.path.expanduser(os.path.join(*args))
-
- #if sys.platform in ('os2emx', 'riscos'):
- # # Don't know what to put here
- # USER_BASE = ''
- # USER_SITE = ''
- if os.name == "nt":
- base = os.environ.get("APPDATA") or "~"
- if env_base:
- USER_BASE = env_base
- else:
- USER_BASE = joinuser(base, "Python")
- USER_SITE = os.path.join(USER_BASE,
- "Python" + sys.version[0] + sys.version[2],
- "site-packages")
- else:
- if env_base:
- USER_BASE = env_base
- else:
- USER_BASE = joinuser("~", ".local")
- USER_SITE = os.path.join(USER_BASE, "lib",
- "python" + sys.version[:3],
- "site-packages")
-
- if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
- addsitedir(USER_SITE, known_paths)
- if ENABLE_USER_SITE:
- for dist_libdir in ("lib", "local/lib"):
- user_site = os.path.join(USER_BASE, dist_libdir,
- "python" + sys.version[:3],
- "dist-packages")
- if os.path.isdir(user_site):
- addsitedir(user_site, known_paths)
- return known_paths
-
-
-
-def setBEGINLIBPATH():
- """The OS/2 EMX port has optional extension modules that do double duty
- as DLLs (and must use the .DLL file extension) for other extensions.
- The library search path needs to be amended so these will be found
- during module import. Use BEGINLIBPATH so that these are at the start
- of the library search path.
-
- """
- dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
- libpath = os.environ['BEGINLIBPATH'].split(';')
- if libpath[-1]:
- libpath.append(dllpath)
- else:
- libpath[-1] = dllpath
- os.environ['BEGINLIBPATH'] = ';'.join(libpath)
-
-
-def setquit():
- """Define new built-ins 'quit' and 'exit'.
- These are simply strings that display a hint on how to exit.
-
- """
- if os.sep == ':':
- eof = 'Cmd-Q'
- elif os.sep == '\\':
- eof = 'Ctrl-Z plus Return'
- else:
- eof = 'Ctrl-D (i.e. EOF)'
-
- class Quitter(object):
- def __init__(self, name):
- self.name = name
- def __repr__(self):
- return 'Use %s() or %s to exit' % (self.name, eof)
- def __call__(self, code=None):
- # Shells like IDLE catch the SystemExit, but listen when their
- # stdin wrapper is closed.
- try:
- sys.stdin.close()
- except:
- pass
- raise SystemExit(code)
- builtins.quit = Quitter('quit')
- builtins.exit = Quitter('exit')
-
-
-class _Printer(object):
- """interactive prompt objects for printing the license text, a list of
- contributors and the copyright notice."""
-
- MAXLINES = 23
-
- def __init__(self, name, data, files=(), dirs=()):
- self.__name = name
- self.__data = data
- self.__files = files
- self.__dirs = dirs
- self.__lines = None
-
- def __setup(self):
- if self.__lines:
- return
- data = None
- for dir in self.__dirs:
- for filename in self.__files:
- filename = os.path.join(dir, filename)
- try:
- fp = open(filename, "rU")
- data = fp.read()
- fp.close()
- break
- except IOError:
- pass
- if data:
- break
- if not data:
- data = self.__data
- self.__lines = data.split('\n')
- self.__linecnt = len(self.__lines)
-
- def __repr__(self):
- self.__setup()
- if len(self.__lines) <= self.MAXLINES:
- return "\n".join(self.__lines)
- else:
- return "Type %s() to see the full %s text" % ((self.__name,)*2)
-
- def __call__(self):
- self.__setup()
- prompt = 'Hit Return for more, or q (and Return) to quit: '
- lineno = 0
- while 1:
- try:
- for i in range(lineno, lineno + self.MAXLINES):
- print(self.__lines[i])
- except IndexError:
- break
- else:
- lineno += self.MAXLINES
- key = None
- while key is None:
- try:
- key = raw_input(prompt)
- except NameError:
- key = input(prompt)
- if key not in ('', 'q'):
- key = None
- if key == 'q':
- break
-
-def setcopyright():
- """Set 'copyright' and 'credits' in __builtin__"""
- builtins.copyright = _Printer("copyright", sys.copyright)
- if _is_jython:
- builtins.credits = _Printer(
- "credits",
- "Jython is maintained by the Jython developers (www.jython.org).")
- elif _is_pypy:
- builtins.credits = _Printer(
- "credits",
- "PyPy is maintained by the PyPy developers: http://pypy.org/")
- else:
- builtins.credits = _Printer("credits", """\
- Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
- for supporting Python development. See www.python.org for more information.""")
- here = os.path.dirname(os.__file__)
- builtins.license = _Printer(
- "license", "See http://www.python.org/%.3s/license.html" % sys.version,
- ["LICENSE.txt", "LICENSE"],
- [os.path.join(here, os.pardir), here, os.curdir])
-
-
-class _Helper(object):
- """Define the built-in 'help'.
- This is a wrapper around pydoc.help (with a twist).
-
- """
-
- def __repr__(self):
- return "Type help() for interactive help, " \
- "or help(object) for help about object."
- def __call__(self, *args, **kwds):
- import pydoc
- return pydoc.help(*args, **kwds)
-
-def sethelper():
- builtins.help = _Helper()
-
-def aliasmbcs():
- """On Windows, some default encodings are not provided by Python,
- while they are always available as "mbcs" in each locale. Make
- them usable by aliasing to "mbcs" in such a case."""
- if sys.platform == 'win32':
- import locale, codecs
- enc = locale.getdefaultlocale()[1]
- if enc.startswith('cp'): # "cp***" ?
- try:
- codecs.lookup(enc)
- except LookupError:
- import encodings
- encodings._cache[enc] = encodings._unknown
- encodings.aliases.aliases[enc] = 'mbcs'
-
-def setencoding():
- """Set the string encoding used by the Unicode implementation. The
- default is 'ascii', but if you're willing to experiment, you can
- change this."""
- encoding = "ascii" # Default value set by _PyUnicode_Init()
- if 0:
- # Enable to support locale aware default string encodings.
- import locale
- loc = locale.getdefaultlocale()
- if loc[1]:
- encoding = loc[1]
- if 0:
- # Enable to switch off string to Unicode coercion and implicit
- # Unicode to string conversion.
- encoding = "undefined"
- if encoding != "ascii":
- # On Non-Unicode builds this will raise an AttributeError...
- sys.setdefaultencoding(encoding) # Needs Python Unicode build !
-
-
-def execsitecustomize():
- """Run custom site specific code, if available."""
- try:
- import sitecustomize
- except ImportError:
- pass
-
-def virtual_install_main_packages():
- f = open(os.path.join(os.path.dirname(__file__), 'orig-prefix.txt'))
- sys.real_prefix = f.read().strip()
- f.close()
- pos = 2
- hardcoded_relative_dirs = []
- if sys.path[0] == '':
- pos += 1
- if _is_jython:
- paths = [os.path.join(sys.real_prefix, 'Lib')]
- elif _is_pypy:
- if sys.version_info > (3, 2):
- cpyver = '%d' % sys.version_info[0]
- elif sys.pypy_version_info >= (1, 5):
- cpyver = '%d.%d' % sys.version_info[:2]
- else:
- cpyver = '%d.%d.%d' % sys.version_info[:3]
- paths = [os.path.join(sys.real_prefix, 'lib_pypy'),
- os.path.join(sys.real_prefix, 'lib-python', cpyver)]
- if sys.pypy_version_info < (1, 9):
- paths.insert(1, os.path.join(sys.real_prefix,
- 'lib-python', 'modified-%s' % cpyver))
- hardcoded_relative_dirs = paths[:] # for the special 'darwin' case below
- #
- # This is hardcoded in the Python executable, but relative to sys.prefix:
- for path in paths[:]:
- plat_path = os.path.join(path, 'plat-%s' % sys.platform)
- if os.path.exists(plat_path):
- paths.append(plat_path)
- elif sys.platform == 'win32':
- paths = [os.path.join(sys.real_prefix, 'Lib'), os.path.join(sys.real_prefix, 'DLLs')]
- else:
- paths = [os.path.join(sys.real_prefix, 'lib', 'python'+sys.version[:3])]
- hardcoded_relative_dirs = paths[:] # for the special 'darwin' case below
- lib64_path = os.path.join(sys.real_prefix, 'lib64', 'python'+sys.version[:3])
- if os.path.exists(lib64_path):
- if _is_64bit:
- paths.insert(0, lib64_path)
- else:
- paths.append(lib64_path)
- # This is hardcoded in the Python executable, but relative to
- # sys.prefix. Debian change: we need to add the multiarch triplet
- # here, which is where the real stuff lives. As per PEP 421, in
- # Python 3.3+, this lives in sys.implementation, while in Python 2.7
- # it lives in sys.
- try:
- arch = getattr(sys, 'implementation', sys)._multiarch
- except AttributeError:
- # This is a non-multiarch aware Python. Fallback to the old way.
- arch = sys.platform
- plat_path = os.path.join(sys.real_prefix, 'lib',
- 'python'+sys.version[:3],
- 'plat-%s' % arch)
- if os.path.exists(plat_path):
- paths.append(plat_path)
- # This is hardcoded in the Python executable, but
- # relative to sys.prefix, so we have to fix up:
- for path in list(paths):
- tk_dir = os.path.join(path, 'lib-tk')
- if os.path.exists(tk_dir):
- paths.append(tk_dir)
-
- # These are hardcoded in the Apple's Python executable,
- # but relative to sys.prefix, so we have to fix them up:
- if sys.platform == 'darwin':
- hardcoded_paths = [os.path.join(relative_dir, module)
- for relative_dir in hardcoded_relative_dirs
- for module in ('plat-darwin', 'plat-mac', 'plat-mac/lib-scriptpackages')]
-
- for path in hardcoded_paths:
- if os.path.exists(path):
- paths.append(path)
-
- sys.path.extend(paths)
-
-def force_global_eggs_after_local_site_packages():
- """
- Force easy_installed eggs in the global environment to get placed
- in sys.path after all packages inside the virtualenv. This
- maintains the "least surprise" result that packages in the
- virtualenv always mask global packages, never the other way
- around.
-
- """
- egginsert = getattr(sys, '__egginsert', 0)
- for i, path in enumerate(sys.path):
- if i > egginsert and path.startswith(sys.prefix):
- egginsert = i
- sys.__egginsert = egginsert + 1
-
-def virtual_addsitepackages(known_paths):
- force_global_eggs_after_local_site_packages()
- return addsitepackages(known_paths, sys_prefix=sys.real_prefix)
-
-def fixclasspath():
- """Adjust the special classpath sys.path entries for Jython. These
- entries should follow the base virtualenv lib directories.
- """
- paths = []
- classpaths = []
- for path in sys.path:
- if path == '__classpath__' or path.startswith('__pyclasspath__'):
- classpaths.append(path)
- else:
- paths.append(path)
- sys.path = paths
- sys.path.extend(classpaths)
-
-def execusercustomize():
- """Run custom user specific code, if available."""
- try:
- import usercustomize
- except ImportError:
- pass
-
-
-def main():
- global ENABLE_USER_SITE
- virtual_install_main_packages()
- abs__file__()
- paths_in_sys = removeduppaths()
- if (os.name == "posix" and sys.path and
- os.path.basename(sys.path[-1]) == "Modules"):
- addbuilddir()
- if _is_jython:
- fixclasspath()
- GLOBAL_SITE_PACKAGES = not os.path.exists(os.path.join(os.path.dirname(__file__), 'no-global-site-packages.txt'))
- if not GLOBAL_SITE_PACKAGES:
- ENABLE_USER_SITE = False
- if ENABLE_USER_SITE is None:
- ENABLE_USER_SITE = check_enableusersite()
- paths_in_sys = addsitepackages(paths_in_sys)
- paths_in_sys = addusersitepackages(paths_in_sys)
- if GLOBAL_SITE_PACKAGES:
- paths_in_sys = virtual_addsitepackages(paths_in_sys)
- if sys.platform == 'os2emx':
- setBEGINLIBPATH()
- setquit()
- setcopyright()
- sethelper()
- aliasmbcs()
- setencoding()
- execsitecustomize()
- if ENABLE_USER_SITE:
- execusercustomize()
- # Remove sys.setdefaultencoding() so that users cannot change the
- # encoding after initialization. The test for presence is needed when
- # this module is run as a script, because this code is executed twice.
- if hasattr(sys, "setdefaultencoding"):
- del sys.setdefaultencoding
-
-main()
-
-def _script():
- help = """\
- %s [--user-base] [--user-site]
-
- Without arguments print some useful information
- With arguments print the value of USER_BASE and/or USER_SITE separated
- by '%s'.
-
- Exit codes with --user-base or --user-site:
- 0 - user site directory is enabled
- 1 - user site directory is disabled by user
- 2 - uses site directory is disabled by super user
- or for security reasons
- >2 - unknown error
- """
- args = sys.argv[1:]
- if not args:
- print("sys.path = [")
- for dir in sys.path:
- print(" %r," % (dir,))
- print("]")
- def exists(path):
- if os.path.isdir(path):
- return "exists"
- else:
- return "doesn't exist"
- print("USER_BASE: %r (%s)" % (USER_BASE, exists(USER_BASE)))
- print("USER_SITE: %r (%s)" % (USER_SITE, exists(USER_BASE)))
- print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
- sys.exit(0)
-
- buffer = []
- if '--user-base' in args:
- buffer.append(USER_BASE)
- if '--user-site' in args:
- buffer.append(USER_SITE)
-
- if buffer:
- print(os.pathsep.join(buffer))
- if ENABLE_USER_SITE:
- sys.exit(0)
- elif ENABLE_USER_SITE is False:
- sys.exit(1)
- elif ENABLE_USER_SITE is None:
- sys.exit(2)
- else:
- sys.exit(3)
- else:
- import textwrap
- print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
- sys.exit(10)
-
-if __name__ == '__main__':
- _script()
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_support/__init__.py b/icestudio/install/virtualenv-14.0.1/virtualenv_support/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_support/argparse-1.4.0-py2.py3-none-any.whl b/icestudio/install/virtualenv-14.0.1/virtualenv_support/argparse-1.4.0-py2.py3-none-any.whl
deleted file mode 100644
index dfef51d44..000000000
Binary files a/icestudio/install/virtualenv-14.0.1/virtualenv_support/argparse-1.4.0-py2.py3-none-any.whl and /dev/null differ
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_support/pip-8.0.2-py2.py3-none-any.whl b/icestudio/install/virtualenv-14.0.1/virtualenv_support/pip-8.0.2-py2.py3-none-any.whl
deleted file mode 100644
index cff6237a1..000000000
Binary files a/icestudio/install/virtualenv-14.0.1/virtualenv_support/pip-8.0.2-py2.py3-none-any.whl and /dev/null differ
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_support/setuptools-19.4-py2.py3-none-any.whl b/icestudio/install/virtualenv-14.0.1/virtualenv_support/setuptools-19.4-py2.py3-none-any.whl
deleted file mode 100644
index b58455f31..000000000
Binary files a/icestudio/install/virtualenv-14.0.1/virtualenv_support/setuptools-19.4-py2.py3-none-any.whl and /dev/null differ
diff --git a/icestudio/install/virtualenv-14.0.1/virtualenv_support/wheel-0.26.0-py2.py3-none-any.whl b/icestudio/install/virtualenv-14.0.1/virtualenv_support/wheel-0.26.0-py2.py3-none-any.whl
deleted file mode 100644
index ac025cb44..000000000
Binary files a/icestudio/install/virtualenv-14.0.1/virtualenv_support/wheel-0.26.0-py2.py3-none-any.whl and /dev/null differ
diff --git a/icestudio/js/app.js b/icestudio/js/app.js
deleted file mode 100644
index 4bf3648e3..000000000
--- a/icestudio/js/app.js
+++ /dev/null
@@ -1,529 +0,0 @@
-
-//
-// Define the 'app' module.
-//
-angular.module('app', ['flowChart', ])
-
-//
-// Application 'action' directive.
-//
-.directive('action', function () {
- return {
- link: function (scope, elem, attr) {
- if (attr['action'] === 'load') {
- elem.bind('change', function (event) {
- var file = event.target.files[0];
- event.target.files.clear();
- if (file) {
- scope.load(file.path);
- }
- })
- }
- else if (attr['action'] === 'saveas') {
- elem.bind('change', function (event) {
- var file = event.target.files[0];
- event.target.files.clear();
- if (file) {
- var filepath = file.path;
- if (! filepath.endsWith('.json')) {
- filepath += '.json';
- }
- scope.saveas(filepath);
- }
- })
- }
- }
- }
-})
-
-//
-// Application controller.
-//
-.controller('AppCtrl', ['$scope',
- '$document',
- 'BitService',
- 'IOService',
- 'LogicService',
- 'CombService',
- 'SecService',
- 'LabelService',
- function AppCtrl ($scope,
- $document,
- BitService,
- IOService,
- LogicService,
- CombService,
- SecService,
- LabelService) {
-
- var os = require('os');
- var fs = require('fs');
- var path = require('path');
- var child_process = require('child_process');
-
- // Load native UI library
- var gui = require('nw.gui');
- var win = gui.Window.get();
-
- const WIN32 = Boolean(os.platform().indexOf('win32') > -1);
- const DARWIN = Boolean(os.platform().indexOf('darwin') > -1);
-
- // Code for the delete key.
- var deleteKeyCode = 46;
- // Code for control key.
- var ctrlKeyCode = 17;
- // Set to true when the ctrl key is down.
- var ctrlDown = false;
- // Code for esc key.
- var escKeyCode = 27;
- // Selects the next node id.
- var nextNodeID = 10;
-
- $scope.showEditor = false;
-
- alertify.set({ delay: 2000 });
-
- var home = process.env.HOME || process.env.USERPROFILE;
- if (WIN32) {
- var apio = path.join(home, '.icestudio', 'Scripts', 'apio ');
- }
- else {
- var apio = path.join(home, '.icestudio', 'bin', 'apio ');
- }
- var apioProfile = path.join(home, '.apio', 'profile.json');
-
- var _pythonExecutableCached = null;
- // Get the system executable
- function getPythonExecutable() {
- if (!_pythonExecutableCached) {
- var executables;
- if (WIN32) {
- executables = ['python.exe', 'C:\\Python27\\python.exe'];
- } else {
- executables = ['python2.7', 'python'];
- }
-
- const args = ['-c', 'import sys; print \'.\'.join(str(v) for v in sys.version_info[:2])'];
- for (var i = 0; i < executables.length; i++) {
- const result = child_process.spawnSync(executables[i], args);
- if (0 === result.status && ('' + result.output).indexOf('2.7') > -1) {
- _pythonExecutableCached = executables[i];
- }
- }
-
- if (!_pythonExecutableCached) {
- var html = 'Download and install Python 2.7
';
- if (WIN32) {
- html += 'DON\'T FORGET to select Add python.exe to Path \
- feature on the \"Customize\" stage, otherwise Python Package \
- Manager pip command will not be available.
';
- }
- swal({
- title: 'Python 2.7 is not installed',
- text: html,
- html: true,
- type: 'error',
- });
- document.getElementById('build').className += ' disabled';
- document.getElementById('upload').className += ' disabled';
- return null;
- }
- }
- return _pythonExecutableCached;
- }
-
- function checkApioExecutable() {
- child_process.exec(apio, function(error, stdout, stderr) {
- if (error) {
- disableToolchainButtons();
- }
- });
- }
-
- function checkToolchainInstalled() {
- fs.exists(apioProfile, function(exists) {
- var result = false;
- if (exists) {
- var data = JSON.parse(fs.readFileSync(apioProfile));
- result = 'tool-scons' in data && 'toolchain-icestorm' in data;
- }
-
- if (result) {
- document.getElementById('install-toolchain').innerHTML = 'Upgrade toolchain';
- }
- else {
- disableToolchainButtons();
- }
- });
- }
-
- function disableToolchainButtons() {
- swal({
- title: 'Toolchain is not installed',
- text: 'Please go to Edit > Install toolchain',
- type: 'error'
- });
- document.getElementById('build').className += ' disabled';
- document.getElementById('upload').className += ' disabled';
- }
-
- // Check backend
- if (getPythonExecutable()) {
- checkApioExecutable();
- checkToolchainInstalled();
- }
-
- // Build Examples dropdown
- var examplesArray = [];
- child_process.exec('ls examples', function(error, stdout, stderr) {
- if (!error) {
- examplesArray = stdout.toString().split('.json\n');
- }
- else {
- examplesArray = ['blink', 'blinkdec', 'counter', 'flipflopt', 'setbit'];
- }
- });
-
- $scope.installToolchain = function () {
- if (getPythonExecutable()) {
- var html = 'Please, wait until the installation is complete. \
- It should take less than a minute. \
- This process requires internet connection
\
- ';
- swal({
- title: 'Installing toolchain',
- text: html,
- html: true,
- showCancelButton: false,
- showConfirmButton: false,
- animation: 'none',
- });
-
- child_process.exec(getPythonExecutable() + ' install/install.py', function(error, stdout, stderr) {
- if (stderr) {
- swal({
- title: 'Error',
- text: stderr,
- type: 'error'
- });
- }
- else {
- swal({
- title: 'Success',
- type: 'success'
- });
- document.getElementById('build').className = 'dropdown';
- document.getElementById('upload').className = 'dropdown';
- document.getElementById('install-toolchain').innerHTML = 'Upgrade toolchain';
- }
- });
- }
-
- win.on('close', function() {
- // TODO: process kill
- this.close(true);
- });
- }
-
-
-
- $scope.examples = function () {
- swal({
- title: 'Examples',
- text: examplesArray.join(', '),
- type: 'input',
- showCancelButton: true,
- closeOnConfirm: true,
- animation: 'none',
- inputPlaceholder: 'blink'
- },
- function (example) {
- if (!example) {
- return false;
- }
- if ((example === "") || (examplesArray.indexOf(example) === -1)) {
- alertify.error('Example ' + example + ' does not exist');
- return false;
- }
- $scope.load('examples/' + example + '.json');
- });
- }
-
- $scope.initialize = function () {
- nextNodeID = 10;
- win.title = 'Icestudio';
- $scope.filepath = '';
- $scope.chartDataModel = { nodes: [], connections: [] };
- $scope.chartViewModel = new flowchart.ChartViewModel($scope.chartDataModel);
- }
-
- $scope.initialize();
-
- $scope.new = function () {
- if ($scope.filepath !== '') {
- $scope.initialize();
- alertify.success('New file created');
- }
- };
-
- $scope.load = function (filename) {
- $scope.filepath = filename;
- var name = filename.replace(/^.*[\\\/]/, '').split('.')[0];
- win.title = 'Icestudio - ' + name;
- var data = JSON.parse(fs.readFileSync(filename));
- var max = nextNodeID;
- for (var i = 0; i < data.nodes.length; i++) {
- if (data.nodes[i].id > max) {
- max = data.nodes[i].id;
- }
- }
- nextNodeID = max + 1;
- $scope.chartDataModel = data;
- $scope.chartViewModel = new flowchart.ChartViewModel(data);
- $scope.$digest();
- alertify.success('File ' + name + ' loaded');
- };
-
- $scope.save = function () {
- if ($scope.filepath === '') {
- document.getElementById('saveas').click();
- }
- else {
- $scope.saveas($scope.filepath);
- }
- };
-
- $scope.saveas = function (filename) {
- $scope.filepath = filename;
- var name = filename.replace(/^.*[\\\/]/, '').split('.')[0];
- win.title = 'Icestudio - ' + name;
- fs.writeFile(filename, JSON.stringify($scope.chartDataModel, null, 2), function(err) {
- if (!err) {
- alertify.success('File ' + name + ' saved');
- }
- });
- };
-
- $scope.build = function () {
- alertify.log('Building...');
- $scope.chartViewModel.deselectAll();
- document.getElementById('build').className += ' disabled';
- fs.writeFile('gen/main.json', JSON.stringify($scope.chartDataModel, null, 2), function(err) {
- if (!err) {
- child_process.exec(apio + 'build', function(error, stdout, stderr) {
- if (error) {
- alertify.error('Build fail');
- }
- else if (stdout) {
- if (stdout.toString().indexOf('Error 1') != -1) {
- alertify.error('Build fail');
- }
- else {
- alertify.success('Build success');
- }
- }
- document.getElementById('build').className = 'dropdown';
- });
- }
- });
- };
-
- $scope.upload = function () {
- alertify.log('Uploading...');
- $scope.chartViewModel.deselectAll();
- document.getElementById('upload').className += ' disabled';
- child_process.exec(apio + 'upload', function(error, stdout, stderr) {
- if (error) {
- alertify.error('Upload fail');
- }
- else if (stdout) {
- if (stdout.toString().indexOf('Error 1') != -1) {
- alertify.error('Upload fail');
- }
- else {
- alertify.success('Upload success');
- }
- }
- document.getElementById('upload').className = 'dropdown';
- });
- };
-
- // Event handler for key-down on the flowchart.
- $scope.keyDown = function (evt) {
-
- if (evt.keyCode === ctrlKeyCode) {
-
- ctrlDown = true;
- evt.stopPropagation();
- evt.preventDefault();
- }
- };
-
- // Event handler for key-up on the flowchart.
- $scope.keyUp = function (evt) {
-
- if (evt.keyCode === deleteKeyCode) {
- // Delete key.
- $scope.chartViewModel.deleteSelected();
- }
-
- if (evt.keyCode == escKeyCode) {
- // Escape.
- $scope.chartViewModel.deselectAll();
- }
-
- if (evt.keyCode === ctrlKeyCode) {
- ctrlDown = false;
- evt.stopPropagation();
- evt.preventDefault();
- }
- };
-
- //
- // Bit
- //
- $scope.addNewDriver0Node = function () {
- BitService.addNewDriverNode(0, nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
- $scope.addNewDriver1Node = function () {
- BitService.addNewDriverNode(1, nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
-
- //
- // IO
- //
- $scope.addNewInputNode = function () {
- IOService.addNewInputNode(nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
- $scope.addNewOutputNode = function () {
- IOService.addNewOutputNode(nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
-
- //
- // Logic gates
- //
- $scope.addNewNotNode = function () {
- LogicService.addNewNotNode(nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
- $scope.addNewAndNode = function () {
- LogicService.addNewAndNode(nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
- $scope.addNewOrNode = function () {
- LogicService.addNewOrNode(nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
- $scope.addNewXorNode = function () {
- LogicService.addNewXorNode(nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
-
- //
- // Comb
- //
- $scope.addNewMuxNode = function () {
- CombService.addNewMuxNode(nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
- $scope.addNewDecNode = function () {
- CombService.addNewDecNode(nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
-
- //
- // Sec
- //
- $scope.addNewDivNode = function () {
- SecService.addNewDivNode(nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
- $scope.addNewTimerNode = function () {
- SecService.addNewTimerNode(nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
- $scope.addNewCounterNode = function () {
- SecService.addNewCounterNode(nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
- $scope.addNewFlipflopNode = function () {
- SecService.addNewFlipflopNode(nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
- $scope.addNewNotesNode = function () {
- SecService.addNewNotesNode(nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
-
- //
- // Label
- //
- $scope.addNewLabelInputNode = function () {
- LabelService.addNewLabelInputNode(nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
- $scope.addNewLabelOutputNode = function () {
- LabelService.addNewLabelOutputNode(nextNodeID, function (node, id) {
- $scope.chartViewModel.addNode(node);
- nextNodeID = id;
- });
- };
-
- // Delete selected nodes and connections.
- $scope.deleteSelected = function () {
- $scope.chartViewModel.deleteSelected();
- };
-
- // Show/Hide verilog editor
- $scope.toggleEditor = function () {
- document.getElementById('editor').style.opacity = '1.0';
- document.getElementById('editor').style.visibility = 'visible';
- $scope.showEditor = !$scope.showEditor;
- if ($scope.showEditor) {
- document.getElementById('BQLogo').style.opacity = '0.0';
- document.getElementById('warning').style.opacity = '0.0';
- document.getElementById('editor').style.height = '280px';
- }
- else {
- document.getElementById('editor').style.height = '0px';
- document.getElementById('BQLogo').style.opacity = '1.0';
- document.getElementById('warning').style.opacity = '1.0';
- }
- };
-}]);
diff --git a/icestudio/js/blocks/bit/bit.js b/icestudio/js/blocks/bit/bit.js
deleted file mode 100644
index 06ac9e419..000000000
--- a/icestudio/js/blocks/bit/bit.js
+++ /dev/null
@@ -1,32 +0,0 @@
-
-angular.module('app')
-
-.service('BitService', function BitService () {
-
- var fs = require('fs');
- var bitv = fs.readFileSync('js/blocks/bit/bit.v').toString();
-
- var exports = {};
-
- exports.addNewDriverNode = function (value, nodeID, callback) {
- value = value.toString();
- var block = {
- label: "",
- type: "driver",
- params: [
- { name: "B", value: "1'b" + value }
- ],
- vcode: bitv,
- id: nodeID++,
- x: 50, y: 100,
- width: 55,
- outputConnectors: [ {
- name: "o",
- label: "\"" + value + "\""
- }]
- };
- callback(block, nodeID);
- };
-
- return exports;
-});
diff --git a/icestudio/js/blocks/bit/bit.v b/icestudio/js/blocks/bit/bit.v
deleted file mode 100644
index 76cfff2ed..000000000
--- a/icestudio/js/blocks/bit/bit.v
+++ /dev/null
@@ -1,3 +0,0 @@
-module driver #(parameter B = 1'b0)(output o);
-assign o = B;
-endmodule
diff --git a/icestudio/js/blocks/comb/comb.js b/icestudio/js/blocks/comb/comb.js
deleted file mode 100644
index a26a0a560..000000000
--- a/icestudio/js/blocks/comb/comb.js
+++ /dev/null
@@ -1,54 +0,0 @@
-
-angular.module('app')
-
-.service('CombService', function CombService () {
-
- var fs = require('fs');
- var muxv = fs.readFileSync('js/blocks/comb/mux.v').toString();
- var decv = fs.readFileSync('js/blocks/comb/dec.v').toString();
-
- var exports = {};
-
- exports.addNewMuxNode = function (nodeID, callback) {
- var block = {
- label: "MUX",
- type: "mux",
- params: [],
- vcode: muxv,
- id: nodeID++,
- x: 50, y: 100,
- width: 150,
- inputConnectors: [
- { name: "c0", label: "c0" },
- { name: "c1", label: "c1" },
- { name: "sel", label: "sel" }
- ],
- outputConnectors: [
- { name: "o", label: "out" }
- ]
- };
- callback(block, nodeID);
- };
-
- exports.addNewDecNode = function (nodeID, callback) {
- var block = {
- label: "DEC",
- type: "dec",
- params: [],
- vcode: decv,
- id: nodeID++,
- x: 50, y: 100,
- width: 140,
- inputConnectors: [
- { name: "c", label: "c" }
- ],
- outputConnectors: [
- { name: "o0", label: "o0" },
- { name: "o1", label: "o1" }
- ]
- };
- callback(block, nodeID);
- };
-
- return exports;
-});
diff --git a/icestudio/js/blocks/comb/dec.v b/icestudio/js/blocks/comb/dec.v
deleted file mode 100644
index ecc9e4cb0..000000000
--- a/icestudio/js/blocks/comb/dec.v
+++ /dev/null
@@ -1,7 +0,0 @@
-module dec (input c, output reg o0, o1);
- always @(*)
- begin
- o0 = (c == 0) ? 1 : 0;
- o1 = (c == 1) ? 1 : 0;
- end
-endmodule
diff --git a/icestudio/js/blocks/comb/mux.v b/icestudio/js/blocks/comb/mux.v
deleted file mode 100644
index de85a33ab..000000000
--- a/icestudio/js/blocks/comb/mux.v
+++ /dev/null
@@ -1,4 +0,0 @@
-module mux (input c0, c1, sel, output reg o);
- always @(*)
- o = (sel == 0) ? c0 : c1;
-endmodule
diff --git a/icestudio/js/blocks/io/io.js b/icestudio/js/blocks/io/io.js
deleted file mode 100644
index 820741309..000000000
--- a/icestudio/js/blocks/io/io.js
+++ /dev/null
@@ -1,75 +0,0 @@
-
-angular.module('app')
-
-.service('IOService', function IOService () {
-
- var exports = {};
-
- exports.addNewInputNode = function (nodeID, callback) {
- swal({
- title: "FPGA pin",
- text: "Enter the input pin:",
- type: "input",
- showCancelButton: true,
- closeOnConfirm: true,
- animation: "none",
- inputPlaceholder: "21 44"
- },
- function(value) {
- if ((value === false) || (value === "")) {
- return false;
- }
- array = value.split(' ');
- for (var i = 0; i < array.length; i++) {
- var item = array[i];
- var block = {
- label: "",
- type: "input",
- params: [ item ],
- id: nodeID++,
- x: 50, y: 100 + i * 60,
- width: 40 + item.length * 8,
- outputConnectors: [ {
- label: item
- }]
- };
- callback(block, nodeID);
- };
- });
- };
-
- exports.addNewOutputNode = function (nodeID, callback) {
- swal({
- title: "FPGA pin",
- text: "Enter the output pin:",
- type: "input",
- showCancelButton: true,
- closeOnConfirm: true,
- animation: "none",
- inputPlaceholder: "95 96 97"
- },
- function(value) {
- if ((value === false) || (value === "")) {
- return false;
- }
- array = value.split(' ');
- for (var i = 0; i < array.length; i++) {
- var item = array[i];
- var block = {
- label: "",
- type: "output",
- params: [ item ],
- id: nodeID++,
- x: 50, y: 100 + i * 60,
- width: 40 + item.length * 8,
- inputConnectors: [ {
- label: item
- }]
- };
- callback(block, nodeID);
- };
- });
- };
-
- return exports;
-});
diff --git a/icestudio/js/blocks/label/label.js b/icestudio/js/blocks/label/label.js
deleted file mode 100644
index 0e8eab5c4..000000000
--- a/icestudio/js/blocks/label/label.js
+++ /dev/null
@@ -1,77 +0,0 @@
-
-angular.module('app')
-
-.service('LabelService', function LabelService () {
-
- var exports = {};
-
- exports.addNewLabelInputNode = function (nodeID, callback) {
- swal({
- title: "Label input",
- text: "Enter the label name:",
- type: "input",
- showCancelButton: true,
- closeOnConfirm: true,
- animation: "none",
- inputPlaceholder: "signal"
- },
- function(value) {
- if ((value === false) || (value === "")) {
- return false;
- }
- array = value.split(' ');
- for (var i = 0; i < array.length; i++) {
- var item = '_' + array[i];
- var block = {
- label: "",
- type: "linput",
- params: [ item ],
- id: nodeID++,
- x: 50, y: 100 + i * 60,
- width: 40 + item.length * 8,
- outputConnectors: [ {
- value: item,
- label: item
- }]
- };
- callback(block, nodeID);
- };
- });
- };
-
- exports.addNewLabelOutputNode = function (nodeID, callback) {
- swal({
- title: "Label output",
- text: "Enter the label name:",
- type: "input",
- showCancelButton: true,
- closeOnConfirm: true,
- animation: "none",
- inputPlaceholder: "signal"
- },
- function(value) {
- if ((value === false) || (value === "")) {
- return false;
- }
- array = value.split(' ');
- for (var i = 0; i < array.length; i++) {
- var item = '_' + array[i];
- var block = {
- label: "",
- type: "loutput",
- params: [ item ],
- id: nodeID++,
- x: 50, y: 100 + i * 60,
- width: 40 + item.length * 8,
- inputConnectors: [ {
- value: item,
- label: item
- }]
- };
- callback(block, nodeID);
- };
- });
- };
-
- return exports;
-});
diff --git a/icestudio/js/blocks/logic/and.v b/icestudio/js/blocks/logic/and.v
deleted file mode 100644
index 08234e4cd..000000000
--- a/icestudio/js/blocks/logic/and.v
+++ /dev/null
@@ -1,3 +0,0 @@
-module andx (input a, b, output o);
-assign o = a & b;
-endmodule
diff --git a/icestudio/js/blocks/logic/logic.js b/icestudio/js/blocks/logic/logic.js
deleted file mode 100644
index 63a34cb15..000000000
--- a/icestudio/js/blocks/logic/logic.js
+++ /dev/null
@@ -1,94 +0,0 @@
-
-angular.module('app')
-
-.service('LogicService', function LogicService () {
-
- var fs = require('fs');
- var notv = fs.readFileSync('js/blocks/logic/not.v').toString();
- var andv = fs.readFileSync('js/blocks/logic/and.v').toString();
- var orv = fs.readFileSync('js/blocks/logic/or.v').toString();
- var xorv = fs.readFileSync('js/blocks/logic/xor.v').toString();
-
- var exports = {};
-
- exports.addNewNotNode = function (nodeID, callback) {
- var block = {
- label: "NOT",
- type: "notx",
- params: [],
- vcode: notv,
- id: nodeID++,
- x: 50, y: 100,
- width: 80,
- inputConnectors: [
- { name: "i", label: "" }
- ],
- outputConnectors: [
- { name: "o", label: "" }
- ]
- };
- callback(block, nodeID);
- };
-
- exports.addNewAndNode = function (nodeID, callback) {
- var block = {
- label: "AND",
- type: "andx",
- params: [],
- vcode: andv,
- id: nodeID++,
- x: 50, y: 100,
- width: 80,
- inputConnectors: [
- { name: "a", label: "" },
- { name: "b", label: "" }
- ],
- outputConnectors: [
- { name: "o", label: "" }
- ]
- };
- callback(block, nodeID);
- };
-
- exports.addNewOrNode = function (nodeID, callback) {
- var block = {
- label: "OR",
- type: "orx",
- params: [],
- vcode: orv,
- id: nodeID++,
- x: 50, y: 100,
- width: 80,
- inputConnectors: [
- { name: "a", label: "" },
- { name: "b", label: "" }
- ],
- outputConnectors: [
- { name: "o", label: "" }
- ]
- };
- callback(block, nodeID);
- };
-
- exports.addNewXorNode = function (nodeID, callback) {
- var block = {
- label: "XOR",
- type: "xorx",
- params: [],
- vcode: xorv,
- id: nodeID++,
- x: 50, y: 100,
- width: 80,
- inputConnectors: [
- { name: "a", label: "" },
- { name: "b", label: "" }
- ],
- outputConnectors: [
- { name: "o", label: "" }
- ]
- };
- callback(block, nodeID);
- };
-
- return exports;
-});
diff --git a/icestudio/js/blocks/logic/not.v b/icestudio/js/blocks/logic/not.v
deleted file mode 100644
index de2b36a8f..000000000
--- a/icestudio/js/blocks/logic/not.v
+++ /dev/null
@@ -1,3 +0,0 @@
-module notx (input i, output o);
-assign o = ! i;
-endmodule
diff --git a/icestudio/js/blocks/logic/or.v b/icestudio/js/blocks/logic/or.v
deleted file mode 100644
index 259627b7f..000000000
--- a/icestudio/js/blocks/logic/or.v
+++ /dev/null
@@ -1,3 +0,0 @@
-module orx (input a, b, output o);
-assign o = a | b;
-endmodule
diff --git a/icestudio/js/blocks/logic/xor.v b/icestudio/js/blocks/logic/xor.v
deleted file mode 100644
index a4f752c9b..000000000
--- a/icestudio/js/blocks/logic/xor.v
+++ /dev/null
@@ -1,3 +0,0 @@
-module xorx (input a, b, output o);
-assign o = a ^ b;
-endmodule
diff --git a/icestudio/js/blocks/sec/counter.v b/icestudio/js/blocks/sec/counter.v
deleted file mode 100644
index 096172e44..000000000
--- a/icestudio/js/blocks/sec/counter.v
+++ /dev/null
@@ -1,10 +0,0 @@
-module counter (input clk, ena, output c0, c1, c2, c3);
- reg [3:0] c = 0;
- always @(posedge clk)
- if (ena)
- c <= c + 1;
- assign c0 = c[0];
- assign c1 = c[1];
- assign c2 = c[2];
- assign c3 = c[3];
-endmodule
diff --git a/icestudio/js/blocks/sec/div.v b/icestudio/js/blocks/sec/div.v
deleted file mode 100644
index 0aa0665de..000000000
--- a/icestudio/js/blocks/sec/div.v
+++ /dev/null
@@ -1,17 +0,0 @@
-module div #(parameter N=22, M=4194304)(input clk, output reg out);
- wire clk_temp;
- reg [N - 1:0] c = 0;
- always @(posedge clk)
- if (M == 0)
- c <= 0;
- else if (c == M - 1)
- c <= 0;
- else
- c <= c + 1;
- assign clk_temp = (c == 0) ? 1 : 0;
- always @(posedge clk)
- if (N == 0)
- out <= 0;
- else if (clk_temp == 1)
- out <= ~out;
-endmodule
diff --git a/icestudio/js/blocks/sec/flipflop.v b/icestudio/js/blocks/sec/flipflop.v
deleted file mode 100644
index dcabaa3b8..000000000
--- a/icestudio/js/blocks/sec/flipflop.v
+++ /dev/null
@@ -1,10 +0,0 @@
-module flipflop (input clk, rst, d, ena, output reg q);
- always @(posedge clk)
- begin
- if (rst)
- q <= 0;
- else
- if (ena)
- q <= d;
- end
-endmodule
diff --git a/icestudio/js/blocks/sec/imperial.list b/icestudio/js/blocks/sec/imperial.list
deleted file mode 100644
index a6ace9aee..000000000
--- a/icestudio/js/blocks/sec/imperial.list
+++ /dev/null
@@ -1,54 +0,0 @@
-//-- Marcha imperial
-0 //-- Un 0 es un SILENCIO
-0
-0
-0
-0
-0
-0
-0
-0
-471A //-- MI_4
-471A
-0
-471A //-- MI_4
-471A
-0
-471A //-- MI_4
-471A
-0
-5996 //-- DO_4
-5996
-3BCA //-- SOL_4
-471A //-- MI_4
-471A
-0
-5996 //-- DO_4
-5996
-3BCA //-- SOL_4
-471A //-- MI_4
-471A
-//----------- Segundo trozo
-0
-0
-0
-2F75 //-- SI_4
-2F75
-0
-2F75 //-- SI_4
-2F75
-0
-2F75 //-- SI_4
-2F75
-0
-2CCB //-- DO_5
-2CCB
-3BCA //-- SOL_4
-471A //-- MI_4
-471A
-0
-5996 //-- DO_4
-5996
-3BCA //-- SOL_4
-471A //-- MI_4
-471A
diff --git a/icestudio/js/blocks/sec/notes.v b/icestudio/js/blocks/sec/notes.v
deleted file mode 100644
index 3c8be2998..000000000
--- a/icestudio/js/blocks/sec/notes.v
+++ /dev/null
@@ -1,179 +0,0 @@
-//-- Author: obijuan
-
-
-module genrom #( //-- Parametros
- parameter AW = 5, //-- Bits de las direcciones (Adress width)
- parameter DW = 4) //-- Bits de los datos (Data witdh)
-
- ( //-- Puertos
- input clk, //-- Señal de reloj global
- input wire [AW-1: 0] addr, //-- Direcciones
- output reg [DW-1: 0] data); //-- Dato de salida
-
-//-- Parametro: Nombre del fichero con el contenido de la ROM
-parameter ROMFILE = "js/blocks/sec/imperial.list";
-
-//-- Calcular el numero de posiciones totales de memoria
-localparam NPOS = 2 ** AW;
-
- //-- Memoria
- reg [DW-1: 0] rom [0: NPOS-1];
-
- //-- Lectura de la memoria
- always @(posedge clk) begin
- data <= rom[addr];
- end
-
-//-- Cargar en la memoria el fichero ROMFILE
-//-- Los valores deben estan dados en hexadecimal
-initial begin
- $readmemh(ROMFILE, rom);
-end
-
-endmodule
-
-
-module notegen(input wire clk, //-- Senal de reloj global
- input wire rstn, //-- Reset
- input wire [15:0] note, //-- Divisor
- output reg clk_out); //-- Señal de salida
-
-wire clk_tmp;
-
-//-- Registro para implementar el contador modulo note
-reg [15:0] divcounter = 0;
-
-//-- Contador módulo note
-always @(posedge clk)
-
- //-- Reset
- if (rstn == 0)
- divcounter <= 0;
-
- //-- Si la nota es 0 no se incrementa contador
- else if (note == 0)
- divcounter <= 0;
-
- //-- Si se alcanza el tope, poner a 0
- else if (divcounter == note - 1)
- divcounter <= 0;
-
- //-- Incrementar contador
- else
- divcounter <= divcounter + 1;
-
-//-- Sacar un pulso de anchura 1 ciclo de reloj si el generador
-assign clk_tmp = (divcounter == 0) ? 1 : 0;
-
-//-- Divisor de frecuencia entre 2, para obtener como salida una señal
-//-- con un ciclo de trabajo del 50%
-always @(posedge clk)
- if (rstn == 0)
- clk_out <= 0;
-
- else if (note == 0)
- clk_out <= 0;
-
- else if (clk_tmp == 1)
- clk_out <= ~clk_out;
-
-endmodule
-
-
-`define T_100ms 1200000
-`define T_200ms 2400000
-
-//-- ENTRADAS:
-//-- -clk: Senal de reloj del sistema (12 MHZ en la iceStick)
-//
-//-- SALIDAS:
-//-- - clk_out. Señal de salida para lograr la velocidad en baudios indicada
-//-- Anchura de 1 periodo de clk. SALIDA NO REGISTRADA
-module dividerp1(input wire clk,
- output wire clk_out);
-
-//-- Valor por defecto de la velocidad en baudios
-parameter M = `T_100ms;
-
-//-- Numero de bits para almacenar el divisor de baudios
-localparam N = $clog2(M);
-
-//-- Registro para implementar el contador modulo M
-reg [N-1:0] divcounter = 0;
-
-//-- Contador módulo M
-always @(posedge clk)
- divcounter <= (divcounter == M - 1) ? 0 : divcounter + 1;
-
-//-- Sacar un pulso de anchura 1 ciclo de reloj si el generador
-assign clk_out = (divcounter == 0) ? 1 : 0;
-
-endmodule
-
-
-module romnotes(input wire clk,
- output wire ch_out);
-
-//-- Parametros
-//-- Duracion de las notas
-parameter DUR = `T_200ms;
-
-//-- Fichero con las notas para cargar en la rom
-parameter ROMFILE = "js/blocks/sec/imperial.list";
-
-//-- Tamaño del bus de direcciones de la rom
-parameter AW = 6;
-
-//-- Tamaño de las notas
-parameter DW = 16;
-
-//-- Cables de salida de los canales
-wire ch0, ch1, ch2;
-
-//-- Selección del canal del multiplexor
-reg [AW-1: 0] addr = 0;
-
-//-- Reloj con la duracion de la nota
-wire clk_dur;
-reg rstn = 0;
-
-wire [DW-1: 0] note;
-
-//-- Instanciar la memoria rom
-genrom
- #( .ROMFILE(ROMFILE),
- .AW(AW),
- .DW(DW))
- ROM (
- .clk(clk),
- .addr(addr),
- .data(note)
- );
-
-//-- Generador de notas
-notegen
- CH0 (
- .clk(clk),
- .rstn(rstn),
- .note(note),
- .clk_out(ch_out)
- );
-
-//-- Inicializador
-always @(posedge clk)
- rstn <= 1;
-
-
-//-- Contador para seleccion de nota
-always @(posedge clk)
- if (clk_dur)
- addr <= addr + 1;
-
-//-- Divisor para marcar la duración de cada nota
-dividerp1 #(DUR)
- TIMER0 (
- .clk(clk),
- .clk_out(clk_dur)
- );
-
-endmodule
diff --git a/icestudio/js/blocks/sec/sec.js b/icestudio/js/blocks/sec/sec.js
deleted file mode 100644
index 07dd6ac39..000000000
--- a/icestudio/js/blocks/sec/sec.js
+++ /dev/null
@@ -1,166 +0,0 @@
-
-angular.module('app')
-
-.service('SecService', function SecService () {
-
- var fs = require('fs');
- var divv = fs.readFileSync('js/blocks/sec/div.v').toString();
- var timerv = fs.readFileSync('js/blocks/sec/timer.v').toString();
- var counterv = fs.readFileSync('js/blocks/sec/counter.v').toString();
- var flipflopv = fs.readFileSync('js/blocks/sec/flipflop.v').toString();
- var notesv = fs.readFileSync('js/blocks/sec/notes.v').toString();
-
- var exports = {};
-
- exports.addNewDivNode = function (nodeID, callback) {
- swal({
- title: "Divider",
- text: "Enter the number of divisions",
- type: "input",
- showCancelButton: true,
- closeOnConfirm: true,
- animation: "none",
- inputPlaceholder: "22 23"
- },
- function(value) {
- if ((value === false) || (value === "")) {
- return false;
- }
- array = value.split(' ');
- for (var i = 0; i < array.length; i++) {
- var item = array[i];
- var N = item;
- var M = Math.pow(2, item);
-
- var block = {
- label: "DIV (" + item.toString() + ")",
- type: "div",
- params: [
- { name: "N", value: N },
- { name: "M", value: M }
- ],
- id: nodeID++,
- x: 50, y: 100 + i * 60,
- width: 150 + item.length * 8,
- vcode: divv,
- inputConnectors: [
- { name: "clk", label: "clk" }
- ],
- outputConnectors: [
- { name: "out", label: "out" }
- ]
- };
- callback(block, nodeID);
- };
- });
- };
-
- exports.addNewTimerNode = function (nodeID, callback) {
- swal({
- title: "Timer",
- text: "Enter the number of divisions",
- type: "input",
- showCancelButton: true,
- closeOnConfirm: true,
- animation: "none",
- inputPlaceholder: "22 23"
- },
- function(value) {
- if ((value === false) || (value === "")) {
- return false;
- }
- array = value.split(' ');
- for (var i = 0; i < array.length; i++) {
- var item = array[i];
- var N = item;
- var M = Math.pow(2, item);
-
- var block = {
- label: "TIM (" + item.toString() + ")",
- type: "timer",
- params: [
- { name: "N", value: N },
- { name: "M", value: M }
- ],
- id: nodeID++,
- x: 50, y: 100 + i * 60,
- width: 150 + item.length * 8,
- vcode: timerv,
- inputConnectors: [
- { name: "clk", label: "clk" }
- ],
- outputConnectors: [
- { name: "out", label: "out" }
- ]
- };
- callback(block, nodeID);
- };
- });
- };
-
- exports.addNewCounterNode = function (nodeID, callback) {
- var block = {
- label: "CNT",
- type: "counter",
- params: [],
- vcode: counterv,
- id: nodeID++,
- x: 50, y: 100,
- width: 150,
- inputConnectors: [
- { name: "clk", label: "clk" },
- { name: "ena", label: "ena" }
- ],
- outputConnectors: [
- { name: "c0", label: "c0" },
- { name: "c1", label: "c1" },
- { name: "c2", label: "c2" },
- { name: "c3", label: "c3" }
- ]
- };
- callback(block, nodeID);
- };
-
- exports.addNewFlipflopNode = function (nodeID, callback) {
- var block = {
- label: "FF",
- type: "flipflop",
- params: [],
- vcode: flipflopv,
- id: nodeID++,
- x: 50, y: 100,
- width: 150,
- inputConnectors: [
- { name: "clk", label: "clk" },
- { name: "rst", label: "rst" },
- { name: "d", label: "D" },
- { name: "ena", label: "ena" },
- ],
- outputConnectors: [
- { name: "q", label: "Q" }
- ]
- };
- callback(block, nodeID);
- };
-
- exports.addNewNotesNode = function (nodeID, callback) {
- var block = {
- label: "Notes",
- type: "romnotes",
- params: [],
- vcode: notesv,
- id: nodeID++,
- x: 50, y: 100,
- width: 150,
- inputConnectors: [
- { name: "clk", label: "clk" }
- ],
- outputConnectors: [
- { name: "ch_out", label: "o" }
- ]
- };
- callback(block, nodeID);
- };
-
- return exports;
-});
diff --git a/icestudio/js/blocks/sec/timer.v b/icestudio/js/blocks/sec/timer.v
deleted file mode 100644
index 800e9f7bb..000000000
--- a/icestudio/js/blocks/sec/timer.v
+++ /dev/null
@@ -1,6 +0,0 @@
-module timer #(parameter N=22, M=4194304)(input clk, output wire out);
- reg [N-1:0] c = 0;
- always @(posedge clk)
- c <= (c == M - 1) ? 0 : c + 1;
- assign out = (c == M - 1) ? 1 : 0;
-endmodule
diff --git a/icestudio/lib/ace-builds/src-noconflict/ace.js b/icestudio/lib/ace-builds/src-noconflict/ace.js
deleted file mode 100644
index 5c4c351bb..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ace.js
+++ /dev/null
@@ -1,18672 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2010, Ajax.org B.V.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of Ajax.org B.V. nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-/**
- * Define a module along with a payload
- * @param module a name for the payload
- * @param payload a function to call with (require, exports, module) params
- */
-
-(function() {
-
-var ACE_NAMESPACE = "ace";
-
-var global = (function() { return this; })();
-if (!global && typeof window != "undefined") global = window; // strict mode
-
-
-if (!ACE_NAMESPACE && typeof requirejs !== "undefined")
- return;
-
-
-var define = function(module, deps, payload) {
- if (typeof module !== "string") {
- if (define.original)
- define.original.apply(this, arguments);
- else {
- console.error("dropping module because define wasn\'t a string.");
- console.trace();
- }
- return;
- }
- if (arguments.length == 2)
- payload = deps;
- if (!define.modules[module]) {
- define.payloads[module] = payload;
- define.modules[module] = null;
- }
-};
-
-define.modules = {};
-define.payloads = {};
-
-/**
- * Get at functionality define()ed using the function above
- */
-var _require = function(parentId, module, callback) {
- if (typeof module === "string") {
- var payload = lookup(parentId, module);
- if (payload != undefined) {
- callback && callback();
- return payload;
- }
- } else if (Object.prototype.toString.call(module) === "[object Array]") {
- var params = [];
- for (var i = 0, l = module.length; i < l; ++i) {
- var dep = lookup(parentId, module[i]);
- if (dep == undefined && require.original)
- return;
- params.push(dep);
- }
- return callback && callback.apply(null, params) || true;
- }
-};
-
-var require = function(module, callback) {
- var packagedModule = _require("", module, callback);
- if (packagedModule == undefined && require.original)
- return require.original.apply(this, arguments);
- return packagedModule;
-};
-
-var normalizeModule = function(parentId, moduleName) {
- // normalize plugin requires
- if (moduleName.indexOf("!") !== -1) {
- var chunks = moduleName.split("!");
- return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]);
- }
- // normalize relative requires
- if (moduleName.charAt(0) == ".") {
- var base = parentId.split("/").slice(0, -1).join("/");
- moduleName = base + "/" + moduleName;
-
- while(moduleName.indexOf(".") !== -1 && previous != moduleName) {
- var previous = moduleName;
- moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
- }
- }
- return moduleName;
-};
-
-/**
- * Internal function to lookup moduleNames and resolve them by calling the
- * definition function if needed.
- */
-var lookup = function(parentId, moduleName) {
- moduleName = normalizeModule(parentId, moduleName);
-
- var module = define.modules[moduleName];
- if (!module) {
- module = define.payloads[moduleName];
- if (typeof module === 'function') {
- var exports = {};
- var mod = {
- id: moduleName,
- uri: '',
- exports: exports,
- packaged: true
- };
-
- var req = function(module, callback) {
- return _require(moduleName, module, callback);
- };
-
- var returnValue = module(req, exports, mod);
- exports = returnValue || mod.exports;
- define.modules[moduleName] = exports;
- delete define.payloads[moduleName];
- }
- module = define.modules[moduleName] = exports || module;
- }
- return module;
-};
-
-function exportAce(ns) {
- var root = global;
- if (ns) {
- if (!global[ns])
- global[ns] = {};
- root = global[ns];
- }
-
- if (!root.define || !root.define.packaged) {
- define.original = root.define;
- root.define = define;
- root.define.packaged = true;
- }
-
- if (!root.require || !root.require.packaged) {
- require.original = root.require;
- root.require = require;
- root.require.packaged = true;
- }
-}
-
-exportAce(ACE_NAMESPACE);
-
-})();
-
-ace.define("ace/lib/regexp",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
- var real = {
- exec: RegExp.prototype.exec,
- test: RegExp.prototype.test,
- match: String.prototype.match,
- replace: String.prototype.replace,
- split: String.prototype.split
- },
- compliantExecNpcg = real.exec.call(/()??/, "")[1] === undefined, // check `exec` handling of nonparticipating capturing groups
- compliantLastIndexIncrement = function () {
- var x = /^/g;
- real.test.call(x, "");
- return !x.lastIndex;
- }();
-
- if (compliantLastIndexIncrement && compliantExecNpcg)
- return;
- RegExp.prototype.exec = function (str) {
- var match = real.exec.apply(this, arguments),
- name, r2;
- if ( typeof(str) == 'string' && match) {
- if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) {
- r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", ""));
- real.replace.call(str.slice(match.index), r2, function () {
- for (var i = 1; i < arguments.length - 2; i++) {
- if (arguments[i] === undefined)
- match[i] = undefined;
- }
- });
- }
- if (this._xregexp && this._xregexp.captureNames) {
- for (var i = 1; i < match.length; i++) {
- name = this._xregexp.captureNames[i - 1];
- if (name)
- match[name] = match[i];
- }
- }
- if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index))
- this.lastIndex--;
- }
- return match;
- };
- if (!compliantLastIndexIncrement) {
- RegExp.prototype.test = function (str) {
- var match = real.exec.call(this, str);
- if (match && this.global && !match[0].length && (this.lastIndex > match.index))
- this.lastIndex--;
- return !!match;
- };
- }
-
- function getNativeFlags (regex) {
- return (regex.global ? "g" : "") +
- (regex.ignoreCase ? "i" : "") +
- (regex.multiline ? "m" : "") +
- (regex.extended ? "x" : "") + // Proposed for ES4; included in AS3
- (regex.sticky ? "y" : "");
- }
-
- function indexOf (array, item, from) {
- if (Array.prototype.indexOf) // Use the native array method if available
- return array.indexOf(item, from);
- for (var i = from || 0; i < array.length; i++) {
- if (array[i] === item)
- return i;
- }
- return -1;
- }
-
-});
-
-ace.define("ace/lib/es5-shim",["require","exports","module"], function(require, exports, module) {
-
-function Empty() {}
-
-if (!Function.prototype.bind) {
- Function.prototype.bind = function bind(that) { // .length is 1
- var target = this;
- if (typeof target != "function") {
- throw new TypeError("Function.prototype.bind called on incompatible " + target);
- }
- var args = slice.call(arguments, 1); // for normal call
- var bound = function () {
-
- if (this instanceof bound) {
-
- var result = target.apply(
- this,
- args.concat(slice.call(arguments))
- );
- if (Object(result) === result) {
- return result;
- }
- return this;
-
- } else {
- return target.apply(
- that,
- args.concat(slice.call(arguments))
- );
-
- }
-
- };
- if(target.prototype) {
- Empty.prototype = target.prototype;
- bound.prototype = new Empty();
- Empty.prototype = null;
- }
- return bound;
- };
-}
-var call = Function.prototype.call;
-var prototypeOfArray = Array.prototype;
-var prototypeOfObject = Object.prototype;
-var slice = prototypeOfArray.slice;
-var _toString = call.bind(prototypeOfObject.toString);
-var owns = call.bind(prototypeOfObject.hasOwnProperty);
-var defineGetter;
-var defineSetter;
-var lookupGetter;
-var lookupSetter;
-var supportsAccessors;
-if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) {
- defineGetter = call.bind(prototypeOfObject.__defineGetter__);
- defineSetter = call.bind(prototypeOfObject.__defineSetter__);
- lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
- lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
-}
-if ([1,2].splice(0).length != 2) {
- if(function() { // test IE < 9 to splice bug - see issue #138
- function makeArray(l) {
- var a = new Array(l+2);
- a[0] = a[1] = 0;
- return a;
- }
- var array = [], lengthBefore;
-
- array.splice.apply(array, makeArray(20));
- array.splice.apply(array, makeArray(26));
-
- lengthBefore = array.length; //46
- array.splice(5, 0, "XXX"); // add one element
-
- lengthBefore + 1 == array.length
-
- if (lengthBefore + 1 == array.length) {
- return true;// has right splice implementation without bugs
- }
- }()) {//IE 6/7
- var array_splice = Array.prototype.splice;
- Array.prototype.splice = function(start, deleteCount) {
- if (!arguments.length) {
- return [];
- } else {
- return array_splice.apply(this, [
- start === void 0 ? 0 : start,
- deleteCount === void 0 ? (this.length - start) : deleteCount
- ].concat(slice.call(arguments, 2)))
- }
- };
- } else {//IE8
- Array.prototype.splice = function(pos, removeCount){
- var length = this.length;
- if (pos > 0) {
- if (pos > length)
- pos = length;
- } else if (pos == void 0) {
- pos = 0;
- } else if (pos < 0) {
- pos = Math.max(length + pos, 0);
- }
-
- if (!(pos+removeCount < length))
- removeCount = length - pos;
-
- var removed = this.slice(pos, pos+removeCount);
- var insert = slice.call(arguments, 2);
- var add = insert.length;
- if (pos === length) {
- if (add) {
- this.push.apply(this, insert);
- }
- } else {
- var remove = Math.min(removeCount, length - pos);
- var tailOldPos = pos + remove;
- var tailNewPos = tailOldPos + add - remove;
- var tailCount = length - tailOldPos;
- var lengthAfterRemove = length - remove;
-
- if (tailNewPos < tailOldPos) { // case A
- for (var i = 0; i < tailCount; ++i) {
- this[tailNewPos+i] = this[tailOldPos+i];
- }
- } else if (tailNewPos > tailOldPos) { // case B
- for (i = tailCount; i--; ) {
- this[tailNewPos+i] = this[tailOldPos+i];
- }
- } // else, add == remove (nothing to do)
-
- if (add && pos === lengthAfterRemove) {
- this.length = lengthAfterRemove; // truncate array
- this.push.apply(this, insert);
- } else {
- this.length = lengthAfterRemove + add; // reserves space
- for (i = 0; i < add; ++i) {
- this[pos+i] = insert[i];
- }
- }
- }
- return removed;
- };
- }
-}
-if (!Array.isArray) {
- Array.isArray = function isArray(obj) {
- return _toString(obj) == "[object Array]";
- };
-}
-var boxedString = Object("a"),
- splitString = boxedString[0] != "a" || !(0 in boxedString);
-
-if (!Array.prototype.forEach) {
- Array.prototype.forEach = function forEach(fun /*, thisp*/) {
- var object = toObject(this),
- self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- object,
- thisp = arguments[1],
- i = -1,
- length = self.length >>> 0;
- if (_toString(fun) != "[object Function]") {
- throw new TypeError(); // TODO message
- }
-
- while (++i < length) {
- if (i in self) {
- fun.call(thisp, self[i], i, object);
- }
- }
- };
-}
-if (!Array.prototype.map) {
- Array.prototype.map = function map(fun /*, thisp*/) {
- var object = toObject(this),
- self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- object,
- length = self.length >>> 0,
- result = Array(length),
- thisp = arguments[1];
- if (_toString(fun) != "[object Function]") {
- throw new TypeError(fun + " is not a function");
- }
-
- for (var i = 0; i < length; i++) {
- if (i in self)
- result[i] = fun.call(thisp, self[i], i, object);
- }
- return result;
- };
-}
-if (!Array.prototype.filter) {
- Array.prototype.filter = function filter(fun /*, thisp */) {
- var object = toObject(this),
- self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- object,
- length = self.length >>> 0,
- result = [],
- value,
- thisp = arguments[1];
- if (_toString(fun) != "[object Function]") {
- throw new TypeError(fun + " is not a function");
- }
-
- for (var i = 0; i < length; i++) {
- if (i in self) {
- value = self[i];
- if (fun.call(thisp, value, i, object)) {
- result.push(value);
- }
- }
- }
- return result;
- };
-}
-if (!Array.prototype.every) {
- Array.prototype.every = function every(fun /*, thisp */) {
- var object = toObject(this),
- self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- object,
- length = self.length >>> 0,
- thisp = arguments[1];
- if (_toString(fun) != "[object Function]") {
- throw new TypeError(fun + " is not a function");
- }
-
- for (var i = 0; i < length; i++) {
- if (i in self && !fun.call(thisp, self[i], i, object)) {
- return false;
- }
- }
- return true;
- };
-}
-if (!Array.prototype.some) {
- Array.prototype.some = function some(fun /*, thisp */) {
- var object = toObject(this),
- self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- object,
- length = self.length >>> 0,
- thisp = arguments[1];
- if (_toString(fun) != "[object Function]") {
- throw new TypeError(fun + " is not a function");
- }
-
- for (var i = 0; i < length; i++) {
- if (i in self && fun.call(thisp, self[i], i, object)) {
- return true;
- }
- }
- return false;
- };
-}
-if (!Array.prototype.reduce) {
- Array.prototype.reduce = function reduce(fun /*, initial*/) {
- var object = toObject(this),
- self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- object,
- length = self.length >>> 0;
- if (_toString(fun) != "[object Function]") {
- throw new TypeError(fun + " is not a function");
- }
- if (!length && arguments.length == 1) {
- throw new TypeError("reduce of empty array with no initial value");
- }
-
- var i = 0;
- var result;
- if (arguments.length >= 2) {
- result = arguments[1];
- } else {
- do {
- if (i in self) {
- result = self[i++];
- break;
- }
- if (++i >= length) {
- throw new TypeError("reduce of empty array with no initial value");
- }
- } while (true);
- }
-
- for (; i < length; i++) {
- if (i in self) {
- result = fun.call(void 0, result, self[i], i, object);
- }
- }
-
- return result;
- };
-}
-if (!Array.prototype.reduceRight) {
- Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
- var object = toObject(this),
- self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- object,
- length = self.length >>> 0;
- if (_toString(fun) != "[object Function]") {
- throw new TypeError(fun + " is not a function");
- }
- if (!length && arguments.length == 1) {
- throw new TypeError("reduceRight of empty array with no initial value");
- }
-
- var result, i = length - 1;
- if (arguments.length >= 2) {
- result = arguments[1];
- } else {
- do {
- if (i in self) {
- result = self[i--];
- break;
- }
- if (--i < 0) {
- throw new TypeError("reduceRight of empty array with no initial value");
- }
- } while (true);
- }
-
- do {
- if (i in this) {
- result = fun.call(void 0, result, self[i], i, object);
- }
- } while (i--);
-
- return result;
- };
-}
-if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) {
- Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
- var self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- toObject(this),
- length = self.length >>> 0;
-
- if (!length) {
- return -1;
- }
-
- var i = 0;
- if (arguments.length > 1) {
- i = toInteger(arguments[1]);
- }
- i = i >= 0 ? i : Math.max(0, length + i);
- for (; i < length; i++) {
- if (i in self && self[i] === sought) {
- return i;
- }
- }
- return -1;
- };
-}
-if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) {
- Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
- var self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- toObject(this),
- length = self.length >>> 0;
-
- if (!length) {
- return -1;
- }
- var i = length - 1;
- if (arguments.length > 1) {
- i = Math.min(i, toInteger(arguments[1]));
- }
- i = i >= 0 ? i : length - Math.abs(i);
- for (; i >= 0; i--) {
- if (i in self && sought === self[i]) {
- return i;
- }
- }
- return -1;
- };
-}
-if (!Object.getPrototypeOf) {
- Object.getPrototypeOf = function getPrototypeOf(object) {
- return object.__proto__ || (
- object.constructor ?
- object.constructor.prototype :
- prototypeOfObject
- );
- };
-}
-if (!Object.getOwnPropertyDescriptor) {
- var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " +
- "non-object: ";
- Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
- if ((typeof object != "object" && typeof object != "function") || object === null)
- throw new TypeError(ERR_NON_OBJECT + object);
- if (!owns(object, property))
- return;
-
- var descriptor, getter, setter;
- descriptor = { enumerable: true, configurable: true };
- if (supportsAccessors) {
- var prototype = object.__proto__;
- object.__proto__ = prototypeOfObject;
-
- var getter = lookupGetter(object, property);
- var setter = lookupSetter(object, property);
- object.__proto__ = prototype;
-
- if (getter || setter) {
- if (getter) descriptor.get = getter;
- if (setter) descriptor.set = setter;
- return descriptor;
- }
- }
- descriptor.value = object[property];
- return descriptor;
- };
-}
-if (!Object.getOwnPropertyNames) {
- Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
- return Object.keys(object);
- };
-}
-if (!Object.create) {
- var createEmpty;
- if (Object.prototype.__proto__ === null) {
- createEmpty = function () {
- return { "__proto__": null };
- };
- } else {
- createEmpty = function () {
- var empty = {};
- for (var i in empty)
- empty[i] = null;
- empty.constructor =
- empty.hasOwnProperty =
- empty.propertyIsEnumerable =
- empty.isPrototypeOf =
- empty.toLocaleString =
- empty.toString =
- empty.valueOf =
- empty.__proto__ = null;
- return empty;
- }
- }
-
- Object.create = function create(prototype, properties) {
- var object;
- if (prototype === null) {
- object = createEmpty();
- } else {
- if (typeof prototype != "object")
- throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
- var Type = function () {};
- Type.prototype = prototype;
- object = new Type();
- object.__proto__ = prototype;
- }
- if (properties !== void 0)
- Object.defineProperties(object, properties);
- return object;
- };
-}
-
-function doesDefinePropertyWork(object) {
- try {
- Object.defineProperty(object, "sentinel", {});
- return "sentinel" in object;
- } catch (exception) {
- }
-}
-if (Object.defineProperty) {
- var definePropertyWorksOnObject = doesDefinePropertyWork({});
- var definePropertyWorksOnDom = typeof document == "undefined" ||
- doesDefinePropertyWork(document.createElement("div"));
- if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
- var definePropertyFallback = Object.defineProperty;
- }
-}
-
-if (!Object.defineProperty || definePropertyFallback) {
- var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
- var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
- var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
- "on this javascript engine";
-
- Object.defineProperty = function defineProperty(object, property, descriptor) {
- if ((typeof object != "object" && typeof object != "function") || object === null)
- throw new TypeError(ERR_NON_OBJECT_TARGET + object);
- if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null)
- throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
- if (definePropertyFallback) {
- try {
- return definePropertyFallback.call(Object, object, property, descriptor);
- } catch (exception) {
- }
- }
- if (owns(descriptor, "value")) {
-
- if (supportsAccessors && (lookupGetter(object, property) ||
- lookupSetter(object, property)))
- {
- var prototype = object.__proto__;
- object.__proto__ = prototypeOfObject;
- delete object[property];
- object[property] = descriptor.value;
- object.__proto__ = prototype;
- } else {
- object[property] = descriptor.value;
- }
- } else {
- if (!supportsAccessors)
- throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
- if (owns(descriptor, "get"))
- defineGetter(object, property, descriptor.get);
- if (owns(descriptor, "set"))
- defineSetter(object, property, descriptor.set);
- }
-
- return object;
- };
-}
-if (!Object.defineProperties) {
- Object.defineProperties = function defineProperties(object, properties) {
- for (var property in properties) {
- if (owns(properties, property))
- Object.defineProperty(object, property, properties[property]);
- }
- return object;
- };
-}
-if (!Object.seal) {
- Object.seal = function seal(object) {
- return object;
- };
-}
-if (!Object.freeze) {
- Object.freeze = function freeze(object) {
- return object;
- };
-}
-try {
- Object.freeze(function () {});
-} catch (exception) {
- Object.freeze = (function freeze(freezeObject) {
- return function freeze(object) {
- if (typeof object == "function") {
- return object;
- } else {
- return freezeObject(object);
- }
- };
- })(Object.freeze);
-}
-if (!Object.preventExtensions) {
- Object.preventExtensions = function preventExtensions(object) {
- return object;
- };
-}
-if (!Object.isSealed) {
- Object.isSealed = function isSealed(object) {
- return false;
- };
-}
-if (!Object.isFrozen) {
- Object.isFrozen = function isFrozen(object) {
- return false;
- };
-}
-if (!Object.isExtensible) {
- Object.isExtensible = function isExtensible(object) {
- if (Object(object) === object) {
- throw new TypeError(); // TODO message
- }
- var name = '';
- while (owns(object, name)) {
- name += '?';
- }
- object[name] = true;
- var returnValue = owns(object, name);
- delete object[name];
- return returnValue;
- };
-}
-if (!Object.keys) {
- var hasDontEnumBug = true,
- dontEnums = [
- "toString",
- "toLocaleString",
- "valueOf",
- "hasOwnProperty",
- "isPrototypeOf",
- "propertyIsEnumerable",
- "constructor"
- ],
- dontEnumsLength = dontEnums.length;
-
- for (var key in {"toString": null}) {
- hasDontEnumBug = false;
- }
-
- Object.keys = function keys(object) {
-
- if (
- (typeof object != "object" && typeof object != "function") ||
- object === null
- ) {
- throw new TypeError("Object.keys called on a non-object");
- }
-
- var keys = [];
- for (var name in object) {
- if (owns(object, name)) {
- keys.push(name);
- }
- }
-
- if (hasDontEnumBug) {
- for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
- var dontEnum = dontEnums[i];
- if (owns(object, dontEnum)) {
- keys.push(dontEnum);
- }
- }
- }
- return keys;
- };
-
-}
-if (!Date.now) {
- Date.now = function now() {
- return new Date().getTime();
- };
-}
-var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
- "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
- "\u2029\uFEFF";
-if (!String.prototype.trim || ws.trim()) {
- ws = "[" + ws + "]";
- var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
- trimEndRegexp = new RegExp(ws + ws + "*$");
- String.prototype.trim = function trim() {
- return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, "");
- };
-}
-
-function toInteger(n) {
- n = +n;
- if (n !== n) { // isNaN
- n = 0;
- } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) {
- n = (n > 0 || -1) * Math.floor(Math.abs(n));
- }
- return n;
-}
-
-function isPrimitive(input) {
- var type = typeof input;
- return (
- input === null ||
- type === "undefined" ||
- type === "boolean" ||
- type === "number" ||
- type === "string"
- );
-}
-
-function toPrimitive(input) {
- var val, valueOf, toString;
- if (isPrimitive(input)) {
- return input;
- }
- valueOf = input.valueOf;
- if (typeof valueOf === "function") {
- val = valueOf.call(input);
- if (isPrimitive(val)) {
- return val;
- }
- }
- toString = input.toString;
- if (typeof toString === "function") {
- val = toString.call(input);
- if (isPrimitive(val)) {
- return val;
- }
- }
- throw new TypeError();
-}
-var toObject = function (o) {
- if (o == null) { // this matches both null and undefined
- throw new TypeError("can't convert "+o+" to object");
- }
- return Object(o);
-};
-
-});
-
-ace.define("ace/lib/fixoldbrowsers",["require","exports","module","ace/lib/regexp","ace/lib/es5-shim"], function(require, exports, module) {
-"use strict";
-
-require("./regexp");
-require("./es5-shim");
-
-});
-
-ace.define("ace/lib/dom",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-var XHTML_NS = "http://www.w3.org/1999/xhtml";
-
-exports.getDocumentHead = function(doc) {
- if (!doc)
- doc = document;
- return doc.head || doc.getElementsByTagName("head")[0] || doc.documentElement;
-};
-
-exports.createElement = function(tag, ns) {
- return document.createElementNS ?
- document.createElementNS(ns || XHTML_NS, tag) :
- document.createElement(tag);
-};
-
-exports.hasCssClass = function(el, name) {
- var classes = (el.className || "").split(/\s+/g);
- return classes.indexOf(name) !== -1;
-};
-exports.addCssClass = function(el, name) {
- if (!exports.hasCssClass(el, name)) {
- el.className += " " + name;
- }
-};
-exports.removeCssClass = function(el, name) {
- var classes = el.className.split(/\s+/g);
- while (true) {
- var index = classes.indexOf(name);
- if (index == -1) {
- break;
- }
- classes.splice(index, 1);
- }
- el.className = classes.join(" ");
-};
-
-exports.toggleCssClass = function(el, name) {
- var classes = el.className.split(/\s+/g), add = true;
- while (true) {
- var index = classes.indexOf(name);
- if (index == -1) {
- break;
- }
- add = false;
- classes.splice(index, 1);
- }
- if (add)
- classes.push(name);
-
- el.className = classes.join(" ");
- return add;
-};
-exports.setCssClass = function(node, className, include) {
- if (include) {
- exports.addCssClass(node, className);
- } else {
- exports.removeCssClass(node, className);
- }
-};
-
-exports.hasCssString = function(id, doc) {
- var index = 0, sheets;
- doc = doc || document;
-
- if (doc.createStyleSheet && (sheets = doc.styleSheets)) {
- while (index < sheets.length)
- if (sheets[index++].owningElement.id === id) return true;
- } else if ((sheets = doc.getElementsByTagName("style"))) {
- while (index < sheets.length)
- if (sheets[index++].id === id) return true;
- }
-
- return false;
-};
-
-exports.importCssString = function importCssString(cssText, id, doc) {
- doc = doc || document;
- if (id && exports.hasCssString(id, doc))
- return null;
-
- var style;
-
- if (id)
- cssText += "\n/*# sourceURL=ace/css/" + id + " */";
-
- if (doc.createStyleSheet) {
- style = doc.createStyleSheet();
- style.cssText = cssText;
- if (id)
- style.owningElement.id = id;
- } else {
- style = exports.createElement("style");
- style.appendChild(doc.createTextNode(cssText));
- if (id)
- style.id = id;
-
- exports.getDocumentHead(doc).appendChild(style);
- }
-};
-
-exports.importCssStylsheet = function(uri, doc) {
- if (doc.createStyleSheet) {
- doc.createStyleSheet(uri);
- } else {
- var link = exports.createElement('link');
- link.rel = 'stylesheet';
- link.href = uri;
-
- exports.getDocumentHead(doc).appendChild(link);
- }
-};
-
-exports.getInnerWidth = function(element) {
- return (
- parseInt(exports.computedStyle(element, "paddingLeft"), 10) +
- parseInt(exports.computedStyle(element, "paddingRight"), 10) +
- element.clientWidth
- );
-};
-
-exports.getInnerHeight = function(element) {
- return (
- parseInt(exports.computedStyle(element, "paddingTop"), 10) +
- parseInt(exports.computedStyle(element, "paddingBottom"), 10) +
- element.clientHeight
- );
-};
-
-exports.scrollbarWidth = function(document) {
- var inner = exports.createElement("ace_inner");
- inner.style.width = "100%";
- inner.style.minWidth = "0px";
- inner.style.height = "200px";
- inner.style.display = "block";
-
- var outer = exports.createElement("ace_outer");
- var style = outer.style;
-
- style.position = "absolute";
- style.left = "-10000px";
- style.overflow = "hidden";
- style.width = "200px";
- style.minWidth = "0px";
- style.height = "150px";
- style.display = "block";
-
- outer.appendChild(inner);
-
- var body = document.documentElement;
- body.appendChild(outer);
-
- var noScrollbar = inner.offsetWidth;
-
- style.overflow = "scroll";
- var withScrollbar = inner.offsetWidth;
-
- if (noScrollbar == withScrollbar) {
- withScrollbar = outer.clientWidth;
- }
-
- body.removeChild(outer);
-
- return noScrollbar-withScrollbar;
-};
-
-if (typeof document == "undefined") {
- exports.importCssString = function() {};
- return;
-}
-
-if (window.pageYOffset !== undefined) {
- exports.getPageScrollTop = function() {
- return window.pageYOffset;
- };
-
- exports.getPageScrollLeft = function() {
- return window.pageXOffset;
- };
-}
-else {
- exports.getPageScrollTop = function() {
- return document.body.scrollTop;
- };
-
- exports.getPageScrollLeft = function() {
- return document.body.scrollLeft;
- };
-}
-
-if (window.getComputedStyle)
- exports.computedStyle = function(element, style) {
- if (style)
- return (window.getComputedStyle(element, "") || {})[style] || "";
- return window.getComputedStyle(element, "") || {};
- };
-else
- exports.computedStyle = function(element, style) {
- if (style)
- return element.currentStyle[style];
- return element.currentStyle;
- };
-exports.setInnerHtml = function(el, innerHtml) {
- var element = el.cloneNode(false);//document.createElement("div");
- element.innerHTML = innerHtml;
- el.parentNode.replaceChild(element, el);
- return element;
-};
-
-if ("textContent" in document.documentElement) {
- exports.setInnerText = function(el, innerText) {
- el.textContent = innerText;
- };
-
- exports.getInnerText = function(el) {
- return el.textContent;
- };
-}
-else {
- exports.setInnerText = function(el, innerText) {
- el.innerText = innerText;
- };
-
- exports.getInnerText = function(el) {
- return el.innerText;
- };
-}
-
-exports.getParentWindow = function(document) {
- return document.defaultView || document.parentWindow;
-};
-
-});
-
-ace.define("ace/lib/oop",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-exports.inherits = function(ctor, superCtor) {
- ctor.super_ = superCtor;
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
-};
-
-exports.mixin = function(obj, mixin) {
- for (var key in mixin) {
- obj[key] = mixin[key];
- }
- return obj;
-};
-
-exports.implement = function(proto, mixin) {
- exports.mixin(proto, mixin);
-};
-
-});
-
-ace.define("ace/lib/keys",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop"], function(require, exports, module) {
-"use strict";
-
-require("./fixoldbrowsers");
-
-var oop = require("./oop");
-var Keys = (function() {
- var ret = {
- MODIFIER_KEYS: {
- 16: 'Shift', 17: 'Ctrl', 18: 'Alt', 224: 'Meta'
- },
-
- KEY_MODS: {
- "ctrl": 1, "alt": 2, "option" : 2, "shift": 4,
- "super": 8, "meta": 8, "command": 8, "cmd": 8
- },
-
- FUNCTION_KEYS : {
- 8 : "Backspace",
- 9 : "Tab",
- 13 : "Return",
- 19 : "Pause",
- 27 : "Esc",
- 32 : "Space",
- 33 : "PageUp",
- 34 : "PageDown",
- 35 : "End",
- 36 : "Home",
- 37 : "Left",
- 38 : "Up",
- 39 : "Right",
- 40 : "Down",
- 44 : "Print",
- 45 : "Insert",
- 46 : "Delete",
- 96 : "Numpad0",
- 97 : "Numpad1",
- 98 : "Numpad2",
- 99 : "Numpad3",
- 100: "Numpad4",
- 101: "Numpad5",
- 102: "Numpad6",
- 103: "Numpad7",
- 104: "Numpad8",
- 105: "Numpad9",
- '-13': "NumpadEnter",
- 112: "F1",
- 113: "F2",
- 114: "F3",
- 115: "F4",
- 116: "F5",
- 117: "F6",
- 118: "F7",
- 119: "F8",
- 120: "F9",
- 121: "F10",
- 122: "F11",
- 123: "F12",
- 144: "Numlock",
- 145: "Scrolllock"
- },
-
- PRINTABLE_KEYS: {
- 32: ' ', 48: '0', 49: '1', 50: '2', 51: '3', 52: '4', 53: '5',
- 54: '6', 55: '7', 56: '8', 57: '9', 59: ';', 61: '=', 65: 'a',
- 66: 'b', 67: 'c', 68: 'd', 69: 'e', 70: 'f', 71: 'g', 72: 'h',
- 73: 'i', 74: 'j', 75: 'k', 76: 'l', 77: 'm', 78: 'n', 79: 'o',
- 80: 'p', 81: 'q', 82: 'r', 83: 's', 84: 't', 85: 'u', 86: 'v',
- 87: 'w', 88: 'x', 89: 'y', 90: 'z', 107: '+', 109: '-', 110: '.',
- 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`',
- 219: '[', 220: '\\',221: ']', 222: "'", 111: '/', 106: '*'
- }
- };
- var name, i;
- for (i in ret.FUNCTION_KEYS) {
- name = ret.FUNCTION_KEYS[i].toLowerCase();
- ret[name] = parseInt(i, 10);
- }
- for (i in ret.PRINTABLE_KEYS) {
- name = ret.PRINTABLE_KEYS[i].toLowerCase();
- ret[name] = parseInt(i, 10);
- }
- oop.mixin(ret, ret.MODIFIER_KEYS);
- oop.mixin(ret, ret.PRINTABLE_KEYS);
- oop.mixin(ret, ret.FUNCTION_KEYS);
- ret.enter = ret["return"];
- ret.escape = ret.esc;
- ret.del = ret["delete"];
- ret[173] = '-';
-
- (function() {
- var mods = ["cmd", "ctrl", "alt", "shift"];
- for (var i = Math.pow(2, mods.length); i--;) {
- ret.KEY_MODS[i] = mods.filter(function(x) {
- return i & ret.KEY_MODS[x];
- }).join("-") + "-";
- }
- })();
-
- ret.KEY_MODS[0] = "";
- ret.KEY_MODS[-1] = "input-";
-
- return ret;
-})();
-oop.mixin(exports, Keys);
-
-exports.keyCodeToString = function(keyCode) {
- var keyString = Keys[keyCode];
- if (typeof keyString != "string")
- keyString = String.fromCharCode(keyCode);
- return keyString.toLowerCase();
-};
-
-});
-
-ace.define("ace/lib/useragent",["require","exports","module"], function(require, exports, module) {
-"use strict";
-exports.OS = {
- LINUX: "LINUX",
- MAC: "MAC",
- WINDOWS: "WINDOWS"
-};
-exports.getOS = function() {
- if (exports.isMac) {
- return exports.OS.MAC;
- } else if (exports.isLinux) {
- return exports.OS.LINUX;
- } else {
- return exports.OS.WINDOWS;
- }
-};
-if (typeof navigator != "object")
- return;
-
-var os = (navigator.platform.match(/mac|win|linux/i) || ["other"])[0].toLowerCase();
-var ua = navigator.userAgent;
-exports.isWin = (os == "win");
-exports.isMac = (os == "mac");
-exports.isLinux = (os == "linux");
-exports.isIE =
- (navigator.appName == "Microsoft Internet Explorer" || navigator.appName.indexOf("MSAppHost") >= 0)
- ? parseFloat((ua.match(/(?:MSIE |Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1])
- : parseFloat((ua.match(/(?:Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1]); // for ie
-
-exports.isOldIE = exports.isIE && exports.isIE < 9;
-exports.isGecko = exports.isMozilla = (window.Controllers || window.controllers) && window.navigator.product === "Gecko";
-exports.isOldGecko = exports.isGecko && parseInt((ua.match(/rv\:(\d+)/)||[])[1], 10) < 4;
-exports.isOpera = window.opera && Object.prototype.toString.call(window.opera) == "[object Opera]";
-exports.isWebKit = parseFloat(ua.split("WebKit/")[1]) || undefined;
-
-exports.isChrome = parseFloat(ua.split(" Chrome/")[1]) || undefined;
-
-exports.isAIR = ua.indexOf("AdobeAIR") >= 0;
-
-exports.isIPad = ua.indexOf("iPad") >= 0;
-
-exports.isTouchPad = ua.indexOf("TouchPad") >= 0;
-
-exports.isChromeOS = ua.indexOf(" CrOS ") >= 0;
-
-});
-
-ace.define("ace/lib/event",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(require, exports, module) {
-"use strict";
-
-var keys = require("./keys");
-var useragent = require("./useragent");
-
-var pressedKeys = null;
-var ts = 0;
-
-exports.addListener = function(elem, type, callback) {
- if (elem.addEventListener) {
- return elem.addEventListener(type, callback, false);
- }
- if (elem.attachEvent) {
- var wrapper = function() {
- callback.call(elem, window.event);
- };
- callback._wrapper = wrapper;
- elem.attachEvent("on" + type, wrapper);
- }
-};
-
-exports.removeListener = function(elem, type, callback) {
- if (elem.removeEventListener) {
- return elem.removeEventListener(type, callback, false);
- }
- if (elem.detachEvent) {
- elem.detachEvent("on" + type, callback._wrapper || callback);
- }
-};
-exports.stopEvent = function(e) {
- exports.stopPropagation(e);
- exports.preventDefault(e);
- return false;
-};
-
-exports.stopPropagation = function(e) {
- if (e.stopPropagation)
- e.stopPropagation();
- else
- e.cancelBubble = true;
-};
-
-exports.preventDefault = function(e) {
- if (e.preventDefault)
- e.preventDefault();
- else
- e.returnValue = false;
-};
-exports.getButton = function(e) {
- if (e.type == "dblclick")
- return 0;
- if (e.type == "contextmenu" || (useragent.isMac && (e.ctrlKey && !e.altKey && !e.shiftKey)))
- return 2;
- if (e.preventDefault) {
- return e.button;
- }
- else {
- return {1:0, 2:2, 4:1}[e.button];
- }
-};
-
-exports.capture = function(el, eventHandler, releaseCaptureHandler) {
- function onMouseUp(e) {
- eventHandler && eventHandler(e);
- releaseCaptureHandler && releaseCaptureHandler(e);
-
- exports.removeListener(document, "mousemove", eventHandler, true);
- exports.removeListener(document, "mouseup", onMouseUp, true);
- exports.removeListener(document, "dragstart", onMouseUp, true);
- }
-
- exports.addListener(document, "mousemove", eventHandler, true);
- exports.addListener(document, "mouseup", onMouseUp, true);
- exports.addListener(document, "dragstart", onMouseUp, true);
-
- return onMouseUp;
-};
-
-exports.addTouchMoveListener = function (el, callback) {
- if ("ontouchmove" in el) {
- var startx, starty;
- exports.addListener(el, "touchstart", function (e) {
- var touchObj = e.changedTouches[0];
- startx = touchObj.clientX;
- starty = touchObj.clientY;
- });
- exports.addListener(el, "touchmove", function (e) {
- var factor = 1,
- touchObj = e.changedTouches[0];
-
- e.wheelX = -(touchObj.clientX - startx) / factor;
- e.wheelY = -(touchObj.clientY - starty) / factor;
-
- startx = touchObj.clientX;
- starty = touchObj.clientY;
-
- callback(e);
- });
- }
-};
-
-exports.addMouseWheelListener = function(el, callback) {
- if ("onmousewheel" in el) {
- exports.addListener(el, "mousewheel", function(e) {
- var factor = 8;
- if (e.wheelDeltaX !== undefined) {
- e.wheelX = -e.wheelDeltaX / factor;
- e.wheelY = -e.wheelDeltaY / factor;
- } else {
- e.wheelX = 0;
- e.wheelY = -e.wheelDelta / factor;
- }
- callback(e);
- });
- } else if ("onwheel" in el) {
- exports.addListener(el, "wheel", function(e) {
- var factor = 0.35;
- switch (e.deltaMode) {
- case e.DOM_DELTA_PIXEL:
- e.wheelX = e.deltaX * factor || 0;
- e.wheelY = e.deltaY * factor || 0;
- break;
- case e.DOM_DELTA_LINE:
- case e.DOM_DELTA_PAGE:
- e.wheelX = (e.deltaX || 0) * 5;
- e.wheelY = (e.deltaY || 0) * 5;
- break;
- }
-
- callback(e);
- });
- } else {
- exports.addListener(el, "DOMMouseScroll", function(e) {
- if (e.axis && e.axis == e.HORIZONTAL_AXIS) {
- e.wheelX = (e.detail || 0) * 5;
- e.wheelY = 0;
- } else {
- e.wheelX = 0;
- e.wheelY = (e.detail || 0) * 5;
- }
- callback(e);
- });
- }
-};
-
-exports.addMultiMouseDownListener = function(elements, timeouts, eventHandler, callbackName) {
- var clicks = 0;
- var startX, startY, timer;
- var eventNames = {
- 2: "dblclick",
- 3: "tripleclick",
- 4: "quadclick"
- };
-
- function onMousedown(e) {
- if (exports.getButton(e) !== 0) {
- clicks = 0;
- } else if (e.detail > 1) {
- clicks++;
- if (clicks > 4)
- clicks = 1;
- } else {
- clicks = 1;
- }
- if (useragent.isIE) {
- var isNewClick = Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5;
- if (!timer || isNewClick)
- clicks = 1;
- if (timer)
- clearTimeout(timer);
- timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600);
-
- if (clicks == 1) {
- startX = e.clientX;
- startY = e.clientY;
- }
- }
-
- e._clicks = clicks;
-
- eventHandler[callbackName]("mousedown", e);
-
- if (clicks > 4)
- clicks = 0;
- else if (clicks > 1)
- return eventHandler[callbackName](eventNames[clicks], e);
- }
- function onDblclick(e) {
- clicks = 2;
- if (timer)
- clearTimeout(timer);
- timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600);
- eventHandler[callbackName]("mousedown", e);
- eventHandler[callbackName](eventNames[clicks], e);
- }
- if (!Array.isArray(elements))
- elements = [elements];
- elements.forEach(function(el) {
- exports.addListener(el, "mousedown", onMousedown);
- if (useragent.isOldIE)
- exports.addListener(el, "dblclick", onDblclick);
- });
-};
-
-var getModifierHash = useragent.isMac && useragent.isOpera && !("KeyboardEvent" in window)
- ? function(e) {
- return 0 | (e.metaKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.ctrlKey ? 8 : 0);
- }
- : function(e) {
- return 0 | (e.ctrlKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.metaKey ? 8 : 0);
- };
-
-exports.getModifierString = function(e) {
- return keys.KEY_MODS[getModifierHash(e)];
-};
-
-function normalizeCommandKeys(callback, e, keyCode) {
- var hashId = getModifierHash(e);
-
- if (!useragent.isMac && pressedKeys) {
- if (pressedKeys.OSKey)
- hashId |= 8;
- if (pressedKeys.altGr) {
- if ((3 & hashId) != 3)
- pressedKeys.altGr = 0;
- else
- return;
- }
- if (keyCode === 18 || keyCode === 17) {
- var location = "location" in e ? e.location : e.keyLocation;
- if (keyCode === 17 && location === 1) {
- if (pressedKeys[keyCode] == 1)
- ts = e.timeStamp;
- } else if (keyCode === 18 && hashId === 3 && location === 2) {
- var dt = e.timeStamp - ts;
- if (dt < 50)
- pressedKeys.altGr = true;
- }
- }
- }
-
- if (keyCode in keys.MODIFIER_KEYS) {
- keyCode = -1;
- }
- if (hashId & 8 && (keyCode >= 91 && keyCode <= 93)) {
- keyCode = -1;
- }
-
- if (!hashId && keyCode === 13) {
- var location = "location" in e ? e.location : e.keyLocation;
- if (location === 3) {
- callback(e, hashId, -keyCode);
- if (e.defaultPrevented)
- return;
- }
- }
-
- if (useragent.isChromeOS && hashId & 8) {
- callback(e, hashId, keyCode);
- if (e.defaultPrevented)
- return;
- else
- hashId &= ~8;
- }
- if (!hashId && !(keyCode in keys.FUNCTION_KEYS) && !(keyCode in keys.PRINTABLE_KEYS)) {
- return false;
- }
-
- return callback(e, hashId, keyCode);
-}
-
-
-exports.addCommandKeyListener = function(el, callback) {
- var addListener = exports.addListener;
- if (useragent.isOldGecko || (useragent.isOpera && !("KeyboardEvent" in window))) {
- var lastKeyDownKeyCode = null;
- addListener(el, "keydown", function(e) {
- lastKeyDownKeyCode = e.keyCode;
- });
- addListener(el, "keypress", function(e) {
- return normalizeCommandKeys(callback, e, lastKeyDownKeyCode);
- });
- } else {
- var lastDefaultPrevented = null;
-
- addListener(el, "keydown", function(e) {
- var keyCode = e.keyCode;
- pressedKeys[keyCode] = (pressedKeys[keyCode] || 0) + 1;
- if (keyCode == 91 || keyCode == 92) {
- pressedKeys.OSKey = true;
- } else if (pressedKeys.OSKey) {
- if (e.timeStamp - pressedKeys.lastT > 200 && pressedKeys.count == 1)
- resetPressedKeys();
- }
- if (pressedKeys[keyCode] == 1)
- pressedKeys.count++;
- pressedKeys.lastT = e.timeStamp;
- var result = normalizeCommandKeys(callback, e, keyCode);
- lastDefaultPrevented = e.defaultPrevented;
- return result;
- });
-
- addListener(el, "keypress", function(e) {
- if (lastDefaultPrevented && (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)) {
- exports.stopEvent(e);
- lastDefaultPrevented = null;
- }
- });
-
- addListener(el, "keyup", function(e) {
- var keyCode = e.keyCode;
- if (!pressedKeys[keyCode]) {
- resetPressedKeys();
- } else {
- pressedKeys.count = Math.max(pressedKeys.count - 1, 0);
- }
- if (keyCode == 91 || keyCode == 92) {
- pressedKeys.OSKey = false;
- }
- pressedKeys[keyCode] = null;
- });
-
- if (!pressedKeys) {
- resetPressedKeys();
- addListener(window, "focus", resetPressedKeys);
- }
- }
-};
-function resetPressedKeys() {
- pressedKeys = Object.create(null);
- pressedKeys.count = 0;
- pressedKeys.lastT = 0;
-}
-
-if (typeof window == "object" && window.postMessage && !useragent.isOldIE) {
- var postMessageId = 1;
- exports.nextTick = function(callback, win) {
- win = win || window;
- var messageName = "zero-timeout-message-" + postMessageId;
- exports.addListener(win, "message", function listener(e) {
- if (e.data == messageName) {
- exports.stopPropagation(e);
- exports.removeListener(win, "message", listener);
- callback();
- }
- });
- win.postMessage(messageName, "*");
- };
-}
-
-
-exports.nextFrame = typeof window == "object" && (window.requestAnimationFrame
- || window.mozRequestAnimationFrame
- || window.webkitRequestAnimationFrame
- || window.msRequestAnimationFrame
- || window.oRequestAnimationFrame);
-
-if (exports.nextFrame)
- exports.nextFrame = exports.nextFrame.bind(window);
-else
- exports.nextFrame = function(callback) {
- setTimeout(callback, 17);
- };
-});
-
-ace.define("ace/lib/lang",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-exports.last = function(a) {
- return a[a.length - 1];
-};
-
-exports.stringReverse = function(string) {
- return string.split("").reverse().join("");
-};
-
-exports.stringRepeat = function (string, count) {
- var result = '';
- while (count > 0) {
- if (count & 1)
- result += string;
-
- if (count >>= 1)
- string += string;
- }
- return result;
-};
-
-var trimBeginRegexp = /^\s\s*/;
-var trimEndRegexp = /\s\s*$/;
-
-exports.stringTrimLeft = function (string) {
- return string.replace(trimBeginRegexp, '');
-};
-
-exports.stringTrimRight = function (string) {
- return string.replace(trimEndRegexp, '');
-};
-
-exports.copyObject = function(obj) {
- var copy = {};
- for (var key in obj) {
- copy[key] = obj[key];
- }
- return copy;
-};
-
-exports.copyArray = function(array){
- var copy = [];
- for (var i=0, l=array.length; i 1);
- return ev.preventDefault();
- };
-
- this.startSelect = function(pos, waitForClickSelection) {
- pos = pos || this.editor.renderer.screenToTextCoordinates(this.x, this.y);
- var editor = this.editor;
- editor.$blockScrolling++;
- if (this.mousedownEvent.getShiftKey())
- editor.selection.selectToPosition(pos);
- else if (!waitForClickSelection)
- editor.selection.moveToPosition(pos);
- if (!waitForClickSelection)
- this.select();
- if (editor.renderer.scroller.setCapture) {
- editor.renderer.scroller.setCapture();
- }
- editor.setStyle("ace_selecting");
- this.setState("select");
- editor.$blockScrolling--;
- };
-
- this.select = function() {
- var anchor, editor = this.editor;
- var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y);
- editor.$blockScrolling++;
- if (this.$clickSelection) {
- var cmp = this.$clickSelection.comparePoint(cursor);
-
- if (cmp == -1) {
- anchor = this.$clickSelection.end;
- } else if (cmp == 1) {
- anchor = this.$clickSelection.start;
- } else {
- var orientedRange = calcRangeOrientation(this.$clickSelection, cursor);
- cursor = orientedRange.cursor;
- anchor = orientedRange.anchor;
- }
- editor.selection.setSelectionAnchor(anchor.row, anchor.column);
- }
- editor.selection.selectToPosition(cursor);
- editor.$blockScrolling--;
- editor.renderer.scrollCursorIntoView();
- };
-
- this.extendSelectionBy = function(unitName) {
- var anchor, editor = this.editor;
- var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y);
- var range = editor.selection[unitName](cursor.row, cursor.column);
- editor.$blockScrolling++;
- if (this.$clickSelection) {
- var cmpStart = this.$clickSelection.comparePoint(range.start);
- var cmpEnd = this.$clickSelection.comparePoint(range.end);
-
- if (cmpStart == -1 && cmpEnd <= 0) {
- anchor = this.$clickSelection.end;
- if (range.end.row != cursor.row || range.end.column != cursor.column)
- cursor = range.start;
- } else if (cmpEnd == 1 && cmpStart >= 0) {
- anchor = this.$clickSelection.start;
- if (range.start.row != cursor.row || range.start.column != cursor.column)
- cursor = range.end;
- } else if (cmpStart == -1 && cmpEnd == 1) {
- cursor = range.end;
- anchor = range.start;
- } else {
- var orientedRange = calcRangeOrientation(this.$clickSelection, cursor);
- cursor = orientedRange.cursor;
- anchor = orientedRange.anchor;
- }
- editor.selection.setSelectionAnchor(anchor.row, anchor.column);
- }
- editor.selection.selectToPosition(cursor);
- editor.$blockScrolling--;
- editor.renderer.scrollCursorIntoView();
- };
-
- this.selectEnd =
- this.selectAllEnd =
- this.selectByWordsEnd =
- this.selectByLinesEnd = function() {
- this.$clickSelection = null;
- this.editor.unsetStyle("ace_selecting");
- if (this.editor.renderer.scroller.releaseCapture) {
- this.editor.renderer.scroller.releaseCapture();
- }
- };
-
- this.focusWait = function() {
- var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y);
- var time = Date.now();
-
- if (distance > DRAG_OFFSET || time - this.mousedownEvent.time > this.$focusTimout)
- this.startSelect(this.mousedownEvent.getDocumentPosition());
- };
-
- this.onDoubleClick = function(ev) {
- var pos = ev.getDocumentPosition();
- var editor = this.editor;
- var session = editor.session;
-
- var range = session.getBracketRange(pos);
- if (range) {
- if (range.isEmpty()) {
- range.start.column--;
- range.end.column++;
- }
- this.setState("select");
- } else {
- range = editor.selection.getWordRange(pos.row, pos.column);
- this.setState("selectByWords");
- }
- this.$clickSelection = range;
- this.select();
- };
-
- this.onTripleClick = function(ev) {
- var pos = ev.getDocumentPosition();
- var editor = this.editor;
-
- this.setState("selectByLines");
- var range = editor.getSelectionRange();
- if (range.isMultiLine() && range.contains(pos.row, pos.column)) {
- this.$clickSelection = editor.selection.getLineRange(range.start.row);
- this.$clickSelection.end = editor.selection.getLineRange(range.end.row).end;
- } else {
- this.$clickSelection = editor.selection.getLineRange(pos.row);
- }
- this.select();
- };
-
- this.onQuadClick = function(ev) {
- var editor = this.editor;
-
- editor.selectAll();
- this.$clickSelection = editor.getSelectionRange();
- this.setState("selectAll");
- };
-
- this.onMouseWheel = function(ev) {
- if (ev.getAccelKey())
- return;
- if (ev.getShiftKey() && ev.wheelY && !ev.wheelX) {
- ev.wheelX = ev.wheelY;
- ev.wheelY = 0;
- }
-
- var t = ev.domEvent.timeStamp;
- var dt = t - (this.$lastScrollTime||0);
-
- var editor = this.editor;
- var isScrolable = editor.renderer.isScrollableBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed);
- if (isScrolable || dt < 200) {
- this.$lastScrollTime = t;
- editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed);
- return ev.stop();
- }
- };
-
- this.onTouchMove = function (ev) {
- var t = ev.domEvent.timeStamp;
- var dt = t - (this.$lastScrollTime || 0);
-
- var editor = this.editor;
- var isScrolable = editor.renderer.isScrollableBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed);
- if (isScrolable || dt < 200) {
- this.$lastScrollTime = t;
- editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed);
- return ev.stop();
- }
- };
-
-}).call(DefaultHandlers.prototype);
-
-exports.DefaultHandlers = DefaultHandlers;
-
-function calcDistance(ax, ay, bx, by) {
- return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2));
-}
-
-function calcRangeOrientation(range, cursor) {
- if (range.start.row == range.end.row)
- var cmp = 2 * cursor.column - range.start.column - range.end.column;
- else if (range.start.row == range.end.row - 1 && !range.start.column && !range.end.column)
- var cmp = cursor.column - 4;
- else
- var cmp = 2 * cursor.row - range.start.row - range.end.row;
-
- if (cmp < 0)
- return {cursor: range.start, anchor: range.end};
- else
- return {cursor: range.end, anchor: range.start};
-}
-
-});
-
-ace.define("ace/tooltip",["require","exports","module","ace/lib/oop","ace/lib/dom"], function(require, exports, module) {
-"use strict";
-
-var oop = require("./lib/oop");
-var dom = require("./lib/dom");
-function Tooltip (parentNode) {
- this.isOpen = false;
- this.$element = null;
- this.$parentNode = parentNode;
-}
-
-(function() {
- this.$init = function() {
- this.$element = dom.createElement("div");
- this.$element.className = "ace_tooltip";
- this.$element.style.display = "none";
- this.$parentNode.appendChild(this.$element);
- return this.$element;
- };
- this.getElement = function() {
- return this.$element || this.$init();
- };
- this.setText = function(text) {
- dom.setInnerText(this.getElement(), text);
- };
- this.setHtml = function(html) {
- this.getElement().innerHTML = html;
- };
- this.setPosition = function(x, y) {
- this.getElement().style.left = x + "px";
- this.getElement().style.top = y + "px";
- };
- this.setClassName = function(className) {
- dom.addCssClass(this.getElement(), className);
- };
- this.show = function(text, x, y) {
- if (text != null)
- this.setText(text);
- if (x != null && y != null)
- this.setPosition(x, y);
- if (!this.isOpen) {
- this.getElement().style.display = "block";
- this.isOpen = true;
- }
- };
-
- this.hide = function() {
- if (this.isOpen) {
- this.getElement().style.display = "none";
- this.isOpen = false;
- }
- };
- this.getHeight = function() {
- return this.getElement().offsetHeight;
- };
- this.getWidth = function() {
- return this.getElement().offsetWidth;
- };
-
-}).call(Tooltip.prototype);
-
-exports.Tooltip = Tooltip;
-});
-
-ace.define("ace/mouse/default_gutter_handler",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/event","ace/tooltip"], function(require, exports, module) {
-"use strict";
-var dom = require("../lib/dom");
-var oop = require("../lib/oop");
-var event = require("../lib/event");
-var Tooltip = require("../tooltip").Tooltip;
-
-function GutterHandler(mouseHandler) {
- var editor = mouseHandler.editor;
- var gutter = editor.renderer.$gutterLayer;
- var tooltip = new GutterTooltip(editor.container);
-
- mouseHandler.editor.setDefaultHandler("guttermousedown", function(e) {
- if (!editor.isFocused() || e.getButton() != 0)
- return;
- var gutterRegion = gutter.getRegion(e);
-
- if (gutterRegion == "foldWidgets")
- return;
-
- var row = e.getDocumentPosition().row;
- var selection = editor.session.selection;
-
- if (e.getShiftKey())
- selection.selectTo(row, 0);
- else {
- if (e.domEvent.detail == 2) {
- editor.selectAll();
- return e.preventDefault();
- }
- mouseHandler.$clickSelection = editor.selection.getLineRange(row);
- }
- mouseHandler.setState("selectByLines");
- mouseHandler.captureMouse(e);
- return e.preventDefault();
- });
-
-
- var tooltipTimeout, mouseEvent, tooltipAnnotation;
-
- function showTooltip() {
- var row = mouseEvent.getDocumentPosition().row;
- var annotation = gutter.$annotations[row];
- if (!annotation)
- return hideTooltip();
-
- var maxRow = editor.session.getLength();
- if (row == maxRow) {
- var screenRow = editor.renderer.pixelToScreenCoordinates(0, mouseEvent.y).row;
- var pos = mouseEvent.$pos;
- if (screenRow > editor.session.documentToScreenRow(pos.row, pos.column))
- return hideTooltip();
- }
-
- if (tooltipAnnotation == annotation)
- return;
- tooltipAnnotation = annotation.text.join("
");
-
- tooltip.setHtml(tooltipAnnotation);
- tooltip.show();
- editor.on("mousewheel", hideTooltip);
-
- if (mouseHandler.$tooltipFollowsMouse) {
- moveTooltip(mouseEvent);
- } else {
- var gutterElement = mouseEvent.domEvent.target;
- var rect = gutterElement.getBoundingClientRect();
- var style = tooltip.getElement().style;
- style.left = rect.right + "px";
- style.top = rect.bottom + "px";
- }
- }
-
- function hideTooltip() {
- if (tooltipTimeout)
- tooltipTimeout = clearTimeout(tooltipTimeout);
- if (tooltipAnnotation) {
- tooltip.hide();
- tooltipAnnotation = null;
- editor.removeEventListener("mousewheel", hideTooltip);
- }
- }
-
- function moveTooltip(e) {
- tooltip.setPosition(e.x, e.y);
- }
-
- mouseHandler.editor.setDefaultHandler("guttermousemove", function(e) {
- var target = e.domEvent.target || e.domEvent.srcElement;
- if (dom.hasCssClass(target, "ace_fold-widget"))
- return hideTooltip();
-
- if (tooltipAnnotation && mouseHandler.$tooltipFollowsMouse)
- moveTooltip(e);
-
- mouseEvent = e;
- if (tooltipTimeout)
- return;
- tooltipTimeout = setTimeout(function() {
- tooltipTimeout = null;
- if (mouseEvent && !mouseHandler.isMousePressed)
- showTooltip();
- else
- hideTooltip();
- }, 50);
- });
-
- event.addListener(editor.renderer.$gutter, "mouseout", function(e) {
- mouseEvent = null;
- if (!tooltipAnnotation || tooltipTimeout)
- return;
-
- tooltipTimeout = setTimeout(function() {
- tooltipTimeout = null;
- hideTooltip();
- }, 50);
- });
-
- editor.on("changeSession", hideTooltip);
-}
-
-function GutterTooltip(parentNode) {
- Tooltip.call(this, parentNode);
-}
-
-oop.inherits(GutterTooltip, Tooltip);
-
-(function(){
- this.setPosition = function(x, y) {
- var windowWidth = window.innerWidth || document.documentElement.clientWidth;
- var windowHeight = window.innerHeight || document.documentElement.clientHeight;
- var width = this.getWidth();
- var height = this.getHeight();
- x += 15;
- y += 15;
- if (x + width > windowWidth) {
- x -= (x + width) - windowWidth;
- }
- if (y + height > windowHeight) {
- y -= 20 + height;
- }
- Tooltip.prototype.setPosition.call(this, x, y);
- };
-
-}).call(GutterTooltip.prototype);
-
-
-
-exports.GutterHandler = GutterHandler;
-
-});
-
-ace.define("ace/mouse/mouse_event",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(require, exports, module) {
-"use strict";
-
-var event = require("../lib/event");
-var useragent = require("../lib/useragent");
-var MouseEvent = exports.MouseEvent = function(domEvent, editor) {
- this.domEvent = domEvent;
- this.editor = editor;
-
- this.x = this.clientX = domEvent.clientX;
- this.y = this.clientY = domEvent.clientY;
-
- this.$pos = null;
- this.$inSelection = null;
-
- this.propagationStopped = false;
- this.defaultPrevented = false;
-};
-
-(function() {
-
- this.stopPropagation = function() {
- event.stopPropagation(this.domEvent);
- this.propagationStopped = true;
- };
-
- this.preventDefault = function() {
- event.preventDefault(this.domEvent);
- this.defaultPrevented = true;
- };
-
- this.stop = function() {
- this.stopPropagation();
- this.preventDefault();
- };
- this.getDocumentPosition = function() {
- if (this.$pos)
- return this.$pos;
-
- this.$pos = this.editor.renderer.screenToTextCoordinates(this.clientX, this.clientY);
- return this.$pos;
- };
- this.inSelection = function() {
- if (this.$inSelection !== null)
- return this.$inSelection;
-
- var editor = this.editor;
-
-
- var selectionRange = editor.getSelectionRange();
- if (selectionRange.isEmpty())
- this.$inSelection = false;
- else {
- var pos = this.getDocumentPosition();
- this.$inSelection = selectionRange.contains(pos.row, pos.column);
- }
-
- return this.$inSelection;
- };
- this.getButton = function() {
- return event.getButton(this.domEvent);
- };
- this.getShiftKey = function() {
- return this.domEvent.shiftKey;
- };
-
- this.getAccelKey = useragent.isMac
- ? function() { return this.domEvent.metaKey; }
- : function() { return this.domEvent.ctrlKey; };
-
-}).call(MouseEvent.prototype);
-
-});
-
-ace.define("ace/mouse/dragdrop_handler",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"], function(require, exports, module) {
-"use strict";
-
-var dom = require("../lib/dom");
-var event = require("../lib/event");
-var useragent = require("../lib/useragent");
-
-var AUTOSCROLL_DELAY = 200;
-var SCROLL_CURSOR_DELAY = 200;
-var SCROLL_CURSOR_HYSTERESIS = 5;
-
-function DragdropHandler(mouseHandler) {
-
- var editor = mouseHandler.editor;
-
- var blankImage = dom.createElement("img");
- blankImage.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
- if (useragent.isOpera)
- blankImage.style.cssText = "width:1px;height:1px;position:fixed;top:0;left:0;z-index:2147483647;opacity:0;";
-
- var exports = ["dragWait", "dragWaitEnd", "startDrag", "dragReadyEnd", "onMouseDrag"];
-
- exports.forEach(function(x) {
- mouseHandler[x] = this[x];
- }, this);
- editor.addEventListener("mousedown", this.onMouseDown.bind(mouseHandler));
-
-
- var mouseTarget = editor.container;
- var dragSelectionMarker, x, y;
- var timerId, range;
- var dragCursor, counter = 0;
- var dragOperation;
- var isInternal;
- var autoScrollStartTime;
- var cursorMovedTime;
- var cursorPointOnCaretMoved;
-
- this.onDragStart = function(e) {
- if (this.cancelDrag || !mouseTarget.draggable) {
- var self = this;
- setTimeout(function(){
- self.startSelect();
- self.captureMouse(e);
- }, 0);
- return e.preventDefault();
- }
- range = editor.getSelectionRange();
-
- var dataTransfer = e.dataTransfer;
- dataTransfer.effectAllowed = editor.getReadOnly() ? "copy" : "copyMove";
- if (useragent.isOpera) {
- editor.container.appendChild(blankImage);
- blankImage.scrollTop = 0;
- }
- dataTransfer.setDragImage && dataTransfer.setDragImage(blankImage, 0, 0);
- if (useragent.isOpera) {
- editor.container.removeChild(blankImage);
- }
- dataTransfer.clearData();
- dataTransfer.setData("Text", editor.session.getTextRange());
-
- isInternal = true;
- this.setState("drag");
- };
-
- this.onDragEnd = function(e) {
- mouseTarget.draggable = false;
- isInternal = false;
- this.setState(null);
- if (!editor.getReadOnly()) {
- var dropEffect = e.dataTransfer.dropEffect;
- if (!dragOperation && dropEffect == "move")
- editor.session.remove(editor.getSelectionRange());
- editor.renderer.$cursorLayer.setBlinking(true);
- }
- this.editor.unsetStyle("ace_dragging");
- this.editor.renderer.setCursorStyle("");
- };
-
- this.onDragEnter = function(e) {
- if (editor.getReadOnly() || !canAccept(e.dataTransfer))
- return;
- x = e.clientX;
- y = e.clientY;
- if (!dragSelectionMarker)
- addDragMarker();
- counter++;
- e.dataTransfer.dropEffect = dragOperation = getDropEffect(e);
- return event.preventDefault(e);
- };
-
- this.onDragOver = function(e) {
- if (editor.getReadOnly() || !canAccept(e.dataTransfer))
- return;
- x = e.clientX;
- y = e.clientY;
- if (!dragSelectionMarker) {
- addDragMarker();
- counter++;
- }
- if (onMouseMoveTimer !== null)
- onMouseMoveTimer = null;
-
- e.dataTransfer.dropEffect = dragOperation = getDropEffect(e);
- return event.preventDefault(e);
- };
-
- this.onDragLeave = function(e) {
- counter--;
- if (counter <= 0 && dragSelectionMarker) {
- clearDragMarker();
- dragOperation = null;
- return event.preventDefault(e);
- }
- };
-
- this.onDrop = function(e) {
- if (!dragCursor)
- return;
- var dataTransfer = e.dataTransfer;
- if (isInternal) {
- switch (dragOperation) {
- case "move":
- if (range.contains(dragCursor.row, dragCursor.column)) {
- range = {
- start: dragCursor,
- end: dragCursor
- };
- } else {
- range = editor.moveText(range, dragCursor);
- }
- break;
- case "copy":
- range = editor.moveText(range, dragCursor, true);
- break;
- }
- } else {
- var dropData = dataTransfer.getData('Text');
- range = {
- start: dragCursor,
- end: editor.session.insert(dragCursor, dropData)
- };
- editor.focus();
- dragOperation = null;
- }
- clearDragMarker();
- return event.preventDefault(e);
- };
-
- event.addListener(mouseTarget, "dragstart", this.onDragStart.bind(mouseHandler));
- event.addListener(mouseTarget, "dragend", this.onDragEnd.bind(mouseHandler));
- event.addListener(mouseTarget, "dragenter", this.onDragEnter.bind(mouseHandler));
- event.addListener(mouseTarget, "dragover", this.onDragOver.bind(mouseHandler));
- event.addListener(mouseTarget, "dragleave", this.onDragLeave.bind(mouseHandler));
- event.addListener(mouseTarget, "drop", this.onDrop.bind(mouseHandler));
-
- function scrollCursorIntoView(cursor, prevCursor) {
- var now = Date.now();
- var vMovement = !prevCursor || cursor.row != prevCursor.row;
- var hMovement = !prevCursor || cursor.column != prevCursor.column;
- if (!cursorMovedTime || vMovement || hMovement) {
- editor.$blockScrolling += 1;
- editor.moveCursorToPosition(cursor);
- editor.$blockScrolling -= 1;
- cursorMovedTime = now;
- cursorPointOnCaretMoved = {x: x, y: y};
- } else {
- var distance = calcDistance(cursorPointOnCaretMoved.x, cursorPointOnCaretMoved.y, x, y);
- if (distance > SCROLL_CURSOR_HYSTERESIS) {
- cursorMovedTime = null;
- } else if (now - cursorMovedTime >= SCROLL_CURSOR_DELAY) {
- editor.renderer.scrollCursorIntoView();
- cursorMovedTime = null;
- }
- }
- }
-
- function autoScroll(cursor, prevCursor) {
- var now = Date.now();
- var lineHeight = editor.renderer.layerConfig.lineHeight;
- var characterWidth = editor.renderer.layerConfig.characterWidth;
- var editorRect = editor.renderer.scroller.getBoundingClientRect();
- var offsets = {
- x: {
- left: x - editorRect.left,
- right: editorRect.right - x
- },
- y: {
- top: y - editorRect.top,
- bottom: editorRect.bottom - y
- }
- };
- var nearestXOffset = Math.min(offsets.x.left, offsets.x.right);
- var nearestYOffset = Math.min(offsets.y.top, offsets.y.bottom);
- var scrollCursor = {row: cursor.row, column: cursor.column};
- if (nearestXOffset / characterWidth <= 2) {
- scrollCursor.column += (offsets.x.left < offsets.x.right ? -3 : +2);
- }
- if (nearestYOffset / lineHeight <= 1) {
- scrollCursor.row += (offsets.y.top < offsets.y.bottom ? -1 : +1);
- }
- var vScroll = cursor.row != scrollCursor.row;
- var hScroll = cursor.column != scrollCursor.column;
- var vMovement = !prevCursor || cursor.row != prevCursor.row;
- if (vScroll || (hScroll && !vMovement)) {
- if (!autoScrollStartTime)
- autoScrollStartTime = now;
- else if (now - autoScrollStartTime >= AUTOSCROLL_DELAY)
- editor.renderer.scrollCursorIntoView(scrollCursor);
- } else {
- autoScrollStartTime = null;
- }
- }
-
- function onDragInterval() {
- var prevCursor = dragCursor;
- dragCursor = editor.renderer.screenToTextCoordinates(x, y);
- scrollCursorIntoView(dragCursor, prevCursor);
- autoScroll(dragCursor, prevCursor);
- }
-
- function addDragMarker() {
- range = editor.selection.toOrientedRange();
- dragSelectionMarker = editor.session.addMarker(range, "ace_selection", editor.getSelectionStyle());
- editor.clearSelection();
- if (editor.isFocused())
- editor.renderer.$cursorLayer.setBlinking(false);
- clearInterval(timerId);
- onDragInterval();
- timerId = setInterval(onDragInterval, 20);
- counter = 0;
- event.addListener(document, "mousemove", onMouseMove);
- }
-
- function clearDragMarker() {
- clearInterval(timerId);
- editor.session.removeMarker(dragSelectionMarker);
- dragSelectionMarker = null;
- editor.$blockScrolling += 1;
- editor.selection.fromOrientedRange(range);
- editor.$blockScrolling -= 1;
- if (editor.isFocused() && !isInternal)
- editor.renderer.$cursorLayer.setBlinking(!editor.getReadOnly());
- range = null;
- dragCursor = null;
- counter = 0;
- autoScrollStartTime = null;
- cursorMovedTime = null;
- event.removeListener(document, "mousemove", onMouseMove);
- }
- var onMouseMoveTimer = null;
- function onMouseMove() {
- if (onMouseMoveTimer == null) {
- onMouseMoveTimer = setTimeout(function() {
- if (onMouseMoveTimer != null && dragSelectionMarker)
- clearDragMarker();
- }, 20);
- }
- }
-
- function canAccept(dataTransfer) {
- var types = dataTransfer.types;
- return !types || Array.prototype.some.call(types, function(type) {
- return type == 'text/plain' || type == 'Text';
- });
- }
-
- function getDropEffect(e) {
- var copyAllowed = ['copy', 'copymove', 'all', 'uninitialized'];
- var moveAllowed = ['move', 'copymove', 'linkmove', 'all', 'uninitialized'];
-
- var copyModifierState = useragent.isMac ? e.altKey : e.ctrlKey;
- var effectAllowed = "uninitialized";
- try {
- effectAllowed = e.dataTransfer.effectAllowed.toLowerCase();
- } catch (e) {}
- var dropEffect = "none";
-
- if (copyModifierState && copyAllowed.indexOf(effectAllowed) >= 0)
- dropEffect = "copy";
- else if (moveAllowed.indexOf(effectAllowed) >= 0)
- dropEffect = "move";
- else if (copyAllowed.indexOf(effectAllowed) >= 0)
- dropEffect = "copy";
-
- return dropEffect;
- }
-}
-
-(function() {
-
- this.dragWait = function() {
- var interval = Date.now() - this.mousedownEvent.time;
- if (interval > this.editor.getDragDelay())
- this.startDrag();
- };
-
- this.dragWaitEnd = function() {
- var target = this.editor.container;
- target.draggable = false;
- this.startSelect(this.mousedownEvent.getDocumentPosition());
- this.selectEnd();
- };
-
- this.dragReadyEnd = function(e) {
- this.editor.renderer.$cursorLayer.setBlinking(!this.editor.getReadOnly());
- this.editor.unsetStyle("ace_dragging");
- this.editor.renderer.setCursorStyle("");
- this.dragWaitEnd();
- };
-
- this.startDrag = function(){
- this.cancelDrag = false;
- var editor = this.editor;
- var target = editor.container;
- target.draggable = true;
- editor.renderer.$cursorLayer.setBlinking(false);
- editor.setStyle("ace_dragging");
- var cursorStyle = useragent.isWin ? "default" : "move";
- editor.renderer.setCursorStyle(cursorStyle);
- this.setState("dragReady");
- };
-
- this.onMouseDrag = function(e) {
- var target = this.editor.container;
- if (useragent.isIE && this.state == "dragReady") {
- var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y);
- if (distance > 3)
- target.dragDrop();
- }
- if (this.state === "dragWait") {
- var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y);
- if (distance > 0) {
- target.draggable = false;
- this.startSelect(this.mousedownEvent.getDocumentPosition());
- }
- }
- };
-
- this.onMouseDown = function(e) {
- if (!this.$dragEnabled)
- return;
- this.mousedownEvent = e;
- var editor = this.editor;
-
- var inSelection = e.inSelection();
- var button = e.getButton();
- var clickCount = e.domEvent.detail || 1;
- if (clickCount === 1 && button === 0 && inSelection) {
- if (e.editor.inMultiSelectMode && (e.getAccelKey() || e.getShiftKey()))
- return;
- this.mousedownEvent.time = Date.now();
- var eventTarget = e.domEvent.target || e.domEvent.srcElement;
- if ("unselectable" in eventTarget)
- eventTarget.unselectable = "on";
- if (editor.getDragDelay()) {
- if (useragent.isWebKit) {
- this.cancelDrag = true;
- var mouseTarget = editor.container;
- mouseTarget.draggable = true;
- }
- this.setState("dragWait");
- } else {
- this.startDrag();
- }
- this.captureMouse(e, this.onMouseDrag.bind(this));
- e.defaultPrevented = true;
- }
- };
-
-}).call(DragdropHandler.prototype);
-
-
-function calcDistance(ax, ay, bx, by) {
- return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2));
-}
-
-exports.DragdropHandler = DragdropHandler;
-
-});
-
-ace.define("ace/lib/net",["require","exports","module","ace/lib/dom"], function(require, exports, module) {
-"use strict";
-var dom = require("./dom");
-
-exports.get = function (url, callback) {
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url, true);
- xhr.onreadystatechange = function () {
- if (xhr.readyState === 4) {
- callback(xhr.responseText);
- }
- };
- xhr.send(null);
-};
-
-exports.loadScript = function(path, callback) {
- var head = dom.getDocumentHead();
- var s = document.createElement('script');
-
- s.src = path;
- head.appendChild(s);
-
- s.onload = s.onreadystatechange = function(_, isAbort) {
- if (isAbort || !s.readyState || s.readyState == "loaded" || s.readyState == "complete") {
- s = s.onload = s.onreadystatechange = null;
- if (!isAbort)
- callback();
- }
- };
-};
-exports.qualifyURL = function(url) {
- var a = document.createElement('a');
- a.href = url;
- return a.href;
-}
-
-});
-
-ace.define("ace/lib/event_emitter",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-var EventEmitter = {};
-var stopPropagation = function() { this.propagationStopped = true; };
-var preventDefault = function() { this.defaultPrevented = true; };
-
-EventEmitter._emit =
-EventEmitter._dispatchEvent = function(eventName, e) {
- this._eventRegistry || (this._eventRegistry = {});
- this._defaultHandlers || (this._defaultHandlers = {});
-
- var listeners = this._eventRegistry[eventName] || [];
- var defaultHandler = this._defaultHandlers[eventName];
- if (!listeners.length && !defaultHandler)
- return;
-
- if (typeof e != "object" || !e)
- e = {};
-
- if (!e.type)
- e.type = eventName;
- if (!e.stopPropagation)
- e.stopPropagation = stopPropagation;
- if (!e.preventDefault)
- e.preventDefault = preventDefault;
-
- listeners = listeners.slice();
- for (var i=0; i 1)
- base = parts[parts.length - 2];
- var path = options[component + "Path"];
- if (path == null) {
- path = options.basePath;
- } else if (sep == "/") {
- component = sep = "";
- }
- if (path && path.slice(-1) != "/")
- path += "/";
- return path + component + sep + base + this.get("suffix");
-};
-
-exports.setModuleUrl = function(name, subst) {
- return options.$moduleUrls[name] = subst;
-};
-
-exports.$loading = {};
-exports.loadModule = function(moduleName, onLoad) {
- var module, moduleType;
- if (Array.isArray(moduleName)) {
- moduleType = moduleName[0];
- moduleName = moduleName[1];
- }
-
- try {
- module = require(moduleName);
- } catch (e) {}
- if (module && !exports.$loading[moduleName])
- return onLoad && onLoad(module);
-
- if (!exports.$loading[moduleName])
- exports.$loading[moduleName] = [];
-
- exports.$loading[moduleName].push(onLoad);
-
- if (exports.$loading[moduleName].length > 1)
- return;
-
- var afterLoad = function() {
- require([moduleName], function(module) {
- exports._emit("load.module", {name: moduleName, module: module});
- var listeners = exports.$loading[moduleName];
- exports.$loading[moduleName] = null;
- listeners.forEach(function(onLoad) {
- onLoad && onLoad(module);
- });
- });
- };
-
- if (!exports.get("packaged"))
- return afterLoad();
- net.loadScript(exports.moduleUrl(moduleName, moduleType), afterLoad);
-};
-init(true);function init(packaged) {
-
- if (!global || !global.document)
- return;
-
- options.packaged = packaged || require.packaged || module.packaged || (global.define && define.packaged);
-
- var scriptOptions = {};
- var scriptUrl = "";
- var currentScript = (document.currentScript || document._currentScript ); // native or polyfill
- var currentDocument = currentScript && currentScript.ownerDocument || document;
-
- var scripts = currentDocument.getElementsByTagName("script");
- for (var i=0; i [" + this.end.row + "/" + this.end.column + "]");
- };
-
- this.contains = function(row, column) {
- return this.compare(row, column) == 0;
- };
- this.compareRange = function(range) {
- var cmp,
- end = range.end,
- start = range.start;
-
- cmp = this.compare(end.row, end.column);
- if (cmp == 1) {
- cmp = this.compare(start.row, start.column);
- if (cmp == 1) {
- return 2;
- } else if (cmp == 0) {
- return 1;
- } else {
- return 0;
- }
- } else if (cmp == -1) {
- return -2;
- } else {
- cmp = this.compare(start.row, start.column);
- if (cmp == -1) {
- return -1;
- } else if (cmp == 1) {
- return 42;
- } else {
- return 0;
- }
- }
- };
- this.comparePoint = function(p) {
- return this.compare(p.row, p.column);
- };
- this.containsRange = function(range) {
- return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0;
- };
- this.intersects = function(range) {
- var cmp = this.compareRange(range);
- return (cmp == -1 || cmp == 0 || cmp == 1);
- };
- this.isEnd = function(row, column) {
- return this.end.row == row && this.end.column == column;
- };
- this.isStart = function(row, column) {
- return this.start.row == row && this.start.column == column;
- };
- this.setStart = function(row, column) {
- if (typeof row == "object") {
- this.start.column = row.column;
- this.start.row = row.row;
- } else {
- this.start.row = row;
- this.start.column = column;
- }
- };
- this.setEnd = function(row, column) {
- if (typeof row == "object") {
- this.end.column = row.column;
- this.end.row = row.row;
- } else {
- this.end.row = row;
- this.end.column = column;
- }
- };
- this.inside = function(row, column) {
- if (this.compare(row, column) == 0) {
- if (this.isEnd(row, column) || this.isStart(row, column)) {
- return false;
- } else {
- return true;
- }
- }
- return false;
- };
- this.insideStart = function(row, column) {
- if (this.compare(row, column) == 0) {
- if (this.isEnd(row, column)) {
- return false;
- } else {
- return true;
- }
- }
- return false;
- };
- this.insideEnd = function(row, column) {
- if (this.compare(row, column) == 0) {
- if (this.isStart(row, column)) {
- return false;
- } else {
- return true;
- }
- }
- return false;
- };
- this.compare = function(row, column) {
- if (!this.isMultiLine()) {
- if (row === this.start.row) {
- return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0);
- }
- }
-
- if (row < this.start.row)
- return -1;
-
- if (row > this.end.row)
- return 1;
-
- if (this.start.row === row)
- return column >= this.start.column ? 0 : -1;
-
- if (this.end.row === row)
- return column <= this.end.column ? 0 : 1;
-
- return 0;
- };
- this.compareStart = function(row, column) {
- if (this.start.row == row && this.start.column == column) {
- return -1;
- } else {
- return this.compare(row, column);
- }
- };
- this.compareEnd = function(row, column) {
- if (this.end.row == row && this.end.column == column) {
- return 1;
- } else {
- return this.compare(row, column);
- }
- };
- this.compareInside = function(row, column) {
- if (this.end.row == row && this.end.column == column) {
- return 1;
- } else if (this.start.row == row && this.start.column == column) {
- return -1;
- } else {
- return this.compare(row, column);
- }
- };
- this.clipRows = function(firstRow, lastRow) {
- if (this.end.row > lastRow)
- var end = {row: lastRow + 1, column: 0};
- else if (this.end.row < firstRow)
- var end = {row: firstRow, column: 0};
-
- if (this.start.row > lastRow)
- var start = {row: lastRow + 1, column: 0};
- else if (this.start.row < firstRow)
- var start = {row: firstRow, column: 0};
-
- return Range.fromPoints(start || this.start, end || this.end);
- };
- this.extend = function(row, column) {
- var cmp = this.compare(row, column);
-
- if (cmp == 0)
- return this;
- else if (cmp == -1)
- var start = {row: row, column: column};
- else
- var end = {row: row, column: column};
-
- return Range.fromPoints(start || this.start, end || this.end);
- };
-
- this.isEmpty = function() {
- return (this.start.row === this.end.row && this.start.column === this.end.column);
- };
- this.isMultiLine = function() {
- return (this.start.row !== this.end.row);
- };
- this.clone = function() {
- return Range.fromPoints(this.start, this.end);
- };
- this.collapseRows = function() {
- if (this.end.column == 0)
- return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0)
- else
- return new Range(this.start.row, 0, this.end.row, 0)
- };
- this.toScreenRange = function(session) {
- var screenPosStart = session.documentToScreenPosition(this.start);
- var screenPosEnd = session.documentToScreenPosition(this.end);
-
- return new Range(
- screenPosStart.row, screenPosStart.column,
- screenPosEnd.row, screenPosEnd.column
- );
- };
- this.moveBy = function(row, column) {
- this.start.row += row;
- this.start.column += column;
- this.end.row += row;
- this.end.column += column;
- };
-
-}).call(Range.prototype);
-Range.fromPoints = function(start, end) {
- return new Range(start.row, start.column, end.row, end.column);
-};
-Range.comparePoints = comparePoints;
-
-Range.comparePoints = function(p1, p2) {
- return p1.row - p2.row || p1.column - p2.column;
-};
-
-
-exports.Range = Range;
-});
-
-ace.define("ace/selection",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter","ace/range"], function(require, exports, module) {
-"use strict";
-
-var oop = require("./lib/oop");
-var lang = require("./lib/lang");
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-var Range = require("./range").Range;
-var Selection = function(session) {
- this.session = session;
- this.doc = session.getDocument();
-
- this.clearSelection();
- this.lead = this.selectionLead = this.doc.createAnchor(0, 0);
- this.anchor = this.selectionAnchor = this.doc.createAnchor(0, 0);
-
- var self = this;
- this.lead.on("change", function(e) {
- self._emit("changeCursor");
- if (!self.$isEmpty)
- self._emit("changeSelection");
- if (!self.$keepDesiredColumnOnChange && e.old.column != e.value.column)
- self.$desiredColumn = null;
- });
-
- this.selectionAnchor.on("change", function() {
- if (!self.$isEmpty)
- self._emit("changeSelection");
- });
-};
-
-(function() {
-
- oop.implement(this, EventEmitter);
- this.isEmpty = function() {
- return (this.$isEmpty || (
- this.anchor.row == this.lead.row &&
- this.anchor.column == this.lead.column
- ));
- };
- this.isMultiLine = function() {
- if (this.isEmpty()) {
- return false;
- }
-
- return this.getRange().isMultiLine();
- };
- this.getCursor = function() {
- return this.lead.getPosition();
- };
- this.setSelectionAnchor = function(row, column) {
- this.anchor.setPosition(row, column);
-
- if (this.$isEmpty) {
- this.$isEmpty = false;
- this._emit("changeSelection");
- }
- };
- this.getSelectionAnchor = function() {
- if (this.$isEmpty)
- return this.getSelectionLead();
- else
- return this.anchor.getPosition();
- };
- this.getSelectionLead = function() {
- return this.lead.getPosition();
- };
- this.shiftSelection = function(columns) {
- if (this.$isEmpty) {
- this.moveCursorTo(this.lead.row, this.lead.column + columns);
- return;
- }
-
- var anchor = this.getSelectionAnchor();
- var lead = this.getSelectionLead();
-
- var isBackwards = this.isBackwards();
-
- if (!isBackwards || anchor.column !== 0)
- this.setSelectionAnchor(anchor.row, anchor.column + columns);
-
- if (isBackwards || lead.column !== 0) {
- this.$moveSelection(function() {
- this.moveCursorTo(lead.row, lead.column + columns);
- });
- }
- };
- this.isBackwards = function() {
- var anchor = this.anchor;
- var lead = this.lead;
- return (anchor.row > lead.row || (anchor.row == lead.row && anchor.column > lead.column));
- };
- this.getRange = function() {
- var anchor = this.anchor;
- var lead = this.lead;
-
- if (this.isEmpty())
- return Range.fromPoints(lead, lead);
-
- if (this.isBackwards()) {
- return Range.fromPoints(lead, anchor);
- }
- else {
- return Range.fromPoints(anchor, lead);
- }
- };
- this.clearSelection = function() {
- if (!this.$isEmpty) {
- this.$isEmpty = true;
- this._emit("changeSelection");
- }
- };
- this.selectAll = function() {
- var lastRow = this.doc.getLength() - 1;
- this.setSelectionAnchor(0, 0);
- this.moveCursorTo(lastRow, this.doc.getLine(lastRow).length);
- };
- this.setRange =
- this.setSelectionRange = function(range, reverse) {
- if (reverse) {
- this.setSelectionAnchor(range.end.row, range.end.column);
- this.selectTo(range.start.row, range.start.column);
- } else {
- this.setSelectionAnchor(range.start.row, range.start.column);
- this.selectTo(range.end.row, range.end.column);
- }
- if (this.getRange().isEmpty())
- this.$isEmpty = true;
- this.$desiredColumn = null;
- };
-
- this.$moveSelection = function(mover) {
- var lead = this.lead;
- if (this.$isEmpty)
- this.setSelectionAnchor(lead.row, lead.column);
-
- mover.call(this);
- };
- this.selectTo = function(row, column) {
- this.$moveSelection(function() {
- this.moveCursorTo(row, column);
- });
- };
- this.selectToPosition = function(pos) {
- this.$moveSelection(function() {
- this.moveCursorToPosition(pos);
- });
- };
- this.moveTo = function(row, column) {
- this.clearSelection();
- this.moveCursorTo(row, column);
- };
- this.moveToPosition = function(pos) {
- this.clearSelection();
- this.moveCursorToPosition(pos);
- };
- this.selectUp = function() {
- this.$moveSelection(this.moveCursorUp);
- };
- this.selectDown = function() {
- this.$moveSelection(this.moveCursorDown);
- };
- this.selectRight = function() {
- this.$moveSelection(this.moveCursorRight);
- };
- this.selectLeft = function() {
- this.$moveSelection(this.moveCursorLeft);
- };
- this.selectLineStart = function() {
- this.$moveSelection(this.moveCursorLineStart);
- };
- this.selectLineEnd = function() {
- this.$moveSelection(this.moveCursorLineEnd);
- };
- this.selectFileEnd = function() {
- this.$moveSelection(this.moveCursorFileEnd);
- };
- this.selectFileStart = function() {
- this.$moveSelection(this.moveCursorFileStart);
- };
- this.selectWordRight = function() {
- this.$moveSelection(this.moveCursorWordRight);
- };
- this.selectWordLeft = function() {
- this.$moveSelection(this.moveCursorWordLeft);
- };
- this.getWordRange = function(row, column) {
- if (typeof column == "undefined") {
- var cursor = row || this.lead;
- row = cursor.row;
- column = cursor.column;
- }
- return this.session.getWordRange(row, column);
- };
- this.selectWord = function() {
- this.setSelectionRange(this.getWordRange());
- };
- this.selectAWord = function() {
- var cursor = this.getCursor();
- var range = this.session.getAWordRange(cursor.row, cursor.column);
- this.setSelectionRange(range);
- };
-
- this.getLineRange = function(row, excludeLastChar) {
- var rowStart = typeof row == "number" ? row : this.lead.row;
- var rowEnd;
-
- var foldLine = this.session.getFoldLine(rowStart);
- if (foldLine) {
- rowStart = foldLine.start.row;
- rowEnd = foldLine.end.row;
- } else {
- rowEnd = rowStart;
- }
- if (excludeLastChar === true)
- return new Range(rowStart, 0, rowEnd, this.session.getLine(rowEnd).length);
- else
- return new Range(rowStart, 0, rowEnd + 1, 0);
- };
- this.selectLine = function() {
- this.setSelectionRange(this.getLineRange());
- };
- this.moveCursorUp = function() {
- this.moveCursorBy(-1, 0);
- };
- this.moveCursorDown = function() {
- this.moveCursorBy(1, 0);
- };
- this.moveCursorLeft = function() {
- var cursor = this.lead.getPosition(),
- fold;
-
- if (fold = this.session.getFoldAt(cursor.row, cursor.column, -1)) {
- this.moveCursorTo(fold.start.row, fold.start.column);
- } else if (cursor.column === 0) {
- if (cursor.row > 0) {
- this.moveCursorTo(cursor.row - 1, this.doc.getLine(cursor.row - 1).length);
- }
- }
- else {
- var tabSize = this.session.getTabSize();
- if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column-tabSize, cursor.column).split(" ").length-1 == tabSize)
- this.moveCursorBy(0, -tabSize);
- else
- this.moveCursorBy(0, -1);
- }
- };
- this.moveCursorRight = function() {
- var cursor = this.lead.getPosition(),
- fold;
- if (fold = this.session.getFoldAt(cursor.row, cursor.column, 1)) {
- this.moveCursorTo(fold.end.row, fold.end.column);
- }
- else if (this.lead.column == this.doc.getLine(this.lead.row).length) {
- if (this.lead.row < this.doc.getLength() - 1) {
- this.moveCursorTo(this.lead.row + 1, 0);
- }
- }
- else {
- var tabSize = this.session.getTabSize();
- var cursor = this.lead;
- if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column, cursor.column+tabSize).split(" ").length-1 == tabSize)
- this.moveCursorBy(0, tabSize);
- else
- this.moveCursorBy(0, 1);
- }
- };
- this.moveCursorLineStart = function() {
- var row = this.lead.row;
- var column = this.lead.column;
- var screenRow = this.session.documentToScreenRow(row, column);
- var firstColumnPosition = this.session.screenToDocumentPosition(screenRow, 0);
- var beforeCursor = this.session.getDisplayLine(
- row, null, firstColumnPosition.row,
- firstColumnPosition.column
- );
-
- var leadingSpace = beforeCursor.match(/^\s*/);
- if (leadingSpace[0].length != column && !this.session.$useEmacsStyleLineStart)
- firstColumnPosition.column += leadingSpace[0].length;
- this.moveCursorToPosition(firstColumnPosition);
- };
- this.moveCursorLineEnd = function() {
- var lead = this.lead;
- var lineEnd = this.session.getDocumentLastRowColumnPosition(lead.row, lead.column);
- if (this.lead.column == lineEnd.column) {
- var line = this.session.getLine(lineEnd.row);
- if (lineEnd.column == line.length) {
- var textEnd = line.search(/\s+$/);
- if (textEnd > 0)
- lineEnd.column = textEnd;
- }
- }
-
- this.moveCursorTo(lineEnd.row, lineEnd.column);
- };
- this.moveCursorFileEnd = function() {
- var row = this.doc.getLength() - 1;
- var column = this.doc.getLine(row).length;
- this.moveCursorTo(row, column);
- };
- this.moveCursorFileStart = function() {
- this.moveCursorTo(0, 0);
- };
- this.moveCursorLongWordRight = function() {
- var row = this.lead.row;
- var column = this.lead.column;
- var line = this.doc.getLine(row);
- var rightOfCursor = line.substring(column);
-
- var match;
- this.session.nonTokenRe.lastIndex = 0;
- this.session.tokenRe.lastIndex = 0;
- var fold = this.session.getFoldAt(row, column, 1);
- if (fold) {
- this.moveCursorTo(fold.end.row, fold.end.column);
- return;
- }
- if (match = this.session.nonTokenRe.exec(rightOfCursor)) {
- column += this.session.nonTokenRe.lastIndex;
- this.session.nonTokenRe.lastIndex = 0;
- rightOfCursor = line.substring(column);
- }
- if (column >= line.length) {
- this.moveCursorTo(row, line.length);
- this.moveCursorRight();
- if (row < this.doc.getLength() - 1)
- this.moveCursorWordRight();
- return;
- }
- if (match = this.session.tokenRe.exec(rightOfCursor)) {
- column += this.session.tokenRe.lastIndex;
- this.session.tokenRe.lastIndex = 0;
- }
-
- this.moveCursorTo(row, column);
- };
- this.moveCursorLongWordLeft = function() {
- var row = this.lead.row;
- var column = this.lead.column;
- var fold;
- if (fold = this.session.getFoldAt(row, column, -1)) {
- this.moveCursorTo(fold.start.row, fold.start.column);
- return;
- }
-
- var str = this.session.getFoldStringAt(row, column, -1);
- if (str == null) {
- str = this.doc.getLine(row).substring(0, column);
- }
-
- var leftOfCursor = lang.stringReverse(str);
- var match;
- this.session.nonTokenRe.lastIndex = 0;
- this.session.tokenRe.lastIndex = 0;
- if (match = this.session.nonTokenRe.exec(leftOfCursor)) {
- column -= this.session.nonTokenRe.lastIndex;
- leftOfCursor = leftOfCursor.slice(this.session.nonTokenRe.lastIndex);
- this.session.nonTokenRe.lastIndex = 0;
- }
- if (column <= 0) {
- this.moveCursorTo(row, 0);
- this.moveCursorLeft();
- if (row > 0)
- this.moveCursorWordLeft();
- return;
- }
- if (match = this.session.tokenRe.exec(leftOfCursor)) {
- column -= this.session.tokenRe.lastIndex;
- this.session.tokenRe.lastIndex = 0;
- }
-
- this.moveCursorTo(row, column);
- };
-
- this.$shortWordEndIndex = function(rightOfCursor) {
- var match, index = 0, ch;
- var whitespaceRe = /\s/;
- var tokenRe = this.session.tokenRe;
-
- tokenRe.lastIndex = 0;
- if (match = this.session.tokenRe.exec(rightOfCursor)) {
- index = this.session.tokenRe.lastIndex;
- } else {
- while ((ch = rightOfCursor[index]) && whitespaceRe.test(ch))
- index ++;
-
- if (index < 1) {
- tokenRe.lastIndex = 0;
- while ((ch = rightOfCursor[index]) && !tokenRe.test(ch)) {
- tokenRe.lastIndex = 0;
- index ++;
- if (whitespaceRe.test(ch)) {
- if (index > 2) {
- index--;
- break;
- } else {
- while ((ch = rightOfCursor[index]) && whitespaceRe.test(ch))
- index ++;
- if (index > 2)
- break;
- }
- }
- }
- }
- }
- tokenRe.lastIndex = 0;
-
- return index;
- };
-
- this.moveCursorShortWordRight = function() {
- var row = this.lead.row;
- var column = this.lead.column;
- var line = this.doc.getLine(row);
- var rightOfCursor = line.substring(column);
-
- var fold = this.session.getFoldAt(row, column, 1);
- if (fold)
- return this.moveCursorTo(fold.end.row, fold.end.column);
-
- if (column == line.length) {
- var l = this.doc.getLength();
- do {
- row++;
- rightOfCursor = this.doc.getLine(row);
- } while (row < l && /^\s*$/.test(rightOfCursor));
-
- if (!/^\s+/.test(rightOfCursor))
- rightOfCursor = "";
- column = 0;
- }
-
- var index = this.$shortWordEndIndex(rightOfCursor);
-
- this.moveCursorTo(row, column + index);
- };
-
- this.moveCursorShortWordLeft = function() {
- var row = this.lead.row;
- var column = this.lead.column;
-
- var fold;
- if (fold = this.session.getFoldAt(row, column, -1))
- return this.moveCursorTo(fold.start.row, fold.start.column);
-
- var line = this.session.getLine(row).substring(0, column);
- if (column === 0) {
- do {
- row--;
- line = this.doc.getLine(row);
- } while (row > 0 && /^\s*$/.test(line));
-
- column = line.length;
- if (!/\s+$/.test(line))
- line = "";
- }
-
- var leftOfCursor = lang.stringReverse(line);
- var index = this.$shortWordEndIndex(leftOfCursor);
-
- return this.moveCursorTo(row, column - index);
- };
-
- this.moveCursorWordRight = function() {
- if (this.session.$selectLongWords)
- this.moveCursorLongWordRight();
- else
- this.moveCursorShortWordRight();
- };
-
- this.moveCursorWordLeft = function() {
- if (this.session.$selectLongWords)
- this.moveCursorLongWordLeft();
- else
- this.moveCursorShortWordLeft();
- };
- this.moveCursorBy = function(rows, chars) {
- var screenPos = this.session.documentToScreenPosition(
- this.lead.row,
- this.lead.column
- );
-
- if (chars === 0) {
- if (this.$desiredColumn)
- screenPos.column = this.$desiredColumn;
- else
- this.$desiredColumn = screenPos.column;
- }
-
- var docPos = this.session.screenToDocumentPosition(screenPos.row + rows, screenPos.column);
-
- if (rows !== 0 && chars === 0 && docPos.row === this.lead.row && docPos.column === this.lead.column) {
- if (this.session.lineWidgets && this.session.lineWidgets[docPos.row]) {
- if (docPos.row > 0 || rows > 0)
- docPos.row++;
- }
- }
- this.moveCursorTo(docPos.row, docPos.column + chars, chars === 0);
- };
- this.moveCursorToPosition = function(position) {
- this.moveCursorTo(position.row, position.column);
- };
- this.moveCursorTo = function(row, column, keepDesiredColumn) {
- var fold = this.session.getFoldAt(row, column, 1);
- if (fold) {
- row = fold.start.row;
- column = fold.start.column;
- }
-
- this.$keepDesiredColumnOnChange = true;
- this.lead.setPosition(row, column);
- this.$keepDesiredColumnOnChange = false;
-
- if (!keepDesiredColumn)
- this.$desiredColumn = null;
- };
- this.moveCursorToScreen = function(row, column, keepDesiredColumn) {
- var pos = this.session.screenToDocumentPosition(row, column);
- this.moveCursorTo(pos.row, pos.column, keepDesiredColumn);
- };
- this.detach = function() {
- this.lead.detach();
- this.anchor.detach();
- this.session = this.doc = null;
- };
-
- this.fromOrientedRange = function(range) {
- this.setSelectionRange(range, range.cursor == range.start);
- this.$desiredColumn = range.desiredColumn || this.$desiredColumn;
- };
-
- this.toOrientedRange = function(range) {
- var r = this.getRange();
- if (range) {
- range.start.column = r.start.column;
- range.start.row = r.start.row;
- range.end.column = r.end.column;
- range.end.row = r.end.row;
- } else {
- range = r;
- }
-
- range.cursor = this.isBackwards() ? range.start : range.end;
- range.desiredColumn = this.$desiredColumn;
- return range;
- };
- this.getRangeOfMovements = function(func) {
- var start = this.getCursor();
- try {
- func(this);
- var end = this.getCursor();
- return Range.fromPoints(start,end);
- } catch(e) {
- return Range.fromPoints(start,start);
- } finally {
- this.moveCursorToPosition(start);
- }
- };
-
- this.toJSON = function() {
- if (this.rangeCount) {
- var data = this.ranges.map(function(r) {
- var r1 = r.clone();
- r1.isBackwards = r.cursor == r.start;
- return r1;
- });
- } else {
- var data = this.getRange();
- data.isBackwards = this.isBackwards();
- }
- return data;
- };
-
- this.fromJSON = function(data) {
- if (data.start == undefined) {
- if (this.rangeList) {
- this.toSingleRange(data[0]);
- for (var i = data.length; i--; ) {
- var r = Range.fromPoints(data[i].start, data[i].end);
- if (data[i].isBackwards)
- r.cursor = r.start;
- this.addRange(r, true);
- }
- return;
- } else
- data = data[0];
- }
- if (this.rangeList)
- this.toSingleRange(data);
- this.setSelectionRange(data, data.isBackwards);
- };
-
- this.isEqual = function(data) {
- if ((data.length || this.rangeCount) && data.length != this.rangeCount)
- return false;
- if (!data.length || !this.ranges)
- return this.getRange().isEqual(data);
-
- for (var i = this.ranges.length; i--; ) {
- if (!this.ranges[i].isEqual(data[i]))
- return false;
- }
- return true;
- };
-
-}).call(Selection.prototype);
-
-exports.Selection = Selection;
-});
-
-ace.define("ace/tokenizer",["require","exports","module","ace/config"], function(require, exports, module) {
-"use strict";
-
-var config = require("./config");
-var MAX_TOKEN_COUNT = 2000;
-var Tokenizer = function(rules) {
- this.states = rules;
-
- this.regExps = {};
- this.matchMappings = {};
- for (var key in this.states) {
- var state = this.states[key];
- var ruleRegExps = [];
- var matchTotal = 0;
- var mapping = this.matchMappings[key] = {defaultToken: "text"};
- var flag = "g";
-
- var splitterRurles = [];
- for (var i = 0; i < state.length; i++) {
- var rule = state[i];
- if (rule.defaultToken)
- mapping.defaultToken = rule.defaultToken;
- if (rule.caseInsensitive)
- flag = "gi";
- if (rule.regex == null)
- continue;
-
- if (rule.regex instanceof RegExp)
- rule.regex = rule.regex.toString().slice(1, -1);
- var adjustedregex = rule.regex;
- var matchcount = new RegExp("(?:(" + adjustedregex + ")|(.))").exec("a").length - 2;
- if (Array.isArray(rule.token)) {
- if (rule.token.length == 1 || matchcount == 1) {
- rule.token = rule.token[0];
- } else if (matchcount - 1 != rule.token.length) {
- this.reportError("number of classes and regexp groups doesn't match", {
- rule: rule,
- groupCount: matchcount - 1
- });
- rule.token = rule.token[0];
- } else {
- rule.tokenArray = rule.token;
- rule.token = null;
- rule.onMatch = this.$arrayTokens;
- }
- } else if (typeof rule.token == "function" && !rule.onMatch) {
- if (matchcount > 1)
- rule.onMatch = this.$applyToken;
- else
- rule.onMatch = rule.token;
- }
-
- if (matchcount > 1) {
- if (/\\\d/.test(rule.regex)) {
- adjustedregex = rule.regex.replace(/\\([0-9]+)/g, function(match, digit) {
- return "\\" + (parseInt(digit, 10) + matchTotal + 1);
- });
- } else {
- matchcount = 1;
- adjustedregex = this.removeCapturingGroups(rule.regex);
- }
- if (!rule.splitRegex && typeof rule.token != "string")
- splitterRurles.push(rule); // flag will be known only at the very end
- }
-
- mapping[matchTotal] = i;
- matchTotal += matchcount;
-
- ruleRegExps.push(adjustedregex);
- if (!rule.onMatch)
- rule.onMatch = null;
- }
-
- if (!ruleRegExps.length) {
- mapping[0] = 0;
- ruleRegExps.push("$");
- }
-
- splitterRurles.forEach(function(rule) {
- rule.splitRegex = this.createSplitterRegexp(rule.regex, flag);
- }, this);
-
- this.regExps[key] = new RegExp("(" + ruleRegExps.join(")|(") + ")|($)", flag);
- }
-};
-
-(function() {
- this.$setMaxTokenCount = function(m) {
- MAX_TOKEN_COUNT = m | 0;
- };
-
- this.$applyToken = function(str) {
- var values = this.splitRegex.exec(str).slice(1);
- var types = this.token.apply(this, values);
- if (typeof types === "string")
- return [{type: types, value: str}];
-
- var tokens = [];
- for (var i = 0, l = types.length; i < l; i++) {
- if (values[i])
- tokens[tokens.length] = {
- type: types[i],
- value: values[i]
- };
- }
- return tokens;
- };
-
- this.$arrayTokens = function(str) {
- if (!str)
- return [];
- var values = this.splitRegex.exec(str);
- if (!values)
- return "text";
- var tokens = [];
- var types = this.tokenArray;
- for (var i = 0, l = types.length; i < l; i++) {
- if (values[i + 1])
- tokens[tokens.length] = {
- type: types[i],
- value: values[i + 1]
- };
- }
- return tokens;
- };
-
- this.removeCapturingGroups = function(src) {
- var r = src.replace(
- /\[(?:\\.|[^\]])*?\]|\\.|\(\?[:=!]|(\()/g,
- function(x, y) {return y ? "(?:" : x;}
- );
- return r;
- };
-
- this.createSplitterRegexp = function(src, flag) {
- if (src.indexOf("(?=") != -1) {
- var stack = 0;
- var inChClass = false;
- var lastCapture = {};
- src.replace(/(\\.)|(\((?:\?[=!])?)|(\))|([\[\]])/g, function(
- m, esc, parenOpen, parenClose, square, index
- ) {
- if (inChClass) {
- inChClass = square != "]";
- } else if (square) {
- inChClass = true;
- } else if (parenClose) {
- if (stack == lastCapture.stack) {
- lastCapture.end = index+1;
- lastCapture.stack = -1;
- }
- stack--;
- } else if (parenOpen) {
- stack++;
- if (parenOpen.length != 1) {
- lastCapture.stack = stack
- lastCapture.start = index;
- }
- }
- return m;
- });
-
- if (lastCapture.end != null && /^\)*$/.test(src.substr(lastCapture.end)))
- src = src.substring(0, lastCapture.start) + src.substr(lastCapture.end);
- }
- if (src.charAt(0) != "^") src = "^" + src;
- if (src.charAt(src.length - 1) != "$") src += "$";
-
- return new RegExp(src, (flag||"").replace("g", ""));
- };
- this.getLineTokens = function(line, startState) {
- if (startState && typeof startState != "string") {
- var stack = startState.slice(0);
- startState = stack[0];
- if (startState === "#tmp") {
- stack.shift()
- startState = stack.shift()
- }
- } else
- var stack = [];
-
- var currentState = startState || "start";
- var state = this.states[currentState];
- if (!state) {
- currentState = "start";
- state = this.states[currentState];
- }
- var mapping = this.matchMappings[currentState];
- var re = this.regExps[currentState];
- re.lastIndex = 0;
-
- var match, tokens = [];
- var lastIndex = 0;
- var matchAttempts = 0;
-
- var token = {type: null, value: ""};
-
- while (match = re.exec(line)) {
- var type = mapping.defaultToken;
- var rule = null;
- var value = match[0];
- var index = re.lastIndex;
-
- if (index - value.length > lastIndex) {
- var skipped = line.substring(lastIndex, index - value.length);
- if (token.type == type) {
- token.value += skipped;
- } else {
- if (token.type)
- tokens.push(token);
- token = {type: type, value: skipped};
- }
- }
-
- for (var i = 0; i < match.length-2; i++) {
- if (match[i + 1] === undefined)
- continue;
-
- rule = state[mapping[i]];
-
- if (rule.onMatch)
- type = rule.onMatch(value, currentState, stack);
- else
- type = rule.token;
-
- if (rule.next) {
- if (typeof rule.next == "string") {
- currentState = rule.next;
- } else {
- currentState = rule.next(currentState, stack);
- }
-
- state = this.states[currentState];
- if (!state) {
- this.reportError("state doesn't exist", currentState);
- currentState = "start";
- state = this.states[currentState];
- }
- mapping = this.matchMappings[currentState];
- lastIndex = index;
- re = this.regExps[currentState];
- re.lastIndex = index;
- }
- break;
- }
-
- if (value) {
- if (typeof type === "string") {
- if ((!rule || rule.merge !== false) && token.type === type) {
- token.value += value;
- } else {
- if (token.type)
- tokens.push(token);
- token = {type: type, value: value};
- }
- } else if (type) {
- if (token.type)
- tokens.push(token);
- token = {type: null, value: ""};
- for (var i = 0; i < type.length; i++)
- tokens.push(type[i]);
- }
- }
-
- if (lastIndex == line.length)
- break;
-
- lastIndex = index;
-
- if (matchAttempts++ > MAX_TOKEN_COUNT) {
- if (matchAttempts > 2 * line.length) {
- this.reportError("infinite loop with in ace tokenizer", {
- startState: startState,
- line: line
- });
- }
- while (lastIndex < line.length) {
- if (token.type)
- tokens.push(token);
- token = {
- value: line.substring(lastIndex, lastIndex += 2000),
- type: "overflow"
- };
- }
- currentState = "start";
- stack = [];
- break;
- }
- }
-
- if (token.type)
- tokens.push(token);
-
- if (stack.length > 1) {
- if (stack[0] !== currentState)
- stack.unshift("#tmp", currentState);
- }
- return {
- tokens : tokens,
- state : stack.length ? stack : currentState
- };
- };
-
- this.reportError = config.reportError;
-
-}).call(Tokenizer.prototype);
-
-exports.Tokenizer = Tokenizer;
-});
-
-ace.define("ace/mode/text_highlight_rules",["require","exports","module","ace/lib/lang"], function(require, exports, module) {
-"use strict";
-
-var lang = require("../lib/lang");
-
-var TextHighlightRules = function() {
-
- this.$rules = {
- "start" : [{
- token : "empty_line",
- regex : '^$'
- }, {
- defaultToken : "text"
- }]
- };
-};
-
-(function() {
-
- this.addRules = function(rules, prefix) {
- if (!prefix) {
- for (var key in rules)
- this.$rules[key] = rules[key];
- return;
- }
- for (var key in rules) {
- var state = rules[key];
- for (var i = 0; i < state.length; i++) {
- var rule = state[i];
- if (rule.next || rule.onMatch) {
- if (typeof rule.next == "string") {
- if (rule.next.indexOf(prefix) !== 0)
- rule.next = prefix + rule.next;
- }
- if (rule.nextState && rule.nextState.indexOf(prefix) !== 0)
- rule.nextState = prefix + rule.nextState;
- }
- }
- this.$rules[prefix + key] = state;
- }
- };
-
- this.getRules = function() {
- return this.$rules;
- };
-
- this.embedRules = function (HighlightRules, prefix, escapeRules, states, append) {
- var embedRules = typeof HighlightRules == "function"
- ? new HighlightRules().getRules()
- : HighlightRules;
- if (states) {
- for (var i = 0; i < states.length; i++)
- states[i] = prefix + states[i];
- } else {
- states = [];
- for (var key in embedRules)
- states.push(prefix + key);
- }
-
- this.addRules(embedRules, prefix);
-
- if (escapeRules) {
- var addRules = Array.prototype[append ? "push" : "unshift"];
- for (var i = 0; i < states.length; i++)
- addRules.apply(this.$rules[states[i]], lang.deepCopy(escapeRules));
- }
-
- if (!this.$embeds)
- this.$embeds = [];
- this.$embeds.push(prefix);
- };
-
- this.getEmbeds = function() {
- return this.$embeds;
- };
-
- var pushState = function(currentState, stack) {
- if (currentState != "start" || stack.length)
- stack.unshift(this.nextState, currentState);
- return this.nextState;
- };
- var popState = function(currentState, stack) {
- stack.shift();
- return stack.shift() || "start";
- };
-
- this.normalizeRules = function() {
- var id = 0;
- var rules = this.$rules;
- function processState(key) {
- var state = rules[key];
- state.processed = true;
- for (var i = 0; i < state.length; i++) {
- var rule = state[i];
- if (!rule.regex && rule.start) {
- rule.regex = rule.start;
- if (!rule.next)
- rule.next = [];
- rule.next.push({
- defaultToken: rule.token
- }, {
- token: rule.token + ".end",
- regex: rule.end || rule.start,
- next: "pop"
- });
- rule.token = rule.token + ".start";
- rule.push = true;
- }
- var next = rule.next || rule.push;
- if (next && Array.isArray(next)) {
- var stateName = rule.stateName;
- if (!stateName) {
- stateName = rule.token;
- if (typeof stateName != "string")
- stateName = stateName[0] || "";
- if (rules[stateName])
- stateName += id++;
- }
- rules[stateName] = next;
- rule.next = stateName;
- processState(stateName);
- } else if (next == "pop") {
- rule.next = popState;
- }
-
- if (rule.push) {
- rule.nextState = rule.next || rule.push;
- rule.next = pushState;
- delete rule.push;
- }
-
- if (rule.rules) {
- for (var r in rule.rules) {
- if (rules[r]) {
- if (rules[r].push)
- rules[r].push.apply(rules[r], rule.rules[r]);
- } else {
- rules[r] = rule.rules[r];
- }
- }
- }
- if (rule.include || typeof rule == "string") {
- var includeName = rule.include || rule;
- var toInsert = rules[includeName];
- } else if (Array.isArray(rule))
- toInsert = rule;
-
- if (toInsert) {
- var args = [i, 1].concat(toInsert);
- if (rule.noEscape)
- args = args.filter(function(x) {return !x.next;});
- state.splice.apply(state, args);
- i--;
- toInsert = null;
- }
-
- if (rule.keywordMap) {
- rule.token = this.createKeywordMapper(
- rule.keywordMap, rule.defaultToken || "text", rule.caseInsensitive
- );
- delete rule.defaultToken;
- }
- }
- }
- Object.keys(rules).forEach(processState, this);
- };
-
- this.createKeywordMapper = function(map, defaultToken, ignoreCase, splitChar) {
- var keywords = Object.create(null);
- Object.keys(map).forEach(function(className) {
- var a = map[className];
- if (ignoreCase)
- a = a.toLowerCase();
- var list = a.split(splitChar || "|");
- for (var i = list.length; i--; )
- keywords[list[i]] = className;
- });
- if (Object.getPrototypeOf(keywords)) {
- keywords.__proto__ = null;
- }
- this.$keywordList = Object.keys(keywords);
- map = null;
- return ignoreCase
- ? function(value) {return keywords[value.toLowerCase()] || defaultToken }
- : function(value) {return keywords[value] || defaultToken };
- };
-
- this.getKeywords = function() {
- return this.$keywords;
- };
-
-}).call(TextHighlightRules.prototype);
-
-exports.TextHighlightRules = TextHighlightRules;
-});
-
-ace.define("ace/mode/behaviour",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-var Behaviour = function() {
- this.$behaviours = {};
-};
-
-(function () {
-
- this.add = function (name, action, callback) {
- switch (undefined) {
- case this.$behaviours:
- this.$behaviours = {};
- case this.$behaviours[name]:
- this.$behaviours[name] = {};
- }
- this.$behaviours[name][action] = callback;
- }
-
- this.addBehaviours = function (behaviours) {
- for (var key in behaviours) {
- for (var action in behaviours[key]) {
- this.add(key, action, behaviours[key][action]);
- }
- }
- }
-
- this.remove = function (name) {
- if (this.$behaviours && this.$behaviours[name]) {
- delete this.$behaviours[name];
- }
- }
-
- this.inherit = function (mode, filter) {
- if (typeof mode === "function") {
- var behaviours = new mode().getBehaviours(filter);
- } else {
- var behaviours = mode.getBehaviours(filter);
- }
- this.addBehaviours(behaviours);
- }
-
- this.getBehaviours = function (filter) {
- if (!filter) {
- return this.$behaviours;
- } else {
- var ret = {}
- for (var i = 0; i < filter.length; i++) {
- if (this.$behaviours[filter[i]]) {
- ret[filter[i]] = this.$behaviours[filter[i]];
- }
- }
- return ret;
- }
- }
-
-}).call(Behaviour.prototype);
-
-exports.Behaviour = Behaviour;
-});
-
-ace.define("ace/unicode",["require","exports","module"], function(require, exports, module) {
-"use strict";
-exports.packages = {};
-
-addUnicodePackage({
- L: "0041-005A0061-007A00AA00B500BA00C0-00D600D8-00F600F8-02C102C6-02D102E0-02E402EC02EE0370-037403760377037A-037D03860388-038A038C038E-03A103A3-03F503F7-0481048A-05250531-055605590561-058705D0-05EA05F0-05F20621-064A066E066F0671-06D306D506E506E606EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA07F407F507FA0800-0815081A082408280904-0939093D09500958-0961097109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E460E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EC60EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10A0-10C510D0-10FA10FC1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317D717DC1820-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541AA71B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C7D1CE9-1CEC1CEE-1CF11D00-1DBF1E00-1F151F18-1F1D1F20-1F451F48-1F4D1F50-1F571F591F5B1F5D1F5F-1F7D1F80-1FB41FB6-1FBC1FBE1FC2-1FC41FC6-1FCC1FD0-1FD31FD6-1FDB1FE0-1FEC1FF2-1FF41FF6-1FFC2071207F2090-209421022107210A-211321152119-211D212421262128212A-212D212F-2139213C-213F2145-2149214E218321842C00-2C2E2C30-2C5E2C60-2CE42CEB-2CEE2D00-2D252D30-2D652D6F2D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE2E2F300530063031-3035303B303C3041-3096309D-309F30A1-30FA30FC-30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A48CA4D0-A4FDA500-A60CA610-A61FA62AA62BA640-A65FA662-A66EA67F-A697A6A0-A6E5A717-A71FA722-A788A78BA78CA7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2A9CFAA00-AA28AA40-AA42AA44-AA4BAA60-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADB-AADDABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB00-FB06FB13-FB17FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF21-FF3AFF41-FF5AFF66-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC",
- Ll: "0061-007A00AA00B500BA00DF-00F600F8-00FF01010103010501070109010B010D010F01110113011501170119011B011D011F01210123012501270129012B012D012F01310133013501370138013A013C013E014001420144014601480149014B014D014F01510153015501570159015B015D015F01610163016501670169016B016D016F0171017301750177017A017C017E-0180018301850188018C018D019201950199-019B019E01A101A301A501A801AA01AB01AD01B001B401B601B901BA01BD-01BF01C601C901CC01CE01D001D201D401D601D801DA01DC01DD01DF01E101E301E501E701E901EB01ED01EF01F001F301F501F901FB01FD01FF02010203020502070209020B020D020F02110213021502170219021B021D021F02210223022502270229022B022D022F02310233-0239023C023F0240024202470249024B024D024F-02930295-02AF037103730377037B-037D039003AC-03CE03D003D103D5-03D703D903DB03DD03DF03E103E303E503E703E903EB03ED03EF-03F303F503F803FB03FC0430-045F04610463046504670469046B046D046F04710473047504770479047B047D047F0481048B048D048F04910493049504970499049B049D049F04A104A304A504A704A904AB04AD04AF04B104B304B504B704B904BB04BD04BF04C204C404C604C804CA04CC04CE04CF04D104D304D504D704D904DB04DD04DF04E104E304E504E704E904EB04ED04EF04F104F304F504F704F904FB04FD04FF05010503050505070509050B050D050F05110513051505170519051B051D051F0521052305250561-05871D00-1D2B1D62-1D771D79-1D9A1E011E031E051E071E091E0B1E0D1E0F1E111E131E151E171E191E1B1E1D1E1F1E211E231E251E271E291E2B1E2D1E2F1E311E331E351E371E391E3B1E3D1E3F1E411E431E451E471E491E4B1E4D1E4F1E511E531E551E571E591E5B1E5D1E5F1E611E631E651E671E691E6B1E6D1E6F1E711E731E751E771E791E7B1E7D1E7F1E811E831E851E871E891E8B1E8D1E8F1E911E931E95-1E9D1E9F1EA11EA31EA51EA71EA91EAB1EAD1EAF1EB11EB31EB51EB71EB91EBB1EBD1EBF1EC11EC31EC51EC71EC91ECB1ECD1ECF1ED11ED31ED51ED71ED91EDB1EDD1EDF1EE11EE31EE51EE71EE91EEB1EED1EEF1EF11EF31EF51EF71EF91EFB1EFD1EFF-1F071F10-1F151F20-1F271F30-1F371F40-1F451F50-1F571F60-1F671F70-1F7D1F80-1F871F90-1F971FA0-1FA71FB0-1FB41FB61FB71FBE1FC2-1FC41FC61FC71FD0-1FD31FD61FD71FE0-1FE71FF2-1FF41FF61FF7210A210E210F2113212F21342139213C213D2146-2149214E21842C30-2C5E2C612C652C662C682C6A2C6C2C712C732C742C76-2C7C2C812C832C852C872C892C8B2C8D2C8F2C912C932C952C972C992C9B2C9D2C9F2CA12CA32CA52CA72CA92CAB2CAD2CAF2CB12CB32CB52CB72CB92CBB2CBD2CBF2CC12CC32CC52CC72CC92CCB2CCD2CCF2CD12CD32CD52CD72CD92CDB2CDD2CDF2CE12CE32CE42CEC2CEE2D00-2D25A641A643A645A647A649A64BA64DA64FA651A653A655A657A659A65BA65DA65FA663A665A667A669A66BA66DA681A683A685A687A689A68BA68DA68FA691A693A695A697A723A725A727A729A72BA72DA72F-A731A733A735A737A739A73BA73DA73FA741A743A745A747A749A74BA74DA74FA751A753A755A757A759A75BA75DA75FA761A763A765A767A769A76BA76DA76FA771-A778A77AA77CA77FA781A783A785A787A78CFB00-FB06FB13-FB17FF41-FF5A",
- Lu: "0041-005A00C0-00D600D8-00DE01000102010401060108010A010C010E01100112011401160118011A011C011E01200122012401260128012A012C012E01300132013401360139013B013D013F0141014301450147014A014C014E01500152015401560158015A015C015E01600162016401660168016A016C016E017001720174017601780179017B017D018101820184018601870189-018B018E-0191019301940196-0198019C019D019F01A001A201A401A601A701A901AC01AE01AF01B1-01B301B501B701B801BC01C401C701CA01CD01CF01D101D301D501D701D901DB01DE01E001E201E401E601E801EA01EC01EE01F101F401F6-01F801FA01FC01FE02000202020402060208020A020C020E02100212021402160218021A021C021E02200222022402260228022A022C022E02300232023A023B023D023E02410243-02460248024A024C024E03700372037603860388-038A038C038E038F0391-03A103A3-03AB03CF03D2-03D403D803DA03DC03DE03E003E203E403E603E803EA03EC03EE03F403F703F903FA03FD-042F04600462046404660468046A046C046E04700472047404760478047A047C047E0480048A048C048E04900492049404960498049A049C049E04A004A204A404A604A804AA04AC04AE04B004B204B404B604B804BA04BC04BE04C004C104C304C504C704C904CB04CD04D004D204D404D604D804DA04DC04DE04E004E204E404E604E804EA04EC04EE04F004F204F404F604F804FA04FC04FE05000502050405060508050A050C050E05100512051405160518051A051C051E0520052205240531-055610A0-10C51E001E021E041E061E081E0A1E0C1E0E1E101E121E141E161E181E1A1E1C1E1E1E201E221E241E261E281E2A1E2C1E2E1E301E321E341E361E381E3A1E3C1E3E1E401E421E441E461E481E4A1E4C1E4E1E501E521E541E561E581E5A1E5C1E5E1E601E621E641E661E681E6A1E6C1E6E1E701E721E741E761E781E7A1E7C1E7E1E801E821E841E861E881E8A1E8C1E8E1E901E921E941E9E1EA01EA21EA41EA61EA81EAA1EAC1EAE1EB01EB21EB41EB61EB81EBA1EBC1EBE1EC01EC21EC41EC61EC81ECA1ECC1ECE1ED01ED21ED41ED61ED81EDA1EDC1EDE1EE01EE21EE41EE61EE81EEA1EEC1EEE1EF01EF21EF41EF61EF81EFA1EFC1EFE1F08-1F0F1F18-1F1D1F28-1F2F1F38-1F3F1F48-1F4D1F591F5B1F5D1F5F1F68-1F6F1FB8-1FBB1FC8-1FCB1FD8-1FDB1FE8-1FEC1FF8-1FFB21022107210B-210D2110-211221152119-211D212421262128212A-212D2130-2133213E213F214521832C00-2C2E2C602C62-2C642C672C692C6B2C6D-2C702C722C752C7E-2C802C822C842C862C882C8A2C8C2C8E2C902C922C942C962C982C9A2C9C2C9E2CA02CA22CA42CA62CA82CAA2CAC2CAE2CB02CB22CB42CB62CB82CBA2CBC2CBE2CC02CC22CC42CC62CC82CCA2CCC2CCE2CD02CD22CD42CD62CD82CDA2CDC2CDE2CE02CE22CEB2CEDA640A642A644A646A648A64AA64CA64EA650A652A654A656A658A65AA65CA65EA662A664A666A668A66AA66CA680A682A684A686A688A68AA68CA68EA690A692A694A696A722A724A726A728A72AA72CA72EA732A734A736A738A73AA73CA73EA740A742A744A746A748A74AA74CA74EA750A752A754A756A758A75AA75CA75EA760A762A764A766A768A76AA76CA76EA779A77BA77DA77EA780A782A784A786A78BFF21-FF3A",
- Lt: "01C501C801CB01F21F88-1F8F1F98-1F9F1FA8-1FAF1FBC1FCC1FFC",
- Lm: "02B0-02C102C6-02D102E0-02E402EC02EE0374037A0559064006E506E607F407F507FA081A0824082809710E460EC610FC17D718431AA71C78-1C7D1D2C-1D611D781D9B-1DBF2071207F2090-20942C7D2D6F2E2F30053031-3035303B309D309E30FC-30FEA015A4F8-A4FDA60CA67FA717-A71FA770A788A9CFAA70AADDFF70FF9EFF9F",
- Lo: "01BB01C0-01C3029405D0-05EA05F0-05F20621-063F0641-064A066E066F0671-06D306D506EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA0800-08150904-0939093D09500958-096109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E450E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10D0-10FA1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317DC1820-18421844-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C771CE9-1CEC1CEE-1CF12135-21382D30-2D652D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE3006303C3041-3096309F30A1-30FA30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A014A016-A48CA4D0-A4F7A500-A60BA610-A61FA62AA62BA66EA6A0-A6E5A7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2AA00-AA28AA40-AA42AA44-AA4BAA60-AA6FAA71-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADBAADCABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF66-FF6FFF71-FF9DFFA0-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC",
- M: "0300-036F0483-04890591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DE-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0903093C093E-094E0951-0955096209630981-098309BC09BE-09C409C709C809CB-09CD09D709E209E30A01-0A030A3C0A3E-0A420A470A480A4B-0A4D0A510A700A710A750A81-0A830ABC0ABE-0AC50AC7-0AC90ACB-0ACD0AE20AE30B01-0B030B3C0B3E-0B440B470B480B4B-0B4D0B560B570B620B630B820BBE-0BC20BC6-0BC80BCA-0BCD0BD70C01-0C030C3E-0C440C46-0C480C4A-0C4D0C550C560C620C630C820C830CBC0CBE-0CC40CC6-0CC80CCA-0CCD0CD50CD60CE20CE30D020D030D3E-0D440D46-0D480D4A-0D4D0D570D620D630D820D830DCA0DCF-0DD40DD60DD8-0DDF0DF20DF30E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F3E0F3F0F71-0F840F860F870F90-0F970F99-0FBC0FC6102B-103E1056-1059105E-10601062-10641067-106D1071-10741082-108D108F109A-109D135F1712-17141732-1734175217531772177317B6-17D317DD180B-180D18A91920-192B1930-193B19B0-19C019C819C91A17-1A1B1A55-1A5E1A60-1A7C1A7F1B00-1B041B34-1B441B6B-1B731B80-1B821BA1-1BAA1C24-1C371CD0-1CD21CD4-1CE81CED1CF21DC0-1DE61DFD-1DFF20D0-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66F-A672A67CA67DA6F0A6F1A802A806A80BA823-A827A880A881A8B4-A8C4A8E0-A8F1A926-A92DA947-A953A980-A983A9B3-A9C0AA29-AA36AA43AA4CAA4DAA7BAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE3-ABEAABECABEDFB1EFE00-FE0FFE20-FE26",
- Mn: "0300-036F0483-04870591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DF-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0902093C0941-0948094D0951-095509620963098109BC09C1-09C409CD09E209E30A010A020A3C0A410A420A470A480A4B-0A4D0A510A700A710A750A810A820ABC0AC1-0AC50AC70AC80ACD0AE20AE30B010B3C0B3F0B41-0B440B4D0B560B620B630B820BC00BCD0C3E-0C400C46-0C480C4A-0C4D0C550C560C620C630CBC0CBF0CC60CCC0CCD0CE20CE30D41-0D440D4D0D620D630DCA0DD2-0DD40DD60E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F71-0F7E0F80-0F840F860F870F90-0F970F99-0FBC0FC6102D-10301032-10371039103A103D103E10581059105E-10601071-1074108210851086108D109D135F1712-17141732-1734175217531772177317B7-17BD17C617C9-17D317DD180B-180D18A91920-19221927192819321939-193B1A171A181A561A58-1A5E1A601A621A65-1A6C1A73-1A7C1A7F1B00-1B031B341B36-1B3A1B3C1B421B6B-1B731B801B811BA2-1BA51BA81BA91C2C-1C331C361C371CD0-1CD21CD4-1CE01CE2-1CE81CED1DC0-1DE61DFD-1DFF20D0-20DC20E120E5-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66FA67CA67DA6F0A6F1A802A806A80BA825A826A8C4A8E0-A8F1A926-A92DA947-A951A980-A982A9B3A9B6-A9B9A9BCAA29-AA2EAA31AA32AA35AA36AA43AA4CAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE5ABE8ABEDFB1EFE00-FE0FFE20-FE26",
- Mc: "0903093E-09400949-094C094E0982098309BE-09C009C709C809CB09CC09D70A030A3E-0A400A830ABE-0AC00AC90ACB0ACC0B020B030B3E0B400B470B480B4B0B4C0B570BBE0BBF0BC10BC20BC6-0BC80BCA-0BCC0BD70C01-0C030C41-0C440C820C830CBE0CC0-0CC40CC70CC80CCA0CCB0CD50CD60D020D030D3E-0D400D46-0D480D4A-0D4C0D570D820D830DCF-0DD10DD8-0DDF0DF20DF30F3E0F3F0F7F102B102C10311038103B103C105610571062-10641067-106D108310841087-108C108F109A-109C17B617BE-17C517C717C81923-19261929-192B193019311933-193819B0-19C019C819C91A19-1A1B1A551A571A611A631A641A6D-1A721B041B351B3B1B3D-1B411B431B441B821BA11BA61BA71BAA1C24-1C2B1C341C351CE11CF2A823A824A827A880A881A8B4-A8C3A952A953A983A9B4A9B5A9BAA9BBA9BD-A9C0AA2FAA30AA33AA34AA4DAA7BABE3ABE4ABE6ABE7ABE9ABEAABEC",
- Me: "0488048906DE20DD-20E020E2-20E4A670-A672",
- N: "0030-003900B200B300B900BC-00BE0660-066906F0-06F907C0-07C90966-096F09E6-09EF09F4-09F90A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BF20C66-0C6F0C78-0C7E0CE6-0CEF0D66-0D750E50-0E590ED0-0ED90F20-0F331040-10491090-10991369-137C16EE-16F017E0-17E917F0-17F91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C5920702074-20792080-20892150-21822185-21892460-249B24EA-24FF2776-27932CFD30073021-30293038-303A3192-31953220-32293251-325F3280-328932B1-32BFA620-A629A6E6-A6EFA830-A835A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19",
- Nd: "0030-00390660-066906F0-06F907C0-07C90966-096F09E6-09EF0A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BEF0C66-0C6F0CE6-0CEF0D66-0D6F0E50-0E590ED0-0ED90F20-0F291040-10491090-109917E0-17E91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C59A620-A629A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19",
- Nl: "16EE-16F02160-21822185-218830073021-30293038-303AA6E6-A6EF",
- No: "00B200B300B900BC-00BE09F4-09F90BF0-0BF20C78-0C7E0D70-0D750F2A-0F331369-137C17F0-17F920702074-20792080-20892150-215F21892460-249B24EA-24FF2776-27932CFD3192-31953220-32293251-325F3280-328932B1-32BFA830-A835",
- P: "0021-00230025-002A002C-002F003A003B003F0040005B-005D005F007B007D00A100AB00B700BB00BF037E0387055A-055F0589058A05BE05C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F3A-0F3D0F850FD0-0FD4104A-104F10FB1361-13681400166D166E169B169C16EB-16ED1735173617D4-17D617D8-17DA1800-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD32010-20272030-20432045-20512053-205E207D207E208D208E2329232A2768-277527C527C627E6-27EF2983-299829D8-29DB29FC29FD2CF9-2CFC2CFE2CFF2E00-2E2E2E302E313001-30033008-30113014-301F3030303D30A030FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFD3EFD3FFE10-FE19FE30-FE52FE54-FE61FE63FE68FE6AFE6BFF01-FF03FF05-FF0AFF0C-FF0FFF1AFF1BFF1FFF20FF3B-FF3DFF3FFF5BFF5DFF5F-FF65",
- Pd: "002D058A05BE140018062010-20152E172E1A301C303030A0FE31FE32FE58FE63FF0D",
- Ps: "0028005B007B0F3A0F3C169B201A201E2045207D208D23292768276A276C276E27702772277427C527E627E827EA27EC27EE2983298529872989298B298D298F299129932995299729D829DA29FC2E222E242E262E283008300A300C300E3010301430163018301A301DFD3EFE17FE35FE37FE39FE3BFE3DFE3FFE41FE43FE47FE59FE5BFE5DFF08FF3BFF5BFF5FFF62",
- Pe: "0029005D007D0F3B0F3D169C2046207E208E232A2769276B276D276F27712773277527C627E727E927EB27ED27EF298429862988298A298C298E2990299229942996299829D929DB29FD2E232E252E272E293009300B300D300F3011301530173019301B301E301FFD3FFE18FE36FE38FE3AFE3CFE3EFE40FE42FE44FE48FE5AFE5CFE5EFF09FF3DFF5DFF60FF63",
- Pi: "00AB2018201B201C201F20392E022E042E092E0C2E1C2E20",
- Pf: "00BB2019201D203A2E032E052E0A2E0D2E1D2E21",
- Pc: "005F203F20402054FE33FE34FE4D-FE4FFF3F",
- Po: "0021-00230025-0027002A002C002E002F003A003B003F0040005C00A100B700BF037E0387055A-055F058905C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F850FD0-0FD4104A-104F10FB1361-1368166D166E16EB-16ED1735173617D4-17D617D8-17DA1800-18051807-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD3201620172020-20272030-2038203B-203E2041-20432047-205120532055-205E2CF9-2CFC2CFE2CFF2E002E012E06-2E082E0B2E0E-2E162E182E192E1B2E1E2E1F2E2A-2E2E2E302E313001-3003303D30FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFE10-FE16FE19FE30FE45FE46FE49-FE4CFE50-FE52FE54-FE57FE5F-FE61FE68FE6AFE6BFF01-FF03FF05-FF07FF0AFF0CFF0EFF0FFF1AFF1BFF1FFF20FF3CFF61FF64FF65",
- S: "0024002B003C-003E005E0060007C007E00A2-00A900AC00AE-00B100B400B600B800D700F702C2-02C502D2-02DF02E5-02EB02ED02EF-02FF03750384038503F604820606-0608060B060E060F06E906FD06FE07F609F209F309FA09FB0AF10B700BF3-0BFA0C7F0CF10CF20D790E3F0F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-139917DB194019E0-19FF1B61-1B6A1B74-1B7C1FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE20442052207A-207C208A-208C20A0-20B8210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B2140-2144214A-214D214F2190-2328232B-23E82400-24262440-244A249C-24E92500-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE27C0-27C427C7-27CA27CC27D0-27E527F0-29822999-29D729DC-29FB29FE-2B4C2B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F309B309C319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A700-A716A720A721A789A78AA828-A82BA836-A839AA77-AA79FB29FDFCFDFDFE62FE64-FE66FE69FF04FF0BFF1C-FF1EFF3EFF40FF5CFF5EFFE0-FFE6FFE8-FFEEFFFCFFFD",
- Sm: "002B003C-003E007C007E00AC00B100D700F703F60606-060820442052207A-207C208A-208C2140-2144214B2190-2194219A219B21A021A321A621AE21CE21CF21D221D421F4-22FF2308-230B23202321237C239B-23B323DC-23E125B725C125F8-25FF266F27C0-27C427C7-27CA27CC27D0-27E527F0-27FF2900-29822999-29D729DC-29FB29FE-2AFF2B30-2B442B47-2B4CFB29FE62FE64-FE66FF0BFF1C-FF1EFF5CFF5EFFE2FFE9-FFEC",
- Sc: "002400A2-00A5060B09F209F309FB0AF10BF90E3F17DB20A0-20B8A838FDFCFE69FF04FFE0FFE1FFE5FFE6",
- Sk: "005E006000A800AF00B400B802C2-02C502D2-02DF02E5-02EB02ED02EF-02FF0375038403851FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE309B309CA700-A716A720A721A789A78AFF3EFF40FFE3",
- So: "00A600A700A900AE00B000B60482060E060F06E906FD06FE07F609FA0B700BF3-0BF80BFA0C7F0CF10CF20D790F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-1399194019E0-19FF1B61-1B6A1B74-1B7C210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B214A214C214D214F2195-2199219C-219F21A121A221A421A521A7-21AD21AF-21CD21D021D121D321D5-21F32300-2307230C-231F2322-2328232B-237B237D-239A23B4-23DB23E2-23E82400-24262440-244A249C-24E92500-25B625B8-25C025C2-25F72600-266E2670-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE2800-28FF2B00-2B2F2B452B462B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A828-A82BA836A837A839AA77-AA79FDFDFFE4FFE8FFEDFFEEFFFCFFFD",
- Z: "002000A01680180E2000-200A20282029202F205F3000",
- Zs: "002000A01680180E2000-200A202F205F3000",
- Zl: "2028",
- Zp: "2029",
- C: "0000-001F007F-009F00AD03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-0605061C061D0620065F06DD070E070F074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17B417B517DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF200B-200F202A-202E2060-206F20722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-F8FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFD-FF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFFBFFFEFFFF",
- Cc: "0000-001F007F-009F",
- Cf: "00AD0600-060306DD070F17B417B5200B-200F202A-202E2060-2064206A-206FFEFFFFF9-FFFB",
- Co: "E000-F8FF",
- Cs: "D800-DFFF",
- Cn: "03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-05FF06040605061C061D0620065F070E074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF2065-206920722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-D7FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFDFEFEFF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFF8FFFEFFFF"
-});
-
-function addUnicodePackage (pack) {
- var codePoint = /\w{4}/g;
- for (var name in pack)
- exports.packages[name] = pack[name].replace(codePoint, "\\u$&");
-}
-
-});
-
-ace.define("ace/token_iterator",["require","exports","module"], function(require, exports, module) {
-"use strict";
-var TokenIterator = function(session, initialRow, initialColumn) {
- this.$session = session;
- this.$row = initialRow;
- this.$rowTokens = session.getTokens(initialRow);
-
- var token = session.getTokenAt(initialRow, initialColumn);
- this.$tokenIndex = token ? token.index : -1;
-};
-
-(function() {
- this.stepBackward = function() {
- this.$tokenIndex -= 1;
-
- while (this.$tokenIndex < 0) {
- this.$row -= 1;
- if (this.$row < 0) {
- this.$row = 0;
- return null;
- }
-
- this.$rowTokens = this.$session.getTokens(this.$row);
- this.$tokenIndex = this.$rowTokens.length - 1;
- }
-
- return this.$rowTokens[this.$tokenIndex];
- };
- this.stepForward = function() {
- this.$tokenIndex += 1;
- var rowCount;
- while (this.$tokenIndex >= this.$rowTokens.length) {
- this.$row += 1;
- if (!rowCount)
- rowCount = this.$session.getLength();
- if (this.$row >= rowCount) {
- this.$row = rowCount - 1;
- return null;
- }
-
- this.$rowTokens = this.$session.getTokens(this.$row);
- this.$tokenIndex = 0;
- }
-
- return this.$rowTokens[this.$tokenIndex];
- };
- this.getCurrentToken = function () {
- return this.$rowTokens[this.$tokenIndex];
- };
- this.getCurrentTokenRow = function () {
- return this.$row;
- };
- this.getCurrentTokenColumn = function() {
- var rowTokens = this.$rowTokens;
- var tokenIndex = this.$tokenIndex;
- var column = rowTokens[tokenIndex].start;
- if (column !== undefined)
- return column;
-
- column = 0;
- while (tokenIndex > 0) {
- tokenIndex -= 1;
- column += rowTokens[tokenIndex].value.length;
- }
-
- return column;
- };
- this.getCurrentTokenPosition = function() {
- return {row: this.$row, column: this.getCurrentTokenColumn()};
- };
-
-}).call(TokenIterator.prototype);
-
-exports.TokenIterator = TokenIterator;
-});
-
-ace.define("ace/mode/text",["require","exports","module","ace/tokenizer","ace/mode/text_highlight_rules","ace/mode/behaviour","ace/unicode","ace/lib/lang","ace/token_iterator","ace/range"], function(require, exports, module) {
-"use strict";
-
-var Tokenizer = require("../tokenizer").Tokenizer;
-var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
-var Behaviour = require("./behaviour").Behaviour;
-var unicode = require("../unicode");
-var lang = require("../lib/lang");
-var TokenIterator = require("../token_iterator").TokenIterator;
-var Range = require("../range").Range;
-
-var Mode = function() {
- this.HighlightRules = TextHighlightRules;
- this.$behaviour = new Behaviour();
-};
-
-(function() {
-
- this.tokenRe = new RegExp("^["
- + unicode.packages.L
- + unicode.packages.Mn + unicode.packages.Mc
- + unicode.packages.Nd
- + unicode.packages.Pc + "\\$_]+", "g"
- );
-
- this.nonTokenRe = new RegExp("^(?:[^"
- + unicode.packages.L
- + unicode.packages.Mn + unicode.packages.Mc
- + unicode.packages.Nd
- + unicode.packages.Pc + "\\$_]|\\s])+", "g"
- );
-
- this.getTokenizer = function() {
- if (!this.$tokenizer) {
- this.$highlightRules = this.$highlightRules || new this.HighlightRules();
- this.$tokenizer = new Tokenizer(this.$highlightRules.getRules());
- }
- return this.$tokenizer;
- };
-
- this.lineCommentStart = "";
- this.blockComment = "";
-
- this.toggleCommentLines = function(state, session, startRow, endRow) {
- var doc = session.doc;
-
- var ignoreBlankLines = true;
- var shouldRemove = true;
- var minIndent = Infinity;
- var tabSize = session.getTabSize();
- var insertAtTabStop = false;
-
- if (!this.lineCommentStart) {
- if (!this.blockComment)
- return false;
- var lineCommentStart = this.blockComment.start;
- var lineCommentEnd = this.blockComment.end;
- var regexpStart = new RegExp("^(\\s*)(?:" + lang.escapeRegExp(lineCommentStart) + ")");
- var regexpEnd = new RegExp("(?:" + lang.escapeRegExp(lineCommentEnd) + ")\\s*$");
-
- var comment = function(line, i) {
- if (testRemove(line, i))
- return;
- if (!ignoreBlankLines || /\S/.test(line)) {
- doc.insertInLine({row: i, column: line.length}, lineCommentEnd);
- doc.insertInLine({row: i, column: minIndent}, lineCommentStart);
- }
- };
-
- var uncomment = function(line, i) {
- var m;
- if (m = line.match(regexpEnd))
- doc.removeInLine(i, line.length - m[0].length, line.length);
- if (m = line.match(regexpStart))
- doc.removeInLine(i, m[1].length, m[0].length);
- };
-
- var testRemove = function(line, row) {
- if (regexpStart.test(line))
- return true;
- var tokens = session.getTokens(row);
- for (var i = 0; i < tokens.length; i++) {
- if (tokens[i].type === "comment")
- return true;
- }
- };
- } else {
- if (Array.isArray(this.lineCommentStart)) {
- var regexpStart = this.lineCommentStart.map(lang.escapeRegExp).join("|");
- var lineCommentStart = this.lineCommentStart[0];
- } else {
- var regexpStart = lang.escapeRegExp(this.lineCommentStart);
- var lineCommentStart = this.lineCommentStart;
- }
- regexpStart = new RegExp("^(\\s*)(?:" + regexpStart + ") ?");
-
- insertAtTabStop = session.getUseSoftTabs();
-
- var uncomment = function(line, i) {
- var m = line.match(regexpStart);
- if (!m) return;
- var start = m[1].length, end = m[0].length;
- if (!shouldInsertSpace(line, start, end) && m[0][end - 1] == " ")
- end--;
- doc.removeInLine(i, start, end);
- };
- var commentWithSpace = lineCommentStart + " ";
- var comment = function(line, i) {
- if (!ignoreBlankLines || /\S/.test(line)) {
- if (shouldInsertSpace(line, minIndent, minIndent))
- doc.insertInLine({row: i, column: minIndent}, commentWithSpace);
- else
- doc.insertInLine({row: i, column: minIndent}, lineCommentStart);
- }
- };
- var testRemove = function(line, i) {
- return regexpStart.test(line);
- };
-
- var shouldInsertSpace = function(line, before, after) {
- var spaces = 0;
- while (before-- && line.charAt(before) == " ")
- spaces++;
- if (spaces % tabSize != 0)
- return false;
- var spaces = 0;
- while (line.charAt(after++) == " ")
- spaces++;
- if (tabSize > 2)
- return spaces % tabSize != tabSize - 1;
- else
- return spaces % tabSize == 0;
- return true;
- };
- }
-
- function iter(fun) {
- for (var i = startRow; i <= endRow; i++)
- fun(doc.getLine(i), i);
- }
-
-
- var minEmptyLength = Infinity;
- iter(function(line, i) {
- var indent = line.search(/\S/);
- if (indent !== -1) {
- if (indent < minIndent)
- minIndent = indent;
- if (shouldRemove && !testRemove(line, i))
- shouldRemove = false;
- } else if (minEmptyLength > line.length) {
- minEmptyLength = line.length;
- }
- });
-
- if (minIndent == Infinity) {
- minIndent = minEmptyLength;
- ignoreBlankLines = false;
- shouldRemove = false;
- }
-
- if (insertAtTabStop && minIndent % tabSize != 0)
- minIndent = Math.floor(minIndent / tabSize) * tabSize;
-
- iter(shouldRemove ? uncomment : comment);
- };
-
- this.toggleBlockComment = function(state, session, range, cursor) {
- var comment = this.blockComment;
- if (!comment)
- return;
- if (!comment.start && comment[0])
- comment = comment[0];
-
- var iterator = new TokenIterator(session, cursor.row, cursor.column);
- var token = iterator.getCurrentToken();
-
- var sel = session.selection;
- var initialRange = session.selection.toOrientedRange();
- var startRow, colDiff;
-
- if (token && /comment/.test(token.type)) {
- var startRange, endRange;
- while (token && /comment/.test(token.type)) {
- var i = token.value.indexOf(comment.start);
- if (i != -1) {
- var row = iterator.getCurrentTokenRow();
- var column = iterator.getCurrentTokenColumn() + i;
- startRange = new Range(row, column, row, column + comment.start.length);
- break;
- }
- token = iterator.stepBackward();
- }
-
- var iterator = new TokenIterator(session, cursor.row, cursor.column);
- var token = iterator.getCurrentToken();
- while (token && /comment/.test(token.type)) {
- var i = token.value.indexOf(comment.end);
- if (i != -1) {
- var row = iterator.getCurrentTokenRow();
- var column = iterator.getCurrentTokenColumn() + i;
- endRange = new Range(row, column, row, column + comment.end.length);
- break;
- }
- token = iterator.stepForward();
- }
- if (endRange)
- session.remove(endRange);
- if (startRange) {
- session.remove(startRange);
- startRow = startRange.start.row;
- colDiff = -comment.start.length;
- }
- } else {
- colDiff = comment.start.length;
- startRow = range.start.row;
- session.insert(range.end, comment.end);
- session.insert(range.start, comment.start);
- }
- if (initialRange.start.row == startRow)
- initialRange.start.column += colDiff;
- if (initialRange.end.row == startRow)
- initialRange.end.column += colDiff;
- session.selection.fromOrientedRange(initialRange);
- };
-
- this.getNextLineIndent = function(state, line, tab) {
- return this.$getIndent(line);
- };
-
- this.checkOutdent = function(state, line, input) {
- return false;
- };
-
- this.autoOutdent = function(state, doc, row) {
- };
-
- this.$getIndent = function(line) {
- return line.match(/^\s*/)[0];
- };
-
- this.createWorker = function(session) {
- return null;
- };
-
- this.createModeDelegates = function (mapping) {
- this.$embeds = [];
- this.$modes = {};
- for (var i in mapping) {
- if (mapping[i]) {
- this.$embeds.push(i);
- this.$modes[i] = new mapping[i]();
- }
- }
-
- var delegations = ["toggleBlockComment", "toggleCommentLines", "getNextLineIndent",
- "checkOutdent", "autoOutdent", "transformAction", "getCompletions"];
-
- for (var i = 0; i < delegations.length; i++) {
- (function(scope) {
- var functionName = delegations[i];
- var defaultHandler = scope[functionName];
- scope[delegations[i]] = function() {
- return this.$delegator(functionName, arguments, defaultHandler);
- };
- }(this));
- }
- };
-
- this.$delegator = function(method, args, defaultHandler) {
- var state = args[0];
- if (typeof state != "string")
- state = state[0];
- for (var i = 0; i < this.$embeds.length; i++) {
- if (!this.$modes[this.$embeds[i]]) continue;
-
- var split = state.split(this.$embeds[i]);
- if (!split[0] && split[1]) {
- args[0] = split[1];
- var mode = this.$modes[this.$embeds[i]];
- return mode[method].apply(mode, args);
- }
- }
- var ret = defaultHandler.apply(this, args);
- return defaultHandler ? ret : undefined;
- };
-
- this.transformAction = function(state, action, editor, session, param) {
- if (this.$behaviour) {
- var behaviours = this.$behaviour.getBehaviours();
- for (var key in behaviours) {
- if (behaviours[key][action]) {
- var ret = behaviours[key][action].apply(this, arguments);
- if (ret) {
- return ret;
- }
- }
- }
- }
- };
-
- this.getKeywords = function(append) {
- if (!this.completionKeywords) {
- var rules = this.$tokenizer.rules;
- var completionKeywords = [];
- for (var rule in rules) {
- var ruleItr = rules[rule];
- for (var r = 0, l = ruleItr.length; r < l; r++) {
- if (typeof ruleItr[r].token === "string") {
- if (/keyword|support|storage/.test(ruleItr[r].token))
- completionKeywords.push(ruleItr[r].regex);
- }
- else if (typeof ruleItr[r].token === "object") {
- for (var a = 0, aLength = ruleItr[r].token.length; a < aLength; a++) {
- if (/keyword|support|storage/.test(ruleItr[r].token[a])) {
- var rule = ruleItr[r].regex.match(/\(.+?\)/g)[a];
- completionKeywords.push(rule.substr(1, rule.length - 2));
- }
- }
- }
- }
- }
- this.completionKeywords = completionKeywords;
- }
- if (!append)
- return this.$keywordList;
- return completionKeywords.concat(this.$keywordList || []);
- };
-
- this.$createKeywordList = function() {
- if (!this.$highlightRules)
- this.getTokenizer();
- return this.$keywordList = this.$highlightRules.$keywordList || [];
- };
-
- this.getCompletions = function(state, session, pos, prefix) {
- var keywords = this.$keywordList || this.$createKeywordList();
- return keywords.map(function(word) {
- return {
- name: word,
- value: word,
- score: 0,
- meta: "keyword"
- };
- });
- };
-
- this.$id = "ace/mode/text";
-}).call(Mode.prototype);
-
-exports.Mode = Mode;
-});
-
-ace.define("ace/apply_delta",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-function throwDeltaError(delta, errorText){
- console.log("Invalid Delta:", delta);
- throw "Invalid Delta: " + errorText;
-}
-
-function positionInDocument(docLines, position) {
- return position.row >= 0 && position.row < docLines.length &&
- position.column >= 0 && position.column <= docLines[position.row].length;
-}
-
-function validateDelta(docLines, delta) {
- if (delta.action != "insert" && delta.action != "remove")
- throwDeltaError(delta, "delta.action must be 'insert' or 'remove'");
- if (!(delta.lines instanceof Array))
- throwDeltaError(delta, "delta.lines must be an Array");
- if (!delta.start || !delta.end)
- throwDeltaError(delta, "delta.start/end must be an present");
- var start = delta.start;
- if (!positionInDocument(docLines, delta.start))
- throwDeltaError(delta, "delta.start must be contained in document");
- var end = delta.end;
- if (delta.action == "remove" && !positionInDocument(docLines, end))
- throwDeltaError(delta, "delta.end must contained in document for 'remove' actions");
- var numRangeRows = end.row - start.row;
- var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0));
- if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars)
- throwDeltaError(delta, "delta.range must match delta lines");
-}
-
-exports.applyDelta = function(docLines, delta, doNotValidate) {
-
- var row = delta.start.row;
- var startColumn = delta.start.column;
- var line = docLines[row] || "";
- switch (delta.action) {
- case "insert":
- var lines = delta.lines;
- if (lines.length === 1) {
- docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn);
- } else {
- var args = [row, 1].concat(delta.lines);
- docLines.splice.apply(docLines, args);
- docLines[row] = line.substring(0, startColumn) + docLines[row];
- docLines[row + delta.lines.length - 1] += line.substring(startColumn);
- }
- break;
- case "remove":
- var endColumn = delta.end.column;
- var endRow = delta.end.row;
- if (row === endRow) {
- docLines[row] = line.substring(0, startColumn) + line.substring(endColumn);
- } else {
- docLines.splice(
- row, endRow - row + 1,
- line.substring(0, startColumn) + docLines[endRow].substring(endColumn)
- );
- }
- break;
- }
-}
-});
-
-ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) {
-"use strict";
-
-var oop = require("./lib/oop");
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-
-var Anchor = exports.Anchor = function(doc, row, column) {
- this.$onChange = this.onChange.bind(this);
- this.attach(doc);
-
- if (typeof column == "undefined")
- this.setPosition(row.row, row.column);
- else
- this.setPosition(row, column);
-};
-
-(function() {
-
- oop.implement(this, EventEmitter);
- this.getPosition = function() {
- return this.$clipPositionToDocument(this.row, this.column);
- };
- this.getDocument = function() {
- return this.document;
- };
- this.$insertRight = false;
- this.onChange = function(delta) {
- if (delta.start.row == delta.end.row && delta.start.row != this.row)
- return;
-
- if (delta.start.row > this.row)
- return;
-
- var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight);
- this.setPosition(point.row, point.column, true);
- };
-
- function $pointsInOrder(point1, point2, equalPointsInOrder) {
- var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column;
- return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter);
- }
-
- function $getTransformedPoint(delta, point, moveIfEqual) {
- var deltaIsInsert = delta.action == "insert";
- var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row);
- var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column);
- var deltaStart = delta.start;
- var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range.
- if ($pointsInOrder(point, deltaStart, moveIfEqual)) {
- return {
- row: point.row,
- column: point.column
- };
- }
- if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) {
- return {
- row: point.row + deltaRowShift,
- column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0)
- };
- }
-
- return {
- row: deltaStart.row,
- column: deltaStart.column
- };
- }
- this.setPosition = function(row, column, noClip) {
- var pos;
- if (noClip) {
- pos = {
- row: row,
- column: column
- };
- } else {
- pos = this.$clipPositionToDocument(row, column);
- }
-
- if (this.row == pos.row && this.column == pos.column)
- return;
-
- var old = {
- row: this.row,
- column: this.column
- };
-
- this.row = pos.row;
- this.column = pos.column;
- this._signal("change", {
- old: old,
- value: pos
- });
- };
- this.detach = function() {
- this.document.removeEventListener("change", this.$onChange);
- };
- this.attach = function(doc) {
- this.document = doc || this.document;
- this.document.on("change", this.$onChange);
- };
- this.$clipPositionToDocument = function(row, column) {
- var pos = {};
-
- if (row >= this.document.getLength()) {
- pos.row = Math.max(0, this.document.getLength() - 1);
- pos.column = this.document.getLine(pos.row).length;
- }
- else if (row < 0) {
- pos.row = 0;
- pos.column = 0;
- }
- else {
- pos.row = row;
- pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column));
- }
-
- if (column < 0)
- pos.column = 0;
-
- return pos;
- };
-
-}).call(Anchor.prototype);
-
-});
-
-ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(require, exports, module) {
-"use strict";
-
-var oop = require("./lib/oop");
-var applyDelta = require("./apply_delta").applyDelta;
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-var Range = require("./range").Range;
-var Anchor = require("./anchor").Anchor;
-
-var Document = function(textOrLines) {
- this.$lines = [""];
- if (textOrLines.length === 0) {
- this.$lines = [""];
- } else if (Array.isArray(textOrLines)) {
- this.insertMergedLines({row: 0, column: 0}, textOrLines);
- } else {
- this.insert({row: 0, column:0}, textOrLines);
- }
-};
-
-(function() {
-
- oop.implement(this, EventEmitter);
- this.setValue = function(text) {
- var len = this.getLength() - 1;
- this.remove(new Range(0, 0, len, this.getLine(len).length));
- this.insert({row: 0, column: 0}, text);
- };
- this.getValue = function() {
- return this.getAllLines().join(this.getNewLineCharacter());
- };
- this.createAnchor = function(row, column) {
- return new Anchor(this, row, column);
- };
- if ("aaa".split(/a/).length === 0) {
- this.$split = function(text) {
- return text.replace(/\r\n|\r/g, "\n").split("\n");
- };
- } else {
- this.$split = function(text) {
- return text.split(/\r\n|\r|\n/);
- };
- }
-
-
- this.$detectNewLine = function(text) {
- var match = text.match(/^.*?(\r\n|\r|\n)/m);
- this.$autoNewLine = match ? match[1] : "\n";
- this._signal("changeNewLineMode");
- };
- this.getNewLineCharacter = function() {
- switch (this.$newLineMode) {
- case "windows":
- return "\r\n";
- case "unix":
- return "\n";
- default:
- return this.$autoNewLine || "\n";
- }
- };
-
- this.$autoNewLine = "";
- this.$newLineMode = "auto";
- this.setNewLineMode = function(newLineMode) {
- if (this.$newLineMode === newLineMode)
- return;
-
- this.$newLineMode = newLineMode;
- this._signal("changeNewLineMode");
- };
- this.getNewLineMode = function() {
- return this.$newLineMode;
- };
- this.isNewLine = function(text) {
- return (text == "\r\n" || text == "\r" || text == "\n");
- };
- this.getLine = function(row) {
- return this.$lines[row] || "";
- };
- this.getLines = function(firstRow, lastRow) {
- return this.$lines.slice(firstRow, lastRow + 1);
- };
- this.getAllLines = function() {
- return this.getLines(0, this.getLength());
- };
- this.getLength = function() {
- return this.$lines.length;
- };
- this.getTextRange = function(range) {
- return this.getLinesForRange(range).join(this.getNewLineCharacter());
- };
- this.getLinesForRange = function(range) {
- var lines;
- if (range.start.row === range.end.row) {
- lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)];
- } else {
- lines = this.getLines(range.start.row, range.end.row);
- lines[0] = (lines[0] || "").substring(range.start.column);
- var l = lines.length - 1;
- if (range.end.row - range.start.row == l)
- lines[l] = lines[l].substring(0, range.end.column);
- }
- return lines;
- };
- this.insertLines = function(row, lines) {
- console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead.");
- return this.insertFullLines(row, lines);
- };
- this.removeLines = function(firstRow, lastRow) {
- console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead.");
- return this.removeFullLines(firstRow, lastRow);
- };
- this.insertNewLine = function(position) {
- console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, [\'\', \'\']) instead.");
- return this.insertMergedLines(position, ["", ""]);
- };
- this.insert = function(position, text) {
- if (this.getLength() <= 1)
- this.$detectNewLine(text);
-
- return this.insertMergedLines(position, this.$split(text));
- };
- this.insertInLine = function(position, text) {
- var start = this.clippedPos(position.row, position.column);
- var end = this.pos(position.row, position.column + text.length);
-
- this.applyDelta({
- start: start,
- end: end,
- action: "insert",
- lines: [text]
- }, true);
-
- return this.clonePos(end);
- };
-
- this.clippedPos = function(row, column) {
- var length = this.getLength();
- if (row === undefined) {
- row = length;
- } else if (row < 0) {
- row = 0;
- } else if (row >= length) {
- row = length - 1;
- column = undefined;
- }
- var line = this.getLine(row);
- if (column == undefined)
- column = line.length;
- column = Math.min(Math.max(column, 0), line.length);
- return {row: row, column: column};
- };
-
- this.clonePos = function(pos) {
- return {row: pos.row, column: pos.column};
- };
-
- this.pos = function(row, column) {
- return {row: row, column: column};
- };
-
- this.$clipPosition = function(position) {
- var length = this.getLength();
- if (position.row >= length) {
- position.row = Math.max(0, length - 1);
- position.column = this.getLine(length - 1).length;
- } else {
- position.row = Math.max(0, position.row);
- position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length);
- }
- return position;
- };
- this.insertFullLines = function(row, lines) {
- row = Math.min(Math.max(row, 0), this.getLength());
- var column = 0;
- if (row < this.getLength()) {
- lines = lines.concat([""]);
- column = 0;
- } else {
- lines = [""].concat(lines);
- row--;
- column = this.$lines[row].length;
- }
- this.insertMergedLines({row: row, column: column}, lines);
- };
- this.insertMergedLines = function(position, lines) {
- var start = this.clippedPos(position.row, position.column);
- var end = {
- row: start.row + lines.length - 1,
- column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length
- };
-
- this.applyDelta({
- start: start,
- end: end,
- action: "insert",
- lines: lines
- });
-
- return this.clonePos(end);
- };
- this.remove = function(range) {
- var start = this.clippedPos(range.start.row, range.start.column);
- var end = this.clippedPos(range.end.row, range.end.column);
- this.applyDelta({
- start: start,
- end: end,
- action: "remove",
- lines: this.getLinesForRange({start: start, end: end})
- });
- return this.clonePos(start);
- };
- this.removeInLine = function(row, startColumn, endColumn) {
- var start = this.clippedPos(row, startColumn);
- var end = this.clippedPos(row, endColumn);
-
- this.applyDelta({
- start: start,
- end: end,
- action: "remove",
- lines: this.getLinesForRange({start: start, end: end})
- }, true);
-
- return this.clonePos(start);
- };
- this.removeFullLines = function(firstRow, lastRow) {
- firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1);
- lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1);
- var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0;
- var deleteLastNewLine = lastRow < this.getLength() - 1;
- var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow );
- var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 );
- var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow );
- var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length );
- var range = new Range(startRow, startCol, endRow, endCol);
- var deletedLines = this.$lines.slice(firstRow, lastRow + 1);
-
- this.applyDelta({
- start: range.start,
- end: range.end,
- action: "remove",
- lines: this.getLinesForRange(range)
- });
- return deletedLines;
- };
- this.removeNewLine = function(row) {
- if (row < this.getLength() - 1 && row >= 0) {
- this.applyDelta({
- start: this.pos(row, this.getLine(row).length),
- end: this.pos(row + 1, 0),
- action: "remove",
- lines: ["", ""]
- });
- }
- };
- this.replace = function(range, text) {
- if (!(range instanceof Range))
- range = Range.fromPoints(range.start, range.end);
- if (text.length === 0 && range.isEmpty())
- return range.start;
- if (text == this.getTextRange(range))
- return range.end;
-
- this.remove(range);
- var end;
- if (text) {
- end = this.insert(range.start, text);
- }
- else {
- end = range.start;
- }
-
- return end;
- };
- this.applyDeltas = function(deltas) {
- for (var i=0; i=0; i--) {
- this.revertDelta(deltas[i]);
- }
- };
- this.applyDelta = function(delta, doNotValidate) {
- var isInsert = delta.action == "insert";
- if (isInsert ? delta.lines.length <= 1 && !delta.lines[0]
- : !Range.comparePoints(delta.start, delta.end)) {
- return;
- }
-
- if (isInsert && delta.lines.length > 20000)
- this.$splitAndapplyLargeDelta(delta, 20000);
- applyDelta(this.$lines, delta, doNotValidate);
- this._signal("change", delta);
- };
-
- this.$splitAndapplyLargeDelta = function(delta, MAX) {
- var lines = delta.lines;
- var l = lines.length;
- var row = delta.start.row;
- var column = delta.start.column;
- var from = 0, to = 0;
- do {
- from = to;
- to += MAX - 1;
- var chunk = lines.slice(from, to);
- if (to > l) {
- delta.lines = chunk;
- delta.start.row = row + from;
- delta.start.column = column;
- break;
- }
- chunk.push("");
- this.applyDelta({
- start: this.pos(row + from, column),
- end: this.pos(row + to, column = 0),
- action: delta.action,
- lines: chunk
- }, true);
- } while(true);
- };
- this.revertDelta = function(delta) {
- this.applyDelta({
- start: this.clonePos(delta.start),
- end: this.clonePos(delta.end),
- action: (delta.action == "insert" ? "remove" : "insert"),
- lines: delta.lines.slice()
- });
- };
- this.indexToPosition = function(index, startRow) {
- var lines = this.$lines || this.getAllLines();
- var newlineLength = this.getNewLineCharacter().length;
- for (var i = startRow || 0, l = lines.length; i < l; i++) {
- index -= lines[i].length + newlineLength;
- if (index < 0)
- return {row: i, column: index + lines[i].length + newlineLength};
- }
- return {row: l-1, column: lines[l-1].length};
- };
- this.positionToIndex = function(pos, startRow) {
- var lines = this.$lines || this.getAllLines();
- var newlineLength = this.getNewLineCharacter().length;
- var index = 0;
- var row = Math.min(pos.row, lines.length);
- for (var i = startRow || 0; i < row; ++i)
- index += lines[i].length + newlineLength;
-
- return index + pos.column;
- };
-
-}).call(Document.prototype);
-
-exports.Document = Document;
-});
-
-ace.define("ace/background_tokenizer",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) {
-"use strict";
-
-var oop = require("./lib/oop");
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-
-var BackgroundTokenizer = function(tokenizer, editor) {
- this.running = false;
- this.lines = [];
- this.states = [];
- this.currentLine = 0;
- this.tokenizer = tokenizer;
-
- var self = this;
-
- this.$worker = function() {
- if (!self.running) { return; }
-
- var workerStart = new Date();
- var currentLine = self.currentLine;
- var endLine = -1;
- var doc = self.doc;
-
- var startLine = currentLine;
- while (self.lines[currentLine])
- currentLine++;
-
- var len = doc.getLength();
- var processedLines = 0;
- self.running = false;
- while (currentLine < len) {
- self.$tokenizeRow(currentLine);
- endLine = currentLine;
- do {
- currentLine++;
- } while (self.lines[currentLine]);
- processedLines ++;
- if ((processedLines % 5 === 0) && (new Date() - workerStart) > 20) {
- self.running = setTimeout(self.$worker, 20);
- break;
- }
- }
- self.currentLine = currentLine;
-
- if (startLine <= endLine)
- self.fireUpdateEvent(startLine, endLine);
- };
-};
-
-(function(){
-
- oop.implement(this, EventEmitter);
- this.setTokenizer = function(tokenizer) {
- this.tokenizer = tokenizer;
- this.lines = [];
- this.states = [];
-
- this.start(0);
- };
- this.setDocument = function(doc) {
- this.doc = doc;
- this.lines = [];
- this.states = [];
-
- this.stop();
- };
- this.fireUpdateEvent = function(firstRow, lastRow) {
- var data = {
- first: firstRow,
- last: lastRow
- };
- this._signal("update", {data: data});
- };
- this.start = function(startRow) {
- this.currentLine = Math.min(startRow || 0, this.currentLine, this.doc.getLength());
- this.lines.splice(this.currentLine, this.lines.length);
- this.states.splice(this.currentLine, this.states.length);
-
- this.stop();
- this.running = setTimeout(this.$worker, 700);
- };
-
- this.scheduleStart = function() {
- if (!this.running)
- this.running = setTimeout(this.$worker, 700);
- }
-
- this.$updateOnChange = function(delta) {
- var startRow = delta.start.row;
- var len = delta.end.row - startRow;
-
- if (len === 0) {
- this.lines[startRow] = null;
- } else if (delta.action == "remove") {
- this.lines.splice(startRow, len + 1, null);
- this.states.splice(startRow, len + 1, null);
- } else {
- var args = Array(len + 1);
- args.unshift(startRow, 1);
- this.lines.splice.apply(this.lines, args);
- this.states.splice.apply(this.states, args);
- }
-
- this.currentLine = Math.min(startRow, this.currentLine, this.doc.getLength());
-
- this.stop();
- };
- this.stop = function() {
- if (this.running)
- clearTimeout(this.running);
- this.running = false;
- };
- this.getTokens = function(row) {
- return this.lines[row] || this.$tokenizeRow(row);
- };
- this.getState = function(row) {
- if (this.currentLine == row)
- this.$tokenizeRow(row);
- return this.states[row] || "start";
- };
-
- this.$tokenizeRow = function(row) {
- var line = this.doc.getLine(row);
- var state = this.states[row - 1];
-
- var data = this.tokenizer.getLineTokens(line, state, row);
-
- if (this.states[row] + "" !== data.state + "") {
- this.states[row] = data.state;
- this.lines[row + 1] = null;
- if (this.currentLine > row + 1)
- this.currentLine = row + 1;
- } else if (this.currentLine == row) {
- this.currentLine = row + 1;
- }
-
- return this.lines[row] = data.tokens;
- };
-
-}).call(BackgroundTokenizer.prototype);
-
-exports.BackgroundTokenizer = BackgroundTokenizer;
-});
-
-ace.define("ace/search_highlight",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(require, exports, module) {
-"use strict";
-
-var lang = require("./lib/lang");
-var oop = require("./lib/oop");
-var Range = require("./range").Range;
-
-var SearchHighlight = function(regExp, clazz, type) {
- this.setRegexp(regExp);
- this.clazz = clazz;
- this.type = type || "text";
-};
-
-(function() {
- this.MAX_RANGES = 500;
-
- this.setRegexp = function(regExp) {
- if (this.regExp+"" == regExp+"")
- return;
- this.regExp = regExp;
- this.cache = [];
- };
-
- this.update = function(html, markerLayer, session, config) {
- if (!this.regExp)
- return;
- var start = config.firstRow, end = config.lastRow;
-
- for (var i = start; i <= end; i++) {
- var ranges = this.cache[i];
- if (ranges == null) {
- ranges = lang.getMatchOffsets(session.getLine(i), this.regExp);
- if (ranges.length > this.MAX_RANGES)
- ranges = ranges.slice(0, this.MAX_RANGES);
- ranges = ranges.map(function(match) {
- return new Range(i, match.offset, i, match.offset + match.length);
- });
- this.cache[i] = ranges.length ? ranges : "";
- }
-
- for (var j = ranges.length; j --; ) {
- markerLayer.drawSingleLineMarker(
- html, ranges[j].toScreenRange(session), this.clazz, config);
- }
- }
- };
-
-}).call(SearchHighlight.prototype);
-
-exports.SearchHighlight = SearchHighlight;
-});
-
-ace.define("ace/edit_session/fold_line",["require","exports","module","ace/range"], function(require, exports, module) {
-"use strict";
-
-var Range = require("../range").Range;
-function FoldLine(foldData, folds) {
- this.foldData = foldData;
- if (Array.isArray(folds)) {
- this.folds = folds;
- } else {
- folds = this.folds = [ folds ];
- }
-
- var last = folds[folds.length - 1];
- this.range = new Range(folds[0].start.row, folds[0].start.column,
- last.end.row, last.end.column);
- this.start = this.range.start;
- this.end = this.range.end;
-
- this.folds.forEach(function(fold) {
- fold.setFoldLine(this);
- }, this);
-}
-
-(function() {
- this.shiftRow = function(shift) {
- this.start.row += shift;
- this.end.row += shift;
- this.folds.forEach(function(fold) {
- fold.start.row += shift;
- fold.end.row += shift;
- });
- };
-
- this.addFold = function(fold) {
- if (fold.sameRow) {
- if (fold.start.row < this.startRow || fold.endRow > this.endRow) {
- throw new Error("Can't add a fold to this FoldLine as it has no connection");
- }
- this.folds.push(fold);
- this.folds.sort(function(a, b) {
- return -a.range.compareEnd(b.start.row, b.start.column);
- });
- if (this.range.compareEnd(fold.start.row, fold.start.column) > 0) {
- this.end.row = fold.end.row;
- this.end.column = fold.end.column;
- } else if (this.range.compareStart(fold.end.row, fold.end.column) < 0) {
- this.start.row = fold.start.row;
- this.start.column = fold.start.column;
- }
- } else if (fold.start.row == this.end.row) {
- this.folds.push(fold);
- this.end.row = fold.end.row;
- this.end.column = fold.end.column;
- } else if (fold.end.row == this.start.row) {
- this.folds.unshift(fold);
- this.start.row = fold.start.row;
- this.start.column = fold.start.column;
- } else {
- throw new Error("Trying to add fold to FoldRow that doesn't have a matching row");
- }
- fold.foldLine = this;
- };
-
- this.containsRow = function(row) {
- return row >= this.start.row && row <= this.end.row;
- };
-
- this.walk = function(callback, endRow, endColumn) {
- var lastEnd = 0,
- folds = this.folds,
- fold,
- cmp, stop, isNewRow = true;
-
- if (endRow == null) {
- endRow = this.end.row;
- endColumn = this.end.column;
- }
-
- for (var i = 0; i < folds.length; i++) {
- fold = folds[i];
-
- cmp = fold.range.compareStart(endRow, endColumn);
- if (cmp == -1) {
- callback(null, endRow, endColumn, lastEnd, isNewRow);
- return;
- }
-
- stop = callback(null, fold.start.row, fold.start.column, lastEnd, isNewRow);
- stop = !stop && callback(fold.placeholder, fold.start.row, fold.start.column, lastEnd);
- if (stop || cmp === 0) {
- return;
- }
- isNewRow = !fold.sameRow;
- lastEnd = fold.end.column;
- }
- callback(null, endRow, endColumn, lastEnd, isNewRow);
- };
-
- this.getNextFoldTo = function(row, column) {
- var fold, cmp;
- for (var i = 0; i < this.folds.length; i++) {
- fold = this.folds[i];
- cmp = fold.range.compareEnd(row, column);
- if (cmp == -1) {
- return {
- fold: fold,
- kind: "after"
- };
- } else if (cmp === 0) {
- return {
- fold: fold,
- kind: "inside"
- };
- }
- }
- return null;
- };
-
- this.addRemoveChars = function(row, column, len) {
- var ret = this.getNextFoldTo(row, column),
- fold, folds;
- if (ret) {
- fold = ret.fold;
- if (ret.kind == "inside"
- && fold.start.column != column
- && fold.start.row != row)
- {
- window.console && window.console.log(row, column, fold);
- } else if (fold.start.row == row) {
- folds = this.folds;
- var i = folds.indexOf(fold);
- if (i === 0) {
- this.start.column += len;
- }
- for (i; i < folds.length; i++) {
- fold = folds[i];
- fold.start.column += len;
- if (!fold.sameRow) {
- return;
- }
- fold.end.column += len;
- }
- this.end.column += len;
- }
- }
- };
-
- this.split = function(row, column) {
- var pos = this.getNextFoldTo(row, column);
-
- if (!pos || pos.kind == "inside")
- return null;
-
- var fold = pos.fold;
- var folds = this.folds;
- var foldData = this.foldData;
-
- var i = folds.indexOf(fold);
- var foldBefore = folds[i - 1];
- this.end.row = foldBefore.end.row;
- this.end.column = foldBefore.end.column;
- folds = folds.splice(i, folds.length - i);
-
- var newFoldLine = new FoldLine(foldData, folds);
- foldData.splice(foldData.indexOf(this) + 1, 0, newFoldLine);
- return newFoldLine;
- };
-
- this.merge = function(foldLineNext) {
- var folds = foldLineNext.folds;
- for (var i = 0; i < folds.length; i++) {
- this.addFold(folds[i]);
- }
- var foldData = this.foldData;
- foldData.splice(foldData.indexOf(foldLineNext), 1);
- };
-
- this.toString = function() {
- var ret = [this.range.toString() + ": [" ];
-
- this.folds.forEach(function(fold) {
- ret.push(" " + fold.toString());
- });
- ret.push("]");
- return ret.join("\n");
- };
-
- this.idxToPosition = function(idx) {
- var lastFoldEndColumn = 0;
-
- for (var i = 0; i < this.folds.length; i++) {
- var fold = this.folds[i];
-
- idx -= fold.start.column - lastFoldEndColumn;
- if (idx < 0) {
- return {
- row: fold.start.row,
- column: fold.start.column + idx
- };
- }
-
- idx -= fold.placeholder.length;
- if (idx < 0) {
- return fold.start;
- }
-
- lastFoldEndColumn = fold.end.column;
- }
-
- return {
- row: this.end.row,
- column: this.end.column + idx
- };
- };
-}).call(FoldLine.prototype);
-
-exports.FoldLine = FoldLine;
-});
-
-ace.define("ace/range_list",["require","exports","module","ace/range"], function(require, exports, module) {
-"use strict";
-var Range = require("./range").Range;
-var comparePoints = Range.comparePoints;
-
-var RangeList = function() {
- this.ranges = [];
-};
-
-(function() {
- this.comparePoints = comparePoints;
-
- this.pointIndex = function(pos, excludeEdges, startIndex) {
- var list = this.ranges;
-
- for (var i = startIndex || 0; i < list.length; i++) {
- var range = list[i];
- var cmpEnd = comparePoints(pos, range.end);
- if (cmpEnd > 0)
- continue;
- var cmpStart = comparePoints(pos, range.start);
- if (cmpEnd === 0)
- return excludeEdges && cmpStart !== 0 ? -i-2 : i;
- if (cmpStart > 0 || (cmpStart === 0 && !excludeEdges))
- return i;
-
- return -i-1;
- }
- return -i - 1;
- };
-
- this.add = function(range) {
- var excludeEdges = !range.isEmpty();
- var startIndex = this.pointIndex(range.start, excludeEdges);
- if (startIndex < 0)
- startIndex = -startIndex - 1;
-
- var endIndex = this.pointIndex(range.end, excludeEdges, startIndex);
-
- if (endIndex < 0)
- endIndex = -endIndex - 1;
- else
- endIndex++;
- return this.ranges.splice(startIndex, endIndex - startIndex, range);
- };
-
- this.addList = function(list) {
- var removed = [];
- for (var i = list.length; i--; ) {
- removed.push.apply(removed, this.add(list[i]));
- }
- return removed;
- };
-
- this.substractPoint = function(pos) {
- var i = this.pointIndex(pos);
-
- if (i >= 0)
- return this.ranges.splice(i, 1);
- };
- this.merge = function() {
- var removed = [];
- var list = this.ranges;
-
- list = list.sort(function(a, b) {
- return comparePoints(a.start, b.start);
- });
-
- var next = list[0], range;
- for (var i = 1; i < list.length; i++) {
- range = next;
- next = list[i];
- var cmp = comparePoints(range.end, next.start);
- if (cmp < 0)
- continue;
-
- if (cmp == 0 && !range.isEmpty() && !next.isEmpty())
- continue;
-
- if (comparePoints(range.end, next.end) < 0) {
- range.end.row = next.end.row;
- range.end.column = next.end.column;
- }
-
- list.splice(i, 1);
- removed.push(next);
- next = range;
- i--;
- }
-
- this.ranges = list;
-
- return removed;
- };
-
- this.contains = function(row, column) {
- return this.pointIndex({row: row, column: column}) >= 0;
- };
-
- this.containsPoint = function(pos) {
- return this.pointIndex(pos) >= 0;
- };
-
- this.rangeAtPoint = function(pos) {
- var i = this.pointIndex(pos);
- if (i >= 0)
- return this.ranges[i];
- };
-
-
- this.clipRows = function(startRow, endRow) {
- var list = this.ranges;
- if (list[0].start.row > endRow || list[list.length - 1].start.row < startRow)
- return [];
-
- var startIndex = this.pointIndex({row: startRow, column: 0});
- if (startIndex < 0)
- startIndex = -startIndex - 1;
- var endIndex = this.pointIndex({row: endRow, column: 0}, startIndex);
- if (endIndex < 0)
- endIndex = -endIndex - 1;
-
- var clipped = [];
- for (var i = startIndex; i < endIndex; i++) {
- clipped.push(list[i]);
- }
- return clipped;
- };
-
- this.removeAll = function() {
- return this.ranges.splice(0, this.ranges.length);
- };
-
- this.attach = function(session) {
- if (this.session)
- this.detach();
-
- this.session = session;
- this.onChange = this.$onChange.bind(this);
-
- this.session.on('change', this.onChange);
- };
-
- this.detach = function() {
- if (!this.session)
- return;
- this.session.removeListener('change', this.onChange);
- this.session = null;
- };
-
- this.$onChange = function(delta) {
- if (delta.action == "insert"){
- var start = delta.start;
- var end = delta.end;
- } else {
- var end = delta.start;
- var start = delta.end;
- }
- var startRow = start.row;
- var endRow = end.row;
- var lineDif = endRow - startRow;
-
- var colDiff = -start.column + end.column;
- var ranges = this.ranges;
-
- for (var i = 0, n = ranges.length; i < n; i++) {
- var r = ranges[i];
- if (r.end.row < startRow)
- continue;
- if (r.start.row > startRow)
- break;
-
- if (r.start.row == startRow && r.start.column >= start.column ) {
- if (r.start.column == start.column && this.$insertRight) {
- } else {
- r.start.column += colDiff;
- r.start.row += lineDif;
- }
- }
- if (r.end.row == startRow && r.end.column >= start.column) {
- if (r.end.column == start.column && this.$insertRight) {
- continue;
- }
- if (r.end.column == start.column && colDiff > 0 && i < n - 1) {
- if (r.end.column > r.start.column && r.end.column == ranges[i+1].start.column)
- r.end.column -= colDiff;
- }
- r.end.column += colDiff;
- r.end.row += lineDif;
- }
- }
-
- if (lineDif != 0 && i < n) {
- for (; i < n; i++) {
- var r = ranges[i];
- r.start.row += lineDif;
- r.end.row += lineDif;
- }
- }
- };
-
-}).call(RangeList.prototype);
-
-exports.RangeList = RangeList;
-});
-
-ace.define("ace/edit_session/fold",["require","exports","module","ace/range","ace/range_list","ace/lib/oop"], function(require, exports, module) {
-"use strict";
-
-var Range = require("../range").Range;
-var RangeList = require("../range_list").RangeList;
-var oop = require("../lib/oop")
-var Fold = exports.Fold = function(range, placeholder) {
- this.foldLine = null;
- this.placeholder = placeholder;
- this.range = range;
- this.start = range.start;
- this.end = range.end;
-
- this.sameRow = range.start.row == range.end.row;
- this.subFolds = this.ranges = [];
-};
-
-oop.inherits(Fold, RangeList);
-
-(function() {
-
- this.toString = function() {
- return '"' + this.placeholder + '" ' + this.range.toString();
- };
-
- this.setFoldLine = function(foldLine) {
- this.foldLine = foldLine;
- this.subFolds.forEach(function(fold) {
- fold.setFoldLine(foldLine);
- });
- };
-
- this.clone = function() {
- var range = this.range.clone();
- var fold = new Fold(range, this.placeholder);
- this.subFolds.forEach(function(subFold) {
- fold.subFolds.push(subFold.clone());
- });
- fold.collapseChildren = this.collapseChildren;
- return fold;
- };
-
- this.addSubFold = function(fold) {
- if (this.range.isEqual(fold))
- return;
-
- if (!this.range.containsRange(fold))
- throw new Error("A fold can't intersect already existing fold" + fold.range + this.range);
- consumeRange(fold, this.start);
-
- var row = fold.start.row, column = fold.start.column;
- for (var i = 0, cmp = -1; i < this.subFolds.length; i++) {
- cmp = this.subFolds[i].range.compare(row, column);
- if (cmp != 1)
- break;
- }
- var afterStart = this.subFolds[i];
-
- if (cmp == 0)
- return afterStart.addSubFold(fold);
- var row = fold.range.end.row, column = fold.range.end.column;
- for (var j = i, cmp = -1; j < this.subFolds.length; j++) {
- cmp = this.subFolds[j].range.compare(row, column);
- if (cmp != 1)
- break;
- }
- var afterEnd = this.subFolds[j];
-
- if (cmp == 0)
- throw new Error("A fold can't intersect already existing fold" + fold.range + this.range);
-
- var consumedFolds = this.subFolds.splice(i, j - i, fold);
- fold.setFoldLine(this.foldLine);
-
- return fold;
- };
-
- this.restoreRange = function(range) {
- return restoreRange(range, this.start);
- };
-
-}).call(Fold.prototype);
-
-function consumePoint(point, anchor) {
- point.row -= anchor.row;
- if (point.row == 0)
- point.column -= anchor.column;
-}
-function consumeRange(range, anchor) {
- consumePoint(range.start, anchor);
- consumePoint(range.end, anchor);
-}
-function restorePoint(point, anchor) {
- if (point.row == 0)
- point.column += anchor.column;
- point.row += anchor.row;
-}
-function restoreRange(range, anchor) {
- restorePoint(range.start, anchor);
- restorePoint(range.end, anchor);
-}
-
-});
-
-ace.define("ace/edit_session/folding",["require","exports","module","ace/range","ace/edit_session/fold_line","ace/edit_session/fold","ace/token_iterator"], function(require, exports, module) {
-"use strict";
-
-var Range = require("../range").Range;
-var FoldLine = require("./fold_line").FoldLine;
-var Fold = require("./fold").Fold;
-var TokenIterator = require("../token_iterator").TokenIterator;
-
-function Folding() {
- this.getFoldAt = function(row, column, side) {
- var foldLine = this.getFoldLine(row);
- if (!foldLine)
- return null;
-
- var folds = foldLine.folds;
- for (var i = 0; i < folds.length; i++) {
- var fold = folds[i];
- if (fold.range.contains(row, column)) {
- if (side == 1 && fold.range.isEnd(row, column)) {
- continue;
- } else if (side == -1 && fold.range.isStart(row, column)) {
- continue;
- }
- return fold;
- }
- }
- };
- this.getFoldsInRange = function(range) {
- var start = range.start;
- var end = range.end;
- var foldLines = this.$foldData;
- var foundFolds = [];
-
- start.column += 1;
- end.column -= 1;
-
- for (var i = 0; i < foldLines.length; i++) {
- var cmp = foldLines[i].range.compareRange(range);
- if (cmp == 2) {
- continue;
- }
- else if (cmp == -2) {
- break;
- }
-
- var folds = foldLines[i].folds;
- for (var j = 0; j < folds.length; j++) {
- var fold = folds[j];
- cmp = fold.range.compareRange(range);
- if (cmp == -2) {
- break;
- } else if (cmp == 2) {
- continue;
- } else
- if (cmp == 42) {
- break;
- }
- foundFolds.push(fold);
- }
- }
- start.column -= 1;
- end.column += 1;
-
- return foundFolds;
- };
-
- this.getFoldsInRangeList = function(ranges) {
- if (Array.isArray(ranges)) {
- var folds = [];
- ranges.forEach(function(range) {
- folds = folds.concat(this.getFoldsInRange(range));
- }, this);
- } else {
- var folds = this.getFoldsInRange(ranges);
- }
- return folds;
- };
- this.getAllFolds = function() {
- var folds = [];
- var foldLines = this.$foldData;
-
- for (var i = 0; i < foldLines.length; i++)
- for (var j = 0; j < foldLines[i].folds.length; j++)
- folds.push(foldLines[i].folds[j]);
-
- return folds;
- };
- this.getFoldStringAt = function(row, column, trim, foldLine) {
- foldLine = foldLine || this.getFoldLine(row);
- if (!foldLine)
- return null;
-
- var lastFold = {
- end: { column: 0 }
- };
- var str, fold;
- for (var i = 0; i < foldLine.folds.length; i++) {
- fold = foldLine.folds[i];
- var cmp = fold.range.compareEnd(row, column);
- if (cmp == -1) {
- str = this
- .getLine(fold.start.row)
- .substring(lastFold.end.column, fold.start.column);
- break;
- }
- else if (cmp === 0) {
- return null;
- }
- lastFold = fold;
- }
- if (!str)
- str = this.getLine(fold.start.row).substring(lastFold.end.column);
-
- if (trim == -1)
- return str.substring(0, column - lastFold.end.column);
- else if (trim == 1)
- return str.substring(column - lastFold.end.column);
- else
- return str;
- };
-
- this.getFoldLine = function(docRow, startFoldLine) {
- var foldData = this.$foldData;
- var i = 0;
- if (startFoldLine)
- i = foldData.indexOf(startFoldLine);
- if (i == -1)
- i = 0;
- for (i; i < foldData.length; i++) {
- var foldLine = foldData[i];
- if (foldLine.start.row <= docRow && foldLine.end.row >= docRow) {
- return foldLine;
- } else if (foldLine.end.row > docRow) {
- return null;
- }
- }
- return null;
- };
- this.getNextFoldLine = function(docRow, startFoldLine) {
- var foldData = this.$foldData;
- var i = 0;
- if (startFoldLine)
- i = foldData.indexOf(startFoldLine);
- if (i == -1)
- i = 0;
- for (i; i < foldData.length; i++) {
- var foldLine = foldData[i];
- if (foldLine.end.row >= docRow) {
- return foldLine;
- }
- }
- return null;
- };
-
- this.getFoldedRowCount = function(first, last) {
- var foldData = this.$foldData, rowCount = last-first+1;
- for (var i = 0; i < foldData.length; i++) {
- var foldLine = foldData[i],
- end = foldLine.end.row,
- start = foldLine.start.row;
- if (end >= last) {
- if (start < last) {
- if (start >= first)
- rowCount -= last-start;
- else
- rowCount = 0; // in one fold
- }
- break;
- } else if (end >= first){
- if (start >= first) // fold inside range
- rowCount -= end-start;
- else
- rowCount -= end-first+1;
- }
- }
- return rowCount;
- };
-
- this.$addFoldLine = function(foldLine) {
- this.$foldData.push(foldLine);
- this.$foldData.sort(function(a, b) {
- return a.start.row - b.start.row;
- });
- return foldLine;
- };
- this.addFold = function(placeholder, range) {
- var foldData = this.$foldData;
- var added = false;
- var fold;
-
- if (placeholder instanceof Fold)
- fold = placeholder;
- else {
- fold = new Fold(range, placeholder);
- fold.collapseChildren = range.collapseChildren;
- }
- this.$clipRangeToDocument(fold.range);
-
- var startRow = fold.start.row;
- var startColumn = fold.start.column;
- var endRow = fold.end.row;
- var endColumn = fold.end.column;
- if (!(startRow < endRow ||
- startRow == endRow && startColumn <= endColumn - 2))
- throw new Error("The range has to be at least 2 characters width");
-
- var startFold = this.getFoldAt(startRow, startColumn, 1);
- var endFold = this.getFoldAt(endRow, endColumn, -1);
- if (startFold && endFold == startFold)
- return startFold.addSubFold(fold);
-
- if (startFold && !startFold.range.isStart(startRow, startColumn))
- this.removeFold(startFold);
-
- if (endFold && !endFold.range.isEnd(endRow, endColumn))
- this.removeFold(endFold);
- var folds = this.getFoldsInRange(fold.range);
- if (folds.length > 0) {
- this.removeFolds(folds);
- folds.forEach(function(subFold) {
- fold.addSubFold(subFold);
- });
- }
-
- for (var i = 0; i < foldData.length; i++) {
- var foldLine = foldData[i];
- if (endRow == foldLine.start.row) {
- foldLine.addFold(fold);
- added = true;
- break;
- } else if (startRow == foldLine.end.row) {
- foldLine.addFold(fold);
- added = true;
- if (!fold.sameRow) {
- var foldLineNext = foldData[i + 1];
- if (foldLineNext && foldLineNext.start.row == endRow) {
- foldLine.merge(foldLineNext);
- break;
- }
- }
- break;
- } else if (endRow <= foldLine.start.row) {
- break;
- }
- }
-
- if (!added)
- foldLine = this.$addFoldLine(new FoldLine(this.$foldData, fold));
-
- if (this.$useWrapMode)
- this.$updateWrapData(foldLine.start.row, foldLine.start.row);
- else
- this.$updateRowLengthCache(foldLine.start.row, foldLine.start.row);
- this.$modified = true;
- this._signal("changeFold", { data: fold, action: "add" });
-
- return fold;
- };
-
- this.addFolds = function(folds) {
- folds.forEach(function(fold) {
- this.addFold(fold);
- }, this);
- };
-
- this.removeFold = function(fold) {
- var foldLine = fold.foldLine;
- var startRow = foldLine.start.row;
- var endRow = foldLine.end.row;
-
- var foldLines = this.$foldData;
- var folds = foldLine.folds;
- if (folds.length == 1) {
- foldLines.splice(foldLines.indexOf(foldLine), 1);
- } else
- if (foldLine.range.isEnd(fold.end.row, fold.end.column)) {
- folds.pop();
- foldLine.end.row = folds[folds.length - 1].end.row;
- foldLine.end.column = folds[folds.length - 1].end.column;
- } else
- if (foldLine.range.isStart(fold.start.row, fold.start.column)) {
- folds.shift();
- foldLine.start.row = folds[0].start.row;
- foldLine.start.column = folds[0].start.column;
- } else
- if (fold.sameRow) {
- folds.splice(folds.indexOf(fold), 1);
- } else
- {
- var newFoldLine = foldLine.split(fold.start.row, fold.start.column);
- folds = newFoldLine.folds;
- folds.shift();
- newFoldLine.start.row = folds[0].start.row;
- newFoldLine.start.column = folds[0].start.column;
- }
-
- if (!this.$updating) {
- if (this.$useWrapMode)
- this.$updateWrapData(startRow, endRow);
- else
- this.$updateRowLengthCache(startRow, endRow);
- }
- this.$modified = true;
- this._signal("changeFold", { data: fold, action: "remove" });
- };
-
- this.removeFolds = function(folds) {
- var cloneFolds = [];
- for (var i = 0; i < folds.length; i++) {
- cloneFolds.push(folds[i]);
- }
-
- cloneFolds.forEach(function(fold) {
- this.removeFold(fold);
- }, this);
- this.$modified = true;
- };
-
- this.expandFold = function(fold) {
- this.removeFold(fold);
- fold.subFolds.forEach(function(subFold) {
- fold.restoreRange(subFold);
- this.addFold(subFold);
- }, this);
- if (fold.collapseChildren > 0) {
- this.foldAll(fold.start.row+1, fold.end.row, fold.collapseChildren-1);
- }
- fold.subFolds = [];
- };
-
- this.expandFolds = function(folds) {
- folds.forEach(function(fold) {
- this.expandFold(fold);
- }, this);
- };
-
- this.unfold = function(location, expandInner) {
- var range, folds;
- if (location == null) {
- range = new Range(0, 0, this.getLength(), 0);
- expandInner = true;
- } else if (typeof location == "number")
- range = new Range(location, 0, location, this.getLine(location).length);
- else if ("row" in location)
- range = Range.fromPoints(location, location);
- else
- range = location;
-
- folds = this.getFoldsInRangeList(range);
- if (expandInner) {
- this.removeFolds(folds);
- } else {
- var subFolds = folds;
- while (subFolds.length) {
- this.expandFolds(subFolds);
- subFolds = this.getFoldsInRangeList(range);
- }
- }
- if (folds.length)
- return folds;
- };
- this.isRowFolded = function(docRow, startFoldRow) {
- return !!this.getFoldLine(docRow, startFoldRow);
- };
-
- this.getRowFoldEnd = function(docRow, startFoldRow) {
- var foldLine = this.getFoldLine(docRow, startFoldRow);
- return foldLine ? foldLine.end.row : docRow;
- };
-
- this.getRowFoldStart = function(docRow, startFoldRow) {
- var foldLine = this.getFoldLine(docRow, startFoldRow);
- return foldLine ? foldLine.start.row : docRow;
- };
-
- this.getFoldDisplayLine = function(foldLine, endRow, endColumn, startRow, startColumn) {
- if (startRow == null)
- startRow = foldLine.start.row;
- if (startColumn == null)
- startColumn = 0;
- if (endRow == null)
- endRow = foldLine.end.row;
- if (endColumn == null)
- endColumn = this.getLine(endRow).length;
- var doc = this.doc;
- var textLine = "";
-
- foldLine.walk(function(placeholder, row, column, lastColumn) {
- if (row < startRow)
- return;
- if (row == startRow) {
- if (column < startColumn)
- return;
- lastColumn = Math.max(startColumn, lastColumn);
- }
-
- if (placeholder != null) {
- textLine += placeholder;
- } else {
- textLine += doc.getLine(row).substring(lastColumn, column);
- }
- }, endRow, endColumn);
- return textLine;
- };
-
- this.getDisplayLine = function(row, endColumn, startRow, startColumn) {
- var foldLine = this.getFoldLine(row);
-
- if (!foldLine) {
- var line;
- line = this.doc.getLine(row);
- return line.substring(startColumn || 0, endColumn || line.length);
- } else {
- return this.getFoldDisplayLine(
- foldLine, row, endColumn, startRow, startColumn);
- }
- };
-
- this.$cloneFoldData = function() {
- var fd = [];
- fd = this.$foldData.map(function(foldLine) {
- var folds = foldLine.folds.map(function(fold) {
- return fold.clone();
- });
- return new FoldLine(fd, folds);
- });
-
- return fd;
- };
-
- this.toggleFold = function(tryToUnfold) {
- var selection = this.selection;
- var range = selection.getRange();
- var fold;
- var bracketPos;
-
- if (range.isEmpty()) {
- var cursor = range.start;
- fold = this.getFoldAt(cursor.row, cursor.column);
-
- if (fold) {
- this.expandFold(fold);
- return;
- } else if (bracketPos = this.findMatchingBracket(cursor)) {
- if (range.comparePoint(bracketPos) == 1) {
- range.end = bracketPos;
- } else {
- range.start = bracketPos;
- range.start.column++;
- range.end.column--;
- }
- } else if (bracketPos = this.findMatchingBracket({row: cursor.row, column: cursor.column + 1})) {
- if (range.comparePoint(bracketPos) == 1)
- range.end = bracketPos;
- else
- range.start = bracketPos;
-
- range.start.column++;
- } else {
- range = this.getCommentFoldRange(cursor.row, cursor.column) || range;
- }
- } else {
- var folds = this.getFoldsInRange(range);
- if (tryToUnfold && folds.length) {
- this.expandFolds(folds);
- return;
- } else if (folds.length == 1 ) {
- fold = folds[0];
- }
- }
-
- if (!fold)
- fold = this.getFoldAt(range.start.row, range.start.column);
-
- if (fold && fold.range.toString() == range.toString()) {
- this.expandFold(fold);
- return;
- }
-
- var placeholder = "...";
- if (!range.isMultiLine()) {
- placeholder = this.getTextRange(range);
- if (placeholder.length < 4)
- return;
- placeholder = placeholder.trim().substring(0, 2) + "..";
- }
-
- this.addFold(placeholder, range);
- };
-
- this.getCommentFoldRange = function(row, column, dir) {
- var iterator = new TokenIterator(this, row, column);
- var token = iterator.getCurrentToken();
- if (token && /^comment|string/.test(token.type)) {
- var range = new Range();
- var re = new RegExp(token.type.replace(/\..*/, "\\."));
- if (dir != 1) {
- do {
- token = iterator.stepBackward();
- } while (token && re.test(token.type));
- iterator.stepForward();
- }
-
- range.start.row = iterator.getCurrentTokenRow();
- range.start.column = iterator.getCurrentTokenColumn() + 2;
-
- iterator = new TokenIterator(this, row, column);
-
- if (dir != -1) {
- do {
- token = iterator.stepForward();
- } while (token && re.test(token.type));
- token = iterator.stepBackward();
- } else
- token = iterator.getCurrentToken();
-
- range.end.row = iterator.getCurrentTokenRow();
- range.end.column = iterator.getCurrentTokenColumn() + token.value.length - 2;
- return range;
- }
- };
-
- this.foldAll = function(startRow, endRow, depth) {
- if (depth == undefined)
- depth = 100000; // JSON.stringify doesn't hanle Infinity
- var foldWidgets = this.foldWidgets;
- if (!foldWidgets)
- return; // mode doesn't support folding
- endRow = endRow || this.getLength();
- startRow = startRow || 0;
- for (var row = startRow; row < endRow; row++) {
- if (foldWidgets[row] == null)
- foldWidgets[row] = this.getFoldWidget(row);
- if (foldWidgets[row] != "start")
- continue;
-
- var range = this.getFoldWidgetRange(row);
- if (range && range.isMultiLine()
- && range.end.row <= endRow
- && range.start.row >= startRow
- ) {
- row = range.end.row;
- try {
- var fold = this.addFold("...", range);
- if (fold)
- fold.collapseChildren = depth;
- } catch(e) {}
- }
- }
- };
- this.$foldStyles = {
- "manual": 1,
- "markbegin": 1,
- "markbeginend": 1
- };
- this.$foldStyle = "markbegin";
- this.setFoldStyle = function(style) {
- if (!this.$foldStyles[style])
- throw new Error("invalid fold style: " + style + "[" + Object.keys(this.$foldStyles).join(", ") + "]");
-
- if (this.$foldStyle == style)
- return;
-
- this.$foldStyle = style;
-
- if (style == "manual")
- this.unfold();
- var mode = this.$foldMode;
- this.$setFolding(null);
- this.$setFolding(mode);
- };
-
- this.$setFolding = function(foldMode) {
- if (this.$foldMode == foldMode)
- return;
-
- this.$foldMode = foldMode;
-
- this.off('change', this.$updateFoldWidgets);
- this.off('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets);
- this._signal("changeAnnotation");
-
- if (!foldMode || this.$foldStyle == "manual") {
- this.foldWidgets = null;
- return;
- }
-
- this.foldWidgets = [];
- this.getFoldWidget = foldMode.getFoldWidget.bind(foldMode, this, this.$foldStyle);
- this.getFoldWidgetRange = foldMode.getFoldWidgetRange.bind(foldMode, this, this.$foldStyle);
-
- this.$updateFoldWidgets = this.updateFoldWidgets.bind(this);
- this.$tokenizerUpdateFoldWidgets = this.tokenizerUpdateFoldWidgets.bind(this);
- this.on('change', this.$updateFoldWidgets);
- this.on('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets);
- };
-
- this.getParentFoldRangeData = function (row, ignoreCurrent) {
- var fw = this.foldWidgets;
- if (!fw || (ignoreCurrent && fw[row]))
- return {};
-
- var i = row - 1, firstRange;
- while (i >= 0) {
- var c = fw[i];
- if (c == null)
- c = fw[i] = this.getFoldWidget(i);
-
- if (c == "start") {
- var range = this.getFoldWidgetRange(i);
- if (!firstRange)
- firstRange = range;
- if (range && range.end.row >= row)
- break;
- }
- i--;
- }
-
- return {
- range: i !== -1 && range,
- firstRange: firstRange
- };
- };
-
- this.onFoldWidgetClick = function(row, e) {
- e = e.domEvent;
- var options = {
- children: e.shiftKey,
- all: e.ctrlKey || e.metaKey,
- siblings: e.altKey
- };
-
- var range = this.$toggleFoldWidget(row, options);
- if (!range) {
- var el = (e.target || e.srcElement);
- if (el && /ace_fold-widget/.test(el.className))
- el.className += " ace_invalid";
- }
- };
-
- this.$toggleFoldWidget = function(row, options) {
- if (!this.getFoldWidget)
- return;
- var type = this.getFoldWidget(row);
- var line = this.getLine(row);
-
- var dir = type === "end" ? -1 : 1;
- var fold = this.getFoldAt(row, dir === -1 ? 0 : line.length, dir);
-
- if (fold) {
- if (options.children || options.all)
- this.removeFold(fold);
- else
- this.expandFold(fold);
- return;
- }
-
- var range = this.getFoldWidgetRange(row, true);
- if (range && !range.isMultiLine()) {
- fold = this.getFoldAt(range.start.row, range.start.column, 1);
- if (fold && range.isEqual(fold.range)) {
- this.removeFold(fold);
- return;
- }
- }
-
- if (options.siblings) {
- var data = this.getParentFoldRangeData(row);
- if (data.range) {
- var startRow = data.range.start.row + 1;
- var endRow = data.range.end.row;
- }
- this.foldAll(startRow, endRow, options.all ? 10000 : 0);
- } else if (options.children) {
- endRow = range ? range.end.row : this.getLength();
- this.foldAll(row + 1, endRow, options.all ? 10000 : 0);
- } else if (range) {
- if (options.all)
- range.collapseChildren = 10000;
- this.addFold("...", range);
- }
-
- return range;
- };
-
-
-
- this.toggleFoldWidget = function(toggleParent) {
- var row = this.selection.getCursor().row;
- row = this.getRowFoldStart(row);
- var range = this.$toggleFoldWidget(row, {});
-
- if (range)
- return;
- var data = this.getParentFoldRangeData(row, true);
- range = data.range || data.firstRange;
-
- if (range) {
- row = range.start.row;
- var fold = this.getFoldAt(row, this.getLine(row).length, 1);
-
- if (fold) {
- this.removeFold(fold);
- } else {
- this.addFold("...", range);
- }
- }
- };
-
- this.updateFoldWidgets = function(delta) {
- var firstRow = delta.start.row;
- var len = delta.end.row - firstRow;
-
- if (len === 0) {
- this.foldWidgets[firstRow] = null;
- } else if (delta.action == 'remove') {
- this.foldWidgets.splice(firstRow, len + 1, null);
- } else {
- var args = Array(len + 1);
- args.unshift(firstRow, 1);
- this.foldWidgets.splice.apply(this.foldWidgets, args);
- }
- };
- this.tokenizerUpdateFoldWidgets = function(e) {
- var rows = e.data;
- if (rows.first != rows.last) {
- if (this.foldWidgets.length > rows.first)
- this.foldWidgets.splice(rows.first, this.foldWidgets.length);
- }
- };
-}
-
-exports.Folding = Folding;
-
-});
-
-ace.define("ace/edit_session/bracket_match",["require","exports","module","ace/token_iterator","ace/range"], function(require, exports, module) {
-"use strict";
-
-var TokenIterator = require("../token_iterator").TokenIterator;
-var Range = require("../range").Range;
-
-
-function BracketMatch() {
-
- this.findMatchingBracket = function(position, chr) {
- if (position.column == 0) return null;
-
- var charBeforeCursor = chr || this.getLine(position.row).charAt(position.column-1);
- if (charBeforeCursor == "") return null;
-
- var match = charBeforeCursor.match(/([\(\[\{])|([\)\]\}])/);
- if (!match)
- return null;
-
- if (match[1])
- return this.$findClosingBracket(match[1], position);
- else
- return this.$findOpeningBracket(match[2], position);
- };
-
- this.getBracketRange = function(pos) {
- var line = this.getLine(pos.row);
- var before = true, range;
-
- var chr = line.charAt(pos.column-1);
- var match = chr && chr.match(/([\(\[\{])|([\)\]\}])/);
- if (!match) {
- chr = line.charAt(pos.column);
- pos = {row: pos.row, column: pos.column + 1};
- match = chr && chr.match(/([\(\[\{])|([\)\]\}])/);
- before = false;
- }
- if (!match)
- return null;
-
- if (match[1]) {
- var bracketPos = this.$findClosingBracket(match[1], pos);
- if (!bracketPos)
- return null;
- range = Range.fromPoints(pos, bracketPos);
- if (!before) {
- range.end.column++;
- range.start.column--;
- }
- range.cursor = range.end;
- } else {
- var bracketPos = this.$findOpeningBracket(match[2], pos);
- if (!bracketPos)
- return null;
- range = Range.fromPoints(bracketPos, pos);
- if (!before) {
- range.start.column++;
- range.end.column--;
- }
- range.cursor = range.start;
- }
-
- return range;
- };
-
- this.$brackets = {
- ")": "(",
- "(": ")",
- "]": "[",
- "[": "]",
- "{": "}",
- "}": "{"
- };
-
- this.$findOpeningBracket = function(bracket, position, typeRe) {
- var openBracket = this.$brackets[bracket];
- var depth = 1;
-
- var iterator = new TokenIterator(this, position.row, position.column);
- var token = iterator.getCurrentToken();
- if (!token)
- token = iterator.stepForward();
- if (!token)
- return;
-
- if (!typeRe){
- typeRe = new RegExp(
- "(\\.?" +
- token.type.replace(".", "\\.").replace("rparen", ".paren")
- .replace(/\b(?:end)\b/, "(?:start|begin|end)")
- + ")+"
- );
- }
- var valueIndex = position.column - iterator.getCurrentTokenColumn() - 2;
- var value = token.value;
-
- while (true) {
-
- while (valueIndex >= 0) {
- var chr = value.charAt(valueIndex);
- if (chr == openBracket) {
- depth -= 1;
- if (depth == 0) {
- return {row: iterator.getCurrentTokenRow(),
- column: valueIndex + iterator.getCurrentTokenColumn()};
- }
- }
- else if (chr == bracket) {
- depth += 1;
- }
- valueIndex -= 1;
- }
- do {
- token = iterator.stepBackward();
- } while (token && !typeRe.test(token.type));
-
- if (token == null)
- break;
-
- value = token.value;
- valueIndex = value.length - 1;
- }
-
- return null;
- };
-
- this.$findClosingBracket = function(bracket, position, typeRe) {
- var closingBracket = this.$brackets[bracket];
- var depth = 1;
-
- var iterator = new TokenIterator(this, position.row, position.column);
- var token = iterator.getCurrentToken();
- if (!token)
- token = iterator.stepForward();
- if (!token)
- return;
-
- if (!typeRe){
- typeRe = new RegExp(
- "(\\.?" +
- token.type.replace(".", "\\.").replace("lparen", ".paren")
- .replace(/\b(?:start|begin)\b/, "(?:start|begin|end)")
- + ")+"
- );
- }
- var valueIndex = position.column - iterator.getCurrentTokenColumn();
-
- while (true) {
-
- var value = token.value;
- var valueLength = value.length;
- while (valueIndex < valueLength) {
- var chr = value.charAt(valueIndex);
- if (chr == closingBracket) {
- depth -= 1;
- if (depth == 0) {
- return {row: iterator.getCurrentTokenRow(),
- column: valueIndex + iterator.getCurrentTokenColumn()};
- }
- }
- else if (chr == bracket) {
- depth += 1;
- }
- valueIndex += 1;
- }
- do {
- token = iterator.stepForward();
- } while (token && !typeRe.test(token.type));
-
- if (token == null)
- break;
-
- valueIndex = 0;
- }
-
- return null;
- };
-}
-exports.BracketMatch = BracketMatch;
-
-});
-
-ace.define("ace/edit_session",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/config","ace/lib/event_emitter","ace/selection","ace/mode/text","ace/range","ace/document","ace/background_tokenizer","ace/search_highlight","ace/edit_session/folding","ace/edit_session/bracket_match"], function(require, exports, module) {
-"use strict";
-
-var oop = require("./lib/oop");
-var lang = require("./lib/lang");
-var config = require("./config");
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-var Selection = require("./selection").Selection;
-var TextMode = require("./mode/text").Mode;
-var Range = require("./range").Range;
-var Document = require("./document").Document;
-var BackgroundTokenizer = require("./background_tokenizer").BackgroundTokenizer;
-var SearchHighlight = require("./search_highlight").SearchHighlight;
-
-var EditSession = function(text, mode) {
- this.$breakpoints = [];
- this.$decorations = [];
- this.$frontMarkers = {};
- this.$backMarkers = {};
- this.$markerId = 1;
- this.$undoSelect = true;
-
- this.$foldData = [];
- this.$foldData.toString = function() {
- return this.join("\n");
- };
- this.on("changeFold", this.onChangeFold.bind(this));
- this.$onChange = this.onChange.bind(this);
-
- if (typeof text != "object" || !text.getLine)
- text = new Document(text);
-
- this.setDocument(text);
- this.selection = new Selection(this);
-
- config.resetOptions(this);
- this.setMode(mode);
- config._signal("session", this);
-};
-
-
-(function() {
-
- oop.implement(this, EventEmitter);
- this.setDocument = function(doc) {
- if (this.doc)
- this.doc.removeListener("change", this.$onChange);
-
- this.doc = doc;
- doc.on("change", this.$onChange);
-
- if (this.bgTokenizer)
- this.bgTokenizer.setDocument(this.getDocument());
-
- this.resetCaches();
- };
- this.getDocument = function() {
- return this.doc;
- };
- this.$resetRowCache = function(docRow) {
- if (!docRow) {
- this.$docRowCache = [];
- this.$screenRowCache = [];
- return;
- }
- var l = this.$docRowCache.length;
- var i = this.$getRowCacheIndex(this.$docRowCache, docRow) + 1;
- if (l > i) {
- this.$docRowCache.splice(i, l);
- this.$screenRowCache.splice(i, l);
- }
- };
-
- this.$getRowCacheIndex = function(cacheArray, val) {
- var low = 0;
- var hi = cacheArray.length - 1;
-
- while (low <= hi) {
- var mid = (low + hi) >> 1;
- var c = cacheArray[mid];
-
- if (val > c)
- low = mid + 1;
- else if (val < c)
- hi = mid - 1;
- else
- return mid;
- }
-
- return low -1;
- };
-
- this.resetCaches = function() {
- this.$modified = true;
- this.$wrapData = [];
- this.$rowLengthCache = [];
- this.$resetRowCache(0);
- if (this.bgTokenizer)
- this.bgTokenizer.start(0);
- };
-
- this.onChangeFold = function(e) {
- var fold = e.data;
- this.$resetRowCache(fold.start.row);
- };
-
- this.onChange = function(delta) {
- this.$modified = true;
-
- this.$resetRowCache(delta.start.row);
-
- var removedFolds = this.$updateInternalDataOnChange(delta);
- if (!this.$fromUndo && this.$undoManager && !delta.ignore) {
- this.$deltasDoc.push(delta);
- if (removedFolds && removedFolds.length != 0) {
- this.$deltasFold.push({
- action: "removeFolds",
- folds: removedFolds
- });
- }
-
- this.$informUndoManager.schedule();
- }
-
- this.bgTokenizer && this.bgTokenizer.$updateOnChange(delta);
- this._signal("change", delta);
- };
- this.setValue = function(text) {
- this.doc.setValue(text);
- this.selection.moveTo(0, 0);
-
- this.$resetRowCache(0);
- this.$deltas = [];
- this.$deltasDoc = [];
- this.$deltasFold = [];
- this.setUndoManager(this.$undoManager);
- this.getUndoManager().reset();
- };
- this.getValue =
- this.toString = function() {
- return this.doc.getValue();
- };
- this.getSelection = function() {
- return this.selection;
- };
- this.getState = function(row) {
- return this.bgTokenizer.getState(row);
- };
- this.getTokens = function(row) {
- return this.bgTokenizer.getTokens(row);
- };
- this.getTokenAt = function(row, column) {
- var tokens = this.bgTokenizer.getTokens(row);
- var token, c = 0;
- if (column == null) {
- i = tokens.length - 1;
- c = this.getLine(row).length;
- } else {
- for (var i = 0; i < tokens.length; i++) {
- c += tokens[i].value.length;
- if (c >= column)
- break;
- }
- }
- token = tokens[i];
- if (!token)
- return null;
- token.index = i;
- token.start = c - token.value.length;
- return token;
- };
- this.setUndoManager = function(undoManager) {
- this.$undoManager = undoManager;
- this.$deltas = [];
- this.$deltasDoc = [];
- this.$deltasFold = [];
-
- if (this.$informUndoManager)
- this.$informUndoManager.cancel();
-
- if (undoManager) {
- var self = this;
-
- this.$syncInformUndoManager = function() {
- self.$informUndoManager.cancel();
-
- if (self.$deltasFold.length) {
- self.$deltas.push({
- group: "fold",
- deltas: self.$deltasFold
- });
- self.$deltasFold = [];
- }
-
- if (self.$deltasDoc.length) {
- self.$deltas.push({
- group: "doc",
- deltas: self.$deltasDoc
- });
- self.$deltasDoc = [];
- }
-
- if (self.$deltas.length > 0) {
- undoManager.execute({
- action: "aceupdate",
- args: [self.$deltas, self],
- merge: self.mergeUndoDeltas
- });
- }
- self.mergeUndoDeltas = false;
- self.$deltas = [];
- };
- this.$informUndoManager = lang.delayedCall(this.$syncInformUndoManager);
- }
- };
- this.markUndoGroup = function() {
- if (this.$syncInformUndoManager)
- this.$syncInformUndoManager();
- };
-
- this.$defaultUndoManager = {
- undo: function() {},
- redo: function() {},
- reset: function() {}
- };
- this.getUndoManager = function() {
- return this.$undoManager || this.$defaultUndoManager;
- };
- this.getTabString = function() {
- if (this.getUseSoftTabs()) {
- return lang.stringRepeat(" ", this.getTabSize());
- } else {
- return "\t";
- }
- };
- this.setUseSoftTabs = function(val) {
- this.setOption("useSoftTabs", val);
- };
- this.getUseSoftTabs = function() {
- return this.$useSoftTabs && !this.$mode.$indentWithTabs;
- };
- this.setTabSize = function(tabSize) {
- this.setOption("tabSize", tabSize);
- };
- this.getTabSize = function() {
- return this.$tabSize;
- };
- this.isTabStop = function(position) {
- return this.$useSoftTabs && (position.column % this.$tabSize === 0);
- };
-
- this.$overwrite = false;
- this.setOverwrite = function(overwrite) {
- this.setOption("overwrite", overwrite);
- };
- this.getOverwrite = function() {
- return this.$overwrite;
- };
- this.toggleOverwrite = function() {
- this.setOverwrite(!this.$overwrite);
- };
- this.addGutterDecoration = function(row, className) {
- if (!this.$decorations[row])
- this.$decorations[row] = "";
- this.$decorations[row] += " " + className;
- this._signal("changeBreakpoint", {});
- };
- this.removeGutterDecoration = function(row, className) {
- this.$decorations[row] = (this.$decorations[row] || "").replace(" " + className, "");
- this._signal("changeBreakpoint", {});
- };
- this.getBreakpoints = function() {
- return this.$breakpoints;
- };
- this.setBreakpoints = function(rows) {
- this.$breakpoints = [];
- for (var i=0; i 0)
- inToken = !!line.charAt(column - 1).match(this.tokenRe);
-
- if (!inToken)
- inToken = !!line.charAt(column).match(this.tokenRe);
-
- if (inToken)
- var re = this.tokenRe;
- else if (/^\s+$/.test(line.slice(column-1, column+1)))
- var re = /\s/;
- else
- var re = this.nonTokenRe;
-
- var start = column;
- if (start > 0) {
- do {
- start--;
- }
- while (start >= 0 && line.charAt(start).match(re));
- start++;
- }
-
- var end = column;
- while (end < line.length && line.charAt(end).match(re)) {
- end++;
- }
-
- return new Range(row, start, row, end);
- };
- this.getAWordRange = function(row, column) {
- var wordRange = this.getWordRange(row, column);
- var line = this.getLine(wordRange.end.row);
-
- while (line.charAt(wordRange.end.column).match(/[ \t]/)) {
- wordRange.end.column += 1;
- }
- return wordRange;
- };
- this.setNewLineMode = function(newLineMode) {
- this.doc.setNewLineMode(newLineMode);
- };
- this.getNewLineMode = function() {
- return this.doc.getNewLineMode();
- };
- this.setUseWorker = function(useWorker) { this.setOption("useWorker", useWorker); };
- this.getUseWorker = function() { return this.$useWorker; };
- this.onReloadTokenizer = function(e) {
- var rows = e.data;
- this.bgTokenizer.start(rows.first);
- this._signal("tokenizerUpdate", e);
- };
-
- this.$modes = {};
- this.$mode = null;
- this.$modeId = null;
- this.setMode = function(mode, cb) {
- if (mode && typeof mode === "object") {
- if (mode.getTokenizer)
- return this.$onChangeMode(mode);
- var options = mode;
- var path = options.path;
- } else {
- path = mode || "ace/mode/text";
- }
- if (!this.$modes["ace/mode/text"])
- this.$modes["ace/mode/text"] = new TextMode();
-
- if (this.$modes[path] && !options) {
- this.$onChangeMode(this.$modes[path]);
- cb && cb();
- return;
- }
- this.$modeId = path;
- config.loadModule(["mode", path], function(m) {
- if (this.$modeId !== path)
- return cb && cb();
- if (this.$modes[path] && !options) {
- this.$onChangeMode(this.$modes[path]);
- } else if (m && m.Mode) {
- m = new m.Mode(options);
- if (!options) {
- this.$modes[path] = m;
- m.$id = path;
- }
- this.$onChangeMode(m);
- }
- cb && cb();
- }.bind(this));
- if (!this.$mode)
- this.$onChangeMode(this.$modes["ace/mode/text"], true);
- };
-
- this.$onChangeMode = function(mode, $isPlaceholder) {
- if (!$isPlaceholder)
- this.$modeId = mode.$id;
- if (this.$mode === mode)
- return;
-
- this.$mode = mode;
-
- this.$stopWorker();
-
- if (this.$useWorker)
- this.$startWorker();
-
- var tokenizer = mode.getTokenizer();
-
- if(tokenizer.addEventListener !== undefined) {
- var onReloadTokenizer = this.onReloadTokenizer.bind(this);
- tokenizer.addEventListener("update", onReloadTokenizer);
- }
-
- if (!this.bgTokenizer) {
- this.bgTokenizer = new BackgroundTokenizer(tokenizer);
- var _self = this;
- this.bgTokenizer.addEventListener("update", function(e) {
- _self._signal("tokenizerUpdate", e);
- });
- } else {
- this.bgTokenizer.setTokenizer(tokenizer);
- }
-
- this.bgTokenizer.setDocument(this.getDocument());
-
- this.tokenRe = mode.tokenRe;
- this.nonTokenRe = mode.nonTokenRe;
-
-
- if (!$isPlaceholder) {
- if (mode.attachToSession)
- mode.attachToSession(this);
- this.$options.wrapMethod.set.call(this, this.$wrapMethod);
- this.$setFolding(mode.foldingRules);
- this.bgTokenizer.start(0);
- this._emit("changeMode");
- }
- };
-
- this.$stopWorker = function() {
- if (this.$worker) {
- this.$worker.terminate();
- this.$worker = null;
- }
- };
-
- this.$startWorker = function() {
- try {
- this.$worker = this.$mode.createWorker(this);
- } catch (e) {
- config.warn("Could not load worker", e);
- this.$worker = null;
- }
- };
- this.getMode = function() {
- return this.$mode;
- };
-
- this.$scrollTop = 0;
- this.setScrollTop = function(scrollTop) {
- if (this.$scrollTop === scrollTop || isNaN(scrollTop))
- return;
-
- this.$scrollTop = scrollTop;
- this._signal("changeScrollTop", scrollTop);
- };
- this.getScrollTop = function() {
- return this.$scrollTop;
- };
-
- this.$scrollLeft = 0;
- this.setScrollLeft = function(scrollLeft) {
- if (this.$scrollLeft === scrollLeft || isNaN(scrollLeft))
- return;
-
- this.$scrollLeft = scrollLeft;
- this._signal("changeScrollLeft", scrollLeft);
- };
- this.getScrollLeft = function() {
- return this.$scrollLeft;
- };
- this.getScreenWidth = function() {
- this.$computeWidth();
- if (this.lineWidgets)
- return Math.max(this.getLineWidgetMaxWidth(), this.screenWidth);
- return this.screenWidth;
- };
-
- this.getLineWidgetMaxWidth = function() {
- if (this.lineWidgetsWidth != null) return this.lineWidgetsWidth;
- var width = 0;
- this.lineWidgets.forEach(function(w) {
- if (w && w.screenWidth > width)
- width = w.screenWidth;
- });
- return this.lineWidgetWidth = width;
- };
-
- this.$computeWidth = function(force) {
- if (this.$modified || force) {
- this.$modified = false;
-
- if (this.$useWrapMode)
- return this.screenWidth = this.$wrapLimit;
-
- var lines = this.doc.getAllLines();
- var cache = this.$rowLengthCache;
- var longestScreenLine = 0;
- var foldIndex = 0;
- var foldLine = this.$foldData[foldIndex];
- var foldStart = foldLine ? foldLine.start.row : Infinity;
- var len = lines.length;
-
- for (var i = 0; i < len; i++) {
- if (i > foldStart) {
- i = foldLine.end.row + 1;
- if (i >= len)
- break;
- foldLine = this.$foldData[foldIndex++];
- foldStart = foldLine ? foldLine.start.row : Infinity;
- }
-
- if (cache[i] == null)
- cache[i] = this.$getStringScreenWidth(lines[i])[0];
-
- if (cache[i] > longestScreenLine)
- longestScreenLine = cache[i];
- }
- this.screenWidth = longestScreenLine;
- }
- };
- this.getLine = function(row) {
- return this.doc.getLine(row);
- };
- this.getLines = function(firstRow, lastRow) {
- return this.doc.getLines(firstRow, lastRow);
- };
- this.getLength = function() {
- return this.doc.getLength();
- };
- this.getTextRange = function(range) {
- return this.doc.getTextRange(range || this.selection.getRange());
- };
- this.insert = function(position, text) {
- return this.doc.insert(position, text);
- };
- this.remove = function(range) {
- return this.doc.remove(range);
- };
- this.removeFullLines = function(firstRow, lastRow){
- return this.doc.removeFullLines(firstRow, lastRow);
- };
- this.undoChanges = function(deltas, dontSelect) {
- if (!deltas.length)
- return;
-
- this.$fromUndo = true;
- var lastUndoRange = null;
- for (var i = deltas.length - 1; i != -1; i--) {
- var delta = deltas[i];
- if (delta.group == "doc") {
- this.doc.revertDeltas(delta.deltas);
- lastUndoRange =
- this.$getUndoSelection(delta.deltas, true, lastUndoRange);
- } else {
- delta.deltas.forEach(function(foldDelta) {
- this.addFolds(foldDelta.folds);
- }, this);
- }
- }
- this.$fromUndo = false;
- lastUndoRange &&
- this.$undoSelect &&
- !dontSelect &&
- this.selection.setSelectionRange(lastUndoRange);
- return lastUndoRange;
- };
- this.redoChanges = function(deltas, dontSelect) {
- if (!deltas.length)
- return;
-
- this.$fromUndo = true;
- var lastUndoRange = null;
- for (var i = 0; i < deltas.length; i++) {
- var delta = deltas[i];
- if (delta.group == "doc") {
- this.doc.applyDeltas(delta.deltas);
- lastUndoRange =
- this.$getUndoSelection(delta.deltas, false, lastUndoRange);
- }
- }
- this.$fromUndo = false;
- lastUndoRange &&
- this.$undoSelect &&
- !dontSelect &&
- this.selection.setSelectionRange(lastUndoRange);
- return lastUndoRange;
- };
- this.setUndoSelect = function(enable) {
- this.$undoSelect = enable;
- };
-
- this.$getUndoSelection = function(deltas, isUndo, lastUndoRange) {
- function isInsert(delta) {
- return isUndo ? delta.action !== "insert" : delta.action === "insert";
- }
-
- var delta = deltas[0];
- var range, point;
- var lastDeltaIsInsert = false;
- if (isInsert(delta)) {
- range = Range.fromPoints(delta.start, delta.end);
- lastDeltaIsInsert = true;
- } else {
- range = Range.fromPoints(delta.start, delta.start);
- lastDeltaIsInsert = false;
- }
-
- for (var i = 1; i < deltas.length; i++) {
- delta = deltas[i];
- if (isInsert(delta)) {
- point = delta.start;
- if (range.compare(point.row, point.column) == -1) {
- range.setStart(point);
- }
- point = delta.end;
- if (range.compare(point.row, point.column) == 1) {
- range.setEnd(point);
- }
- lastDeltaIsInsert = true;
- } else {
- point = delta.start;
- if (range.compare(point.row, point.column) == -1) {
- range = Range.fromPoints(delta.start, delta.start);
- }
- lastDeltaIsInsert = false;
- }
- }
- if (lastUndoRange != null) {
- if (Range.comparePoints(lastUndoRange.start, range.start) === 0) {
- lastUndoRange.start.column += range.end.column - range.start.column;
- lastUndoRange.end.column += range.end.column - range.start.column;
- }
-
- var cmp = lastUndoRange.compareRange(range);
- if (cmp == 1) {
- range.setStart(lastUndoRange.start);
- } else if (cmp == -1) {
- range.setEnd(lastUndoRange.end);
- }
- }
-
- return range;
- };
- this.replace = function(range, text) {
- return this.doc.replace(range, text);
- };
- this.moveText = function(fromRange, toPosition, copy) {
- var text = this.getTextRange(fromRange);
- var folds = this.getFoldsInRange(fromRange);
-
- var toRange = Range.fromPoints(toPosition, toPosition);
- if (!copy) {
- this.remove(fromRange);
- var rowDiff = fromRange.start.row - fromRange.end.row;
- var collDiff = rowDiff ? -fromRange.end.column : fromRange.start.column - fromRange.end.column;
- if (collDiff) {
- if (toRange.start.row == fromRange.end.row && toRange.start.column > fromRange.end.column)
- toRange.start.column += collDiff;
- if (toRange.end.row == fromRange.end.row && toRange.end.column > fromRange.end.column)
- toRange.end.column += collDiff;
- }
- if (rowDiff && toRange.start.row >= fromRange.end.row) {
- toRange.start.row += rowDiff;
- toRange.end.row += rowDiff;
- }
- }
-
- toRange.end = this.insert(toRange.start, text);
- if (folds.length) {
- var oldStart = fromRange.start;
- var newStart = toRange.start;
- var rowDiff = newStart.row - oldStart.row;
- var collDiff = newStart.column - oldStart.column;
- this.addFolds(folds.map(function(x) {
- x = x.clone();
- if (x.start.row == oldStart.row)
- x.start.column += collDiff;
- if (x.end.row == oldStart.row)
- x.end.column += collDiff;
- x.start.row += rowDiff;
- x.end.row += rowDiff;
- return x;
- }));
- }
-
- return toRange;
- };
- this.indentRows = function(startRow, endRow, indentString) {
- indentString = indentString.replace(/\t/g, this.getTabString());
- for (var row=startRow; row<=endRow; row++)
- this.doc.insertInLine({row: row, column: 0}, indentString);
- };
- this.outdentRows = function (range) {
- var rowRange = range.collapseRows();
- var deleteRange = new Range(0, 0, 0, 0);
- var size = this.getTabSize();
-
- for (var i = rowRange.start.row; i <= rowRange.end.row; ++i) {
- var line = this.getLine(i);
-
- deleteRange.start.row = i;
- deleteRange.end.row = i;
- for (var j = 0; j < size; ++j)
- if (line.charAt(j) != ' ')
- break;
- if (j < size && line.charAt(j) == '\t') {
- deleteRange.start.column = j;
- deleteRange.end.column = j + 1;
- } else {
- deleteRange.start.column = 0;
- deleteRange.end.column = j;
- }
- this.remove(deleteRange);
- }
- };
-
- this.$moveLines = function(firstRow, lastRow, dir) {
- firstRow = this.getRowFoldStart(firstRow);
- lastRow = this.getRowFoldEnd(lastRow);
- if (dir < 0) {
- var row = this.getRowFoldStart(firstRow + dir);
- if (row < 0) return 0;
- var diff = row-firstRow;
- } else if (dir > 0) {
- var row = this.getRowFoldEnd(lastRow + dir);
- if (row > this.doc.getLength()-1) return 0;
- var diff = row-lastRow;
- } else {
- firstRow = this.$clipRowToDocument(firstRow);
- lastRow = this.$clipRowToDocument(lastRow);
- var diff = lastRow - firstRow + 1;
- }
-
- var range = new Range(firstRow, 0, lastRow, Number.MAX_VALUE);
- var folds = this.getFoldsInRange(range).map(function(x){
- x = x.clone();
- x.start.row += diff;
- x.end.row += diff;
- return x;
- });
-
- var lines = dir == 0
- ? this.doc.getLines(firstRow, lastRow)
- : this.doc.removeFullLines(firstRow, lastRow);
- this.doc.insertFullLines(firstRow+diff, lines);
- folds.length && this.addFolds(folds);
- return diff;
- };
- this.moveLinesUp = function(firstRow, lastRow) {
- return this.$moveLines(firstRow, lastRow, -1);
- };
- this.moveLinesDown = function(firstRow, lastRow) {
- return this.$moveLines(firstRow, lastRow, 1);
- };
- this.duplicateLines = function(firstRow, lastRow) {
- return this.$moveLines(firstRow, lastRow, 0);
- };
-
-
- this.$clipRowToDocument = function(row) {
- return Math.max(0, Math.min(row, this.doc.getLength()-1));
- };
-
- this.$clipColumnToRow = function(row, column) {
- if (column < 0)
- return 0;
- return Math.min(this.doc.getLine(row).length, column);
- };
-
-
- this.$clipPositionToDocument = function(row, column) {
- column = Math.max(0, column);
-
- if (row < 0) {
- row = 0;
- column = 0;
- } else {
- var len = this.doc.getLength();
- if (row >= len) {
- row = len - 1;
- column = this.doc.getLine(len-1).length;
- } else {
- column = Math.min(this.doc.getLine(row).length, column);
- }
- }
-
- return {
- row: row,
- column: column
- };
- };
-
- this.$clipRangeToDocument = function(range) {
- if (range.start.row < 0) {
- range.start.row = 0;
- range.start.column = 0;
- } else {
- range.start.column = this.$clipColumnToRow(
- range.start.row,
- range.start.column
- );
- }
-
- var len = this.doc.getLength() - 1;
- if (range.end.row > len) {
- range.end.row = len;
- range.end.column = this.doc.getLine(len).length;
- } else {
- range.end.column = this.$clipColumnToRow(
- range.end.row,
- range.end.column
- );
- }
- return range;
- };
- this.$wrapLimit = 80;
- this.$useWrapMode = false;
- this.$wrapLimitRange = {
- min : null,
- max : null
- };
- this.setUseWrapMode = function(useWrapMode) {
- if (useWrapMode != this.$useWrapMode) {
- this.$useWrapMode = useWrapMode;
- this.$modified = true;
- this.$resetRowCache(0);
- if (useWrapMode) {
- var len = this.getLength();
- this.$wrapData = Array(len);
- this.$updateWrapData(0, len - 1);
- }
-
- this._signal("changeWrapMode");
- }
- };
- this.getUseWrapMode = function() {
- return this.$useWrapMode;
- };
- this.setWrapLimitRange = function(min, max) {
- if (this.$wrapLimitRange.min !== min || this.$wrapLimitRange.max !== max) {
- this.$wrapLimitRange = { min: min, max: max };
- this.$modified = true;
- if (this.$useWrapMode)
- this._signal("changeWrapMode");
- }
- };
- this.adjustWrapLimit = function(desiredLimit, $printMargin) {
- var limits = this.$wrapLimitRange;
- if (limits.max < 0)
- limits = {min: $printMargin, max: $printMargin};
- var wrapLimit = this.$constrainWrapLimit(desiredLimit, limits.min, limits.max);
- if (wrapLimit != this.$wrapLimit && wrapLimit > 1) {
- this.$wrapLimit = wrapLimit;
- this.$modified = true;
- if (this.$useWrapMode) {
- this.$updateWrapData(0, this.getLength() - 1);
- this.$resetRowCache(0);
- this._signal("changeWrapLimit");
- }
- return true;
- }
- return false;
- };
-
- this.$constrainWrapLimit = function(wrapLimit, min, max) {
- if (min)
- wrapLimit = Math.max(min, wrapLimit);
-
- if (max)
- wrapLimit = Math.min(max, wrapLimit);
-
- return wrapLimit;
- };
- this.getWrapLimit = function() {
- return this.$wrapLimit;
- };
- this.setWrapLimit = function (limit) {
- this.setWrapLimitRange(limit, limit);
- };
- this.getWrapLimitRange = function() {
- return {
- min : this.$wrapLimitRange.min,
- max : this.$wrapLimitRange.max
- };
- };
-
- this.$updateInternalDataOnChange = function(delta) {
- var useWrapMode = this.$useWrapMode;
- var action = delta.action;
- var start = delta.start;
- var end = delta.end;
- var firstRow = start.row;
- var lastRow = end.row;
- var len = lastRow - firstRow;
- var removedFolds = null;
-
- this.$updating = true;
- if (len != 0) {
- if (action === "remove") {
- this[useWrapMode ? "$wrapData" : "$rowLengthCache"].splice(firstRow, len);
-
- var foldLines = this.$foldData;
- removedFolds = this.getFoldsInRange(delta);
- this.removeFolds(removedFolds);
-
- var foldLine = this.getFoldLine(end.row);
- var idx = 0;
- if (foldLine) {
- foldLine.addRemoveChars(end.row, end.column, start.column - end.column);
- foldLine.shiftRow(-len);
-
- var foldLineBefore = this.getFoldLine(firstRow);
- if (foldLineBefore && foldLineBefore !== foldLine) {
- foldLineBefore.merge(foldLine);
- foldLine = foldLineBefore;
- }
- idx = foldLines.indexOf(foldLine) + 1;
- }
-
- for (idx; idx < foldLines.length; idx++) {
- var foldLine = foldLines[idx];
- if (foldLine.start.row >= end.row) {
- foldLine.shiftRow(-len);
- }
- }
-
- lastRow = firstRow;
- } else {
- var args = Array(len);
- args.unshift(firstRow, 0);
- var arr = useWrapMode ? this.$wrapData : this.$rowLengthCache
- arr.splice.apply(arr, args);
- var foldLines = this.$foldData;
- var foldLine = this.getFoldLine(firstRow);
- var idx = 0;
- if (foldLine) {
- var cmp = foldLine.range.compareInside(start.row, start.column);
- if (cmp == 0) {
- foldLine = foldLine.split(start.row, start.column);
- if (foldLine) {
- foldLine.shiftRow(len);
- foldLine.addRemoveChars(lastRow, 0, end.column - start.column);
- }
- } else
- if (cmp == -1) {
- foldLine.addRemoveChars(firstRow, 0, end.column - start.column);
- foldLine.shiftRow(len);
- }
- idx = foldLines.indexOf(foldLine) + 1;
- }
-
- for (idx; idx < foldLines.length; idx++) {
- var foldLine = foldLines[idx];
- if (foldLine.start.row >= firstRow) {
- foldLine.shiftRow(len);
- }
- }
- }
- } else {
- len = Math.abs(delta.start.column - delta.end.column);
- if (action === "remove") {
- removedFolds = this.getFoldsInRange(delta);
- this.removeFolds(removedFolds);
-
- len = -len;
- }
- var foldLine = this.getFoldLine(firstRow);
- if (foldLine) {
- foldLine.addRemoveChars(firstRow, start.column, len);
- }
- }
-
- if (useWrapMode && this.$wrapData.length != this.doc.getLength()) {
- console.error("doc.getLength() and $wrapData.length have to be the same!");
- }
- this.$updating = false;
-
- if (useWrapMode)
- this.$updateWrapData(firstRow, lastRow);
- else
- this.$updateRowLengthCache(firstRow, lastRow);
-
- return removedFolds;
- };
-
- this.$updateRowLengthCache = function(firstRow, lastRow, b) {
- this.$rowLengthCache[firstRow] = null;
- this.$rowLengthCache[lastRow] = null;
- };
-
- this.$updateWrapData = function(firstRow, lastRow) {
- var lines = this.doc.getAllLines();
- var tabSize = this.getTabSize();
- var wrapData = this.$wrapData;
- var wrapLimit = this.$wrapLimit;
- var tokens;
- var foldLine;
-
- var row = firstRow;
- lastRow = Math.min(lastRow, lines.length - 1);
- while (row <= lastRow) {
- foldLine = this.getFoldLine(row, foldLine);
- if (!foldLine) {
- tokens = this.$getDisplayTokens(lines[row]);
- wrapData[row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize);
- row ++;
- } else {
- tokens = [];
- foldLine.walk(function(placeholder, row, column, lastColumn) {
- var walkTokens;
- if (placeholder != null) {
- walkTokens = this.$getDisplayTokens(
- placeholder, tokens.length);
- walkTokens[0] = PLACEHOLDER_START;
- for (var i = 1; i < walkTokens.length; i++) {
- walkTokens[i] = PLACEHOLDER_BODY;
- }
- } else {
- walkTokens = this.$getDisplayTokens(
- lines[row].substring(lastColumn, column),
- tokens.length);
- }
- tokens = tokens.concat(walkTokens);
- }.bind(this),
- foldLine.end.row,
- lines[foldLine.end.row].length + 1
- );
-
- wrapData[foldLine.start.row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize);
- row = foldLine.end.row + 1;
- }
- }
- };
- var CHAR = 1,
- CHAR_EXT = 2,
- PLACEHOLDER_START = 3,
- PLACEHOLDER_BODY = 4,
- PUNCTUATION = 9,
- SPACE = 10,
- TAB = 11,
- TAB_SPACE = 12;
-
-
- this.$computeWrapSplits = function(tokens, wrapLimit, tabSize) {
- if (tokens.length == 0) {
- return [];
- }
-
- var splits = [];
- var displayLength = tokens.length;
- var lastSplit = 0, lastDocSplit = 0;
-
- var isCode = this.$wrapAsCode;
-
- var indentedSoftWrap = this.$indentedSoftWrap;
- var maxIndent = wrapLimit <= Math.max(2 * tabSize, 8)
- || indentedSoftWrap === false ? 0 : Math.floor(wrapLimit / 2);
-
- function getWrapIndent() {
- var indentation = 0;
- if (maxIndent === 0)
- return indentation;
- if (indentedSoftWrap) {
- for (var i = 0; i < tokens.length; i++) {
- var token = tokens[i];
- if (token == SPACE)
- indentation += 1;
- else if (token == TAB)
- indentation += tabSize;
- else if (token == TAB_SPACE)
- continue;
- else
- break;
- }
- }
- if (isCode && indentedSoftWrap !== false)
- indentation += tabSize;
- return Math.min(indentation, maxIndent);
- }
- function addSplit(screenPos) {
- var displayed = tokens.slice(lastSplit, screenPos);
- var len = displayed.length;
- displayed.join("")
- .replace(/12/g, function() {
- len -= 1;
- })
- .replace(/2/g, function() {
- len -= 1;
- });
-
- if (!splits.length) {
- indent = getWrapIndent();
- splits.indent = indent;
- }
- lastDocSplit += len;
- splits.push(lastDocSplit);
- lastSplit = screenPos;
- }
- var indent = 0;
- while (displayLength - lastSplit > wrapLimit - indent) {
- var split = lastSplit + wrapLimit - indent;
- if (tokens[split - 1] >= SPACE && tokens[split] >= SPACE) {
- addSplit(split);
- continue;
- }
- if (tokens[split] == PLACEHOLDER_START || tokens[split] == PLACEHOLDER_BODY) {
- for (split; split != lastSplit - 1; split--) {
- if (tokens[split] == PLACEHOLDER_START) {
- break;
- }
- }
- if (split > lastSplit) {
- addSplit(split);
- continue;
- }
- split = lastSplit + wrapLimit;
- for (split; split < tokens.length; split++) {
- if (tokens[split] != PLACEHOLDER_BODY) {
- break;
- }
- }
- if (split == tokens.length) {
- break; // Breaks the while-loop.
- }
- addSplit(split);
- continue;
- }
- var minSplit = Math.max(split - (wrapLimit -(wrapLimit>>2)), lastSplit - 1);
- while (split > minSplit && tokens[split] < PLACEHOLDER_START) {
- split --;
- }
- if (isCode) {
- while (split > minSplit && tokens[split] < PLACEHOLDER_START) {
- split --;
- }
- while (split > minSplit && tokens[split] == PUNCTUATION) {
- split --;
- }
- } else {
- while (split > minSplit && tokens[split] < SPACE) {
- split --;
- }
- }
- if (split > minSplit) {
- addSplit(++split);
- continue;
- }
- split = lastSplit + wrapLimit;
- if (tokens[split] == CHAR_EXT)
- split--;
- addSplit(split - indent);
- }
- return splits;
- };
- this.$getDisplayTokens = function(str, offset) {
- var arr = [];
- var tabSize;
- offset = offset || 0;
-
- for (var i = 0; i < str.length; i++) {
- var c = str.charCodeAt(i);
- if (c == 9) {
- tabSize = this.getScreenTabSize(arr.length + offset);
- arr.push(TAB);
- for (var n = 1; n < tabSize; n++) {
- arr.push(TAB_SPACE);
- }
- }
- else if (c == 32) {
- arr.push(SPACE);
- } else if((c > 39 && c < 48) || (c > 57 && c < 64)) {
- arr.push(PUNCTUATION);
- }
- else if (c >= 0x1100 && isFullWidth(c)) {
- arr.push(CHAR, CHAR_EXT);
- } else {
- arr.push(CHAR);
- }
- }
- return arr;
- };
- this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) {
- if (maxScreenColumn == 0)
- return [0, 0];
- if (maxScreenColumn == null)
- maxScreenColumn = Infinity;
- screenColumn = screenColumn || 0;
-
- var c, column;
- for (column = 0; column < str.length; column++) {
- c = str.charCodeAt(column);
- if (c == 9) {
- screenColumn += this.getScreenTabSize(screenColumn);
- }
- else if (c >= 0x1100 && isFullWidth(c)) {
- screenColumn += 2;
- } else {
- screenColumn += 1;
- }
- if (screenColumn > maxScreenColumn) {
- break;
- }
- }
-
- return [screenColumn, column];
- };
-
- this.lineWidgets = null;
- this.getRowLength = function(row) {
- if (this.lineWidgets)
- var h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0;
- else
- h = 0
- if (!this.$useWrapMode || !this.$wrapData[row]) {
- return 1 + h;
- } else {
- return this.$wrapData[row].length + 1 + h;
- }
- };
- this.getRowLineCount = function(row) {
- if (!this.$useWrapMode || !this.$wrapData[row]) {
- return 1;
- } else {
- return this.$wrapData[row].length + 1;
- }
- };
-
- this.getRowWrapIndent = function(screenRow) {
- if (this.$useWrapMode) {
- var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE);
- var splits = this.$wrapData[pos.row];
- return splits.length && splits[0] < pos.column ? splits.indent : 0;
- } else {
- return 0;
- }
- }
- this.getScreenLastRowColumn = function(screenRow) {
- var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE);
- return this.documentToScreenColumn(pos.row, pos.column);
- };
- this.getDocumentLastRowColumn = function(docRow, docColumn) {
- var screenRow = this.documentToScreenRow(docRow, docColumn);
- return this.getScreenLastRowColumn(screenRow);
- };
- this.getDocumentLastRowColumnPosition = function(docRow, docColumn) {
- var screenRow = this.documentToScreenRow(docRow, docColumn);
- return this.screenToDocumentPosition(screenRow, Number.MAX_VALUE / 10);
- };
- this.getRowSplitData = function(row) {
- if (!this.$useWrapMode) {
- return undefined;
- } else {
- return this.$wrapData[row];
- }
- };
- this.getScreenTabSize = function(screenColumn) {
- return this.$tabSize - screenColumn % this.$tabSize;
- };
-
-
- this.screenToDocumentRow = function(screenRow, screenColumn) {
- return this.screenToDocumentPosition(screenRow, screenColumn).row;
- };
-
-
- this.screenToDocumentColumn = function(screenRow, screenColumn) {
- return this.screenToDocumentPosition(screenRow, screenColumn).column;
- };
- this.screenToDocumentPosition = function(screenRow, screenColumn) {
- if (screenRow < 0)
- return {row: 0, column: 0};
-
- var line;
- var docRow = 0;
- var docColumn = 0;
- var column;
- var row = 0;
- var rowLength = 0;
-
- var rowCache = this.$screenRowCache;
- var i = this.$getRowCacheIndex(rowCache, screenRow);
- var l = rowCache.length;
- if (l && i >= 0) {
- var row = rowCache[i];
- var docRow = this.$docRowCache[i];
- var doCache = screenRow > rowCache[l - 1];
- } else {
- var doCache = !l;
- }
-
- var maxRow = this.getLength() - 1;
- var foldLine = this.getNextFoldLine(docRow);
- var foldStart = foldLine ? foldLine.start.row : Infinity;
-
- while (row <= screenRow) {
- rowLength = this.getRowLength(docRow);
- if (row + rowLength > screenRow || docRow >= maxRow) {
- break;
- } else {
- row += rowLength;
- docRow++;
- if (docRow > foldStart) {
- docRow = foldLine.end.row+1;
- foldLine = this.getNextFoldLine(docRow, foldLine);
- foldStart = foldLine ? foldLine.start.row : Infinity;
- }
- }
-
- if (doCache) {
- this.$docRowCache.push(docRow);
- this.$screenRowCache.push(row);
- }
- }
-
- if (foldLine && foldLine.start.row <= docRow) {
- line = this.getFoldDisplayLine(foldLine);
- docRow = foldLine.start.row;
- } else if (row + rowLength <= screenRow || docRow > maxRow) {
- return {
- row: maxRow,
- column: this.getLine(maxRow).length
- };
- } else {
- line = this.getLine(docRow);
- foldLine = null;
- }
- var wrapIndent = 0;
- if (this.$useWrapMode) {
- var splits = this.$wrapData[docRow];
- if (splits) {
- var splitIndex = Math.floor(screenRow - row);
- column = splits[splitIndex];
- if(splitIndex > 0 && splits.length) {
- wrapIndent = splits.indent;
- docColumn = splits[splitIndex - 1] || splits[splits.length - 1];
- line = line.substring(docColumn);
- }
- }
- }
-
- docColumn += this.$getStringScreenWidth(line, screenColumn - wrapIndent)[1];
- if (this.$useWrapMode && docColumn >= column)
- docColumn = column - 1;
-
- if (foldLine)
- return foldLine.idxToPosition(docColumn);
-
- return {row: docRow, column: docColumn};
- };
- this.documentToScreenPosition = function(docRow, docColumn) {
- if (typeof docColumn === "undefined")
- var pos = this.$clipPositionToDocument(docRow.row, docRow.column);
- else
- pos = this.$clipPositionToDocument(docRow, docColumn);
-
- docRow = pos.row;
- docColumn = pos.column;
-
- var screenRow = 0;
- var foldStartRow = null;
- var fold = null;
- fold = this.getFoldAt(docRow, docColumn, 1);
- if (fold) {
- docRow = fold.start.row;
- docColumn = fold.start.column;
- }
-
- var rowEnd, row = 0;
-
-
- var rowCache = this.$docRowCache;
- var i = this.$getRowCacheIndex(rowCache, docRow);
- var l = rowCache.length;
- if (l && i >= 0) {
- var row = rowCache[i];
- var screenRow = this.$screenRowCache[i];
- var doCache = docRow > rowCache[l - 1];
- } else {
- var doCache = !l;
- }
-
- var foldLine = this.getNextFoldLine(row);
- var foldStart = foldLine ?foldLine.start.row :Infinity;
-
- while (row < docRow) {
- if (row >= foldStart) {
- rowEnd = foldLine.end.row + 1;
- if (rowEnd > docRow)
- break;
- foldLine = this.getNextFoldLine(rowEnd, foldLine);
- foldStart = foldLine ?foldLine.start.row :Infinity;
- }
- else {
- rowEnd = row + 1;
- }
-
- screenRow += this.getRowLength(row);
- row = rowEnd;
-
- if (doCache) {
- this.$docRowCache.push(row);
- this.$screenRowCache.push(screenRow);
- }
- }
- var textLine = "";
- if (foldLine && row >= foldStart) {
- textLine = this.getFoldDisplayLine(foldLine, docRow, docColumn);
- foldStartRow = foldLine.start.row;
- } else {
- textLine = this.getLine(docRow).substring(0, docColumn);
- foldStartRow = docRow;
- }
- var wrapIndent = 0;
- if (this.$useWrapMode) {
- var wrapRow = this.$wrapData[foldStartRow];
- if (wrapRow) {
- var screenRowOffset = 0;
- while (textLine.length >= wrapRow[screenRowOffset]) {
- screenRow ++;
- screenRowOffset++;
- }
- textLine = textLine.substring(
- wrapRow[screenRowOffset - 1] || 0, textLine.length
- );
- wrapIndent = screenRowOffset > 0 ? wrapRow.indent : 0;
- }
- }
-
- return {
- row: screenRow,
- column: wrapIndent + this.$getStringScreenWidth(textLine)[0]
- };
- };
- this.documentToScreenColumn = function(row, docColumn) {
- return this.documentToScreenPosition(row, docColumn).column;
- };
- this.documentToScreenRow = function(docRow, docColumn) {
- return this.documentToScreenPosition(docRow, docColumn).row;
- };
- this.getScreenLength = function() {
- var screenRows = 0;
- var fold = null;
- if (!this.$useWrapMode) {
- screenRows = this.getLength();
- var foldData = this.$foldData;
- for (var i = 0; i < foldData.length; i++) {
- fold = foldData[i];
- screenRows -= fold.end.row - fold.start.row;
- }
- } else {
- var lastRow = this.$wrapData.length;
- var row = 0, i = 0;
- var fold = this.$foldData[i++];
- var foldStart = fold ? fold.start.row :Infinity;
-
- while (row < lastRow) {
- var splits = this.$wrapData[row];
- screenRows += splits ? splits.length + 1 : 1;
- row ++;
- if (row > foldStart) {
- row = fold.end.row+1;
- fold = this.$foldData[i++];
- foldStart = fold ?fold.start.row :Infinity;
- }
- }
- }
- if (this.lineWidgets)
- screenRows += this.$getWidgetScreenLength();
-
- return screenRows;
- };
- this.$setFontMetrics = function(fm) {
- if (!this.$enableVarChar) return;
- this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) {
- if (maxScreenColumn === 0)
- return [0, 0];
- if (!maxScreenColumn)
- maxScreenColumn = Infinity;
- screenColumn = screenColumn || 0;
-
- var c, column;
- for (column = 0; column < str.length; column++) {
- c = str.charAt(column);
- if (c === "\t") {
- screenColumn += this.getScreenTabSize(screenColumn);
- } else {
- screenColumn += fm.getCharacterWidth(c);
- }
- if (screenColumn > maxScreenColumn) {
- break;
- }
- }
-
- return [screenColumn, column];
- };
- };
-
- this.destroy = function() {
- if (this.bgTokenizer) {
- this.bgTokenizer.setDocument(null);
- this.bgTokenizer = null;
- }
- this.$stopWorker();
- };
- function isFullWidth(c) {
- if (c < 0x1100)
- return false;
- return c >= 0x1100 && c <= 0x115F ||
- c >= 0x11A3 && c <= 0x11A7 ||
- c >= 0x11FA && c <= 0x11FF ||
- c >= 0x2329 && c <= 0x232A ||
- c >= 0x2E80 && c <= 0x2E99 ||
- c >= 0x2E9B && c <= 0x2EF3 ||
- c >= 0x2F00 && c <= 0x2FD5 ||
- c >= 0x2FF0 && c <= 0x2FFB ||
- c >= 0x3000 && c <= 0x303E ||
- c >= 0x3041 && c <= 0x3096 ||
- c >= 0x3099 && c <= 0x30FF ||
- c >= 0x3105 && c <= 0x312D ||
- c >= 0x3131 && c <= 0x318E ||
- c >= 0x3190 && c <= 0x31BA ||
- c >= 0x31C0 && c <= 0x31E3 ||
- c >= 0x31F0 && c <= 0x321E ||
- c >= 0x3220 && c <= 0x3247 ||
- c >= 0x3250 && c <= 0x32FE ||
- c >= 0x3300 && c <= 0x4DBF ||
- c >= 0x4E00 && c <= 0xA48C ||
- c >= 0xA490 && c <= 0xA4C6 ||
- c >= 0xA960 && c <= 0xA97C ||
- c >= 0xAC00 && c <= 0xD7A3 ||
- c >= 0xD7B0 && c <= 0xD7C6 ||
- c >= 0xD7CB && c <= 0xD7FB ||
- c >= 0xF900 && c <= 0xFAFF ||
- c >= 0xFE10 && c <= 0xFE19 ||
- c >= 0xFE30 && c <= 0xFE52 ||
- c >= 0xFE54 && c <= 0xFE66 ||
- c >= 0xFE68 && c <= 0xFE6B ||
- c >= 0xFF01 && c <= 0xFF60 ||
- c >= 0xFFE0 && c <= 0xFFE6;
- }
-
-}).call(EditSession.prototype);
-
-require("./edit_session/folding").Folding.call(EditSession.prototype);
-require("./edit_session/bracket_match").BracketMatch.call(EditSession.prototype);
-
-
-config.defineOptions(EditSession.prototype, "session", {
- wrap: {
- set: function(value) {
- if (!value || value == "off")
- value = false;
- else if (value == "free")
- value = true;
- else if (value == "printMargin")
- value = -1;
- else if (typeof value == "string")
- value = parseInt(value, 10) || false;
-
- if (this.$wrap == value)
- return;
- this.$wrap = value;
- if (!value) {
- this.setUseWrapMode(false);
- } else {
- var col = typeof value == "number" ? value : null;
- this.setWrapLimitRange(col, col);
- this.setUseWrapMode(true);
- }
- },
- get: function() {
- if (this.getUseWrapMode()) {
- if (this.$wrap == -1)
- return "printMargin";
- if (!this.getWrapLimitRange().min)
- return "free";
- return this.$wrap;
- }
- return "off";
- },
- handlesSet: true
- },
- wrapMethod: {
- set: function(val) {
- val = val == "auto"
- ? this.$mode.type != "text"
- : val != "text";
- if (val != this.$wrapAsCode) {
- this.$wrapAsCode = val;
- if (this.$useWrapMode) {
- this.$modified = true;
- this.$resetRowCache(0);
- this.$updateWrapData(0, this.getLength() - 1);
- }
- }
- },
- initialValue: "auto"
- },
- indentedSoftWrap: { initialValue: true },
- firstLineNumber: {
- set: function() {this._signal("changeBreakpoint");},
- initialValue: 1
- },
- useWorker: {
- set: function(useWorker) {
- this.$useWorker = useWorker;
-
- this.$stopWorker();
- if (useWorker)
- this.$startWorker();
- },
- initialValue: true
- },
- useSoftTabs: {initialValue: true},
- tabSize: {
- set: function(tabSize) {
- if (isNaN(tabSize) || this.$tabSize === tabSize) return;
-
- this.$modified = true;
- this.$rowLengthCache = [];
- this.$tabSize = tabSize;
- this._signal("changeTabSize");
- },
- initialValue: 4,
- handlesSet: true
- },
- overwrite: {
- set: function(val) {this._signal("changeOverwrite");},
- initialValue: false
- },
- newLineMode: {
- set: function(val) {this.doc.setNewLineMode(val)},
- get: function() {return this.doc.getNewLineMode()},
- handlesSet: true
- },
- mode: {
- set: function(val) { this.setMode(val) },
- get: function() { return this.$modeId }
- }
-});
-
-exports.EditSession = EditSession;
-});
-
-ace.define("ace/search",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(require, exports, module) {
-"use strict";
-
-var lang = require("./lib/lang");
-var oop = require("./lib/oop");
-var Range = require("./range").Range;
-
-var Search = function() {
- this.$options = {};
-};
-
-(function() {
- this.set = function(options) {
- oop.mixin(this.$options, options);
- return this;
- };
- this.getOptions = function() {
- return lang.copyObject(this.$options);
- };
- this.setOptions = function(options) {
- this.$options = options;
- };
- this.find = function(session) {
- var options = this.$options;
- var iterator = this.$matchIterator(session, options);
- if (!iterator)
- return false;
-
- var firstRange = null;
- iterator.forEach(function(range, row, offset) {
- if (!range.start) {
- var column = range.offset + (offset || 0);
- firstRange = new Range(row, column, row, column + range.length);
- if (!range.length && options.start && options.start.start
- && options.skipCurrent != false && firstRange.isEqual(options.start)
- ) {
- firstRange = null;
- return false;
- }
- } else
- firstRange = range;
- return true;
- });
-
- return firstRange;
- };
- this.findAll = function(session) {
- var options = this.$options;
- if (!options.needle)
- return [];
- this.$assembleRegExp(options);
-
- var range = options.range;
- var lines = range
- ? session.getLines(range.start.row, range.end.row)
- : session.doc.getAllLines();
-
- var ranges = [];
- var re = options.re;
- if (options.$isMultiLine) {
- var len = re.length;
- var maxRow = lines.length - len;
- var prevRange;
- outer: for (var row = re.offset || 0; row <= maxRow; row++) {
- for (var j = 0; j < len; j++)
- if (lines[row + j].search(re[j]) == -1)
- continue outer;
-
- var startLine = lines[row];
- var line = lines[row + len - 1];
- var startIndex = startLine.length - startLine.match(re[0])[0].length;
- var endIndex = line.match(re[len - 1])[0].length;
-
- if (prevRange && prevRange.end.row === row &&
- prevRange.end.column > startIndex
- ) {
- continue;
- }
- ranges.push(prevRange = new Range(
- row, startIndex, row + len - 1, endIndex
- ));
- if (len > 2)
- row = row + len - 2;
- }
- } else {
- for (var i = 0; i < lines.length; i++) {
- var matches = lang.getMatchOffsets(lines[i], re);
- for (var j = 0; j < matches.length; j++) {
- var match = matches[j];
- ranges.push(new Range(i, match.offset, i, match.offset + match.length));
- }
- }
- }
-
- if (range) {
- var startColumn = range.start.column;
- var endColumn = range.start.column;
- var i = 0, j = ranges.length - 1;
- while (i < j && ranges[i].start.column < startColumn && ranges[i].start.row == range.start.row)
- i++;
-
- while (i < j && ranges[j].end.column > endColumn && ranges[j].end.row == range.end.row)
- j--;
-
- ranges = ranges.slice(i, j + 1);
- for (i = 0, j = ranges.length; i < j; i++) {
- ranges[i].start.row += range.start.row;
- ranges[i].end.row += range.start.row;
- }
- }
-
- return ranges;
- };
- this.replace = function(input, replacement) {
- var options = this.$options;
-
- var re = this.$assembleRegExp(options);
- if (options.$isMultiLine)
- return replacement;
-
- if (!re)
- return;
-
- var match = re.exec(input);
- if (!match || match[0].length != input.length)
- return null;
-
- replacement = input.replace(re, replacement);
- if (options.preserveCase) {
- replacement = replacement.split("");
- for (var i = Math.min(input.length, input.length); i--; ) {
- var ch = input[i];
- if (ch && ch.toLowerCase() != ch)
- replacement[i] = replacement[i].toUpperCase();
- else
- replacement[i] = replacement[i].toLowerCase();
- }
- replacement = replacement.join("");
- }
-
- return replacement;
- };
-
- this.$matchIterator = function(session, options) {
- var re = this.$assembleRegExp(options);
- if (!re)
- return false;
-
- var callback;
- if (options.$isMultiLine) {
- var len = re.length;
- var matchIterator = function(line, row, offset) {
- var startIndex = line.search(re[0]);
- if (startIndex == -1)
- return;
- for (var i = 1; i < len; i++) {
- line = session.getLine(row + i);
- if (line.search(re[i]) == -1)
- return;
- }
-
- var endIndex = line.match(re[len - 1])[0].length;
-
- var range = new Range(row, startIndex, row + len - 1, endIndex);
- if (re.offset == 1) {
- range.start.row--;
- range.start.column = Number.MAX_VALUE;
- } else if (offset)
- range.start.column += offset;
-
- if (callback(range))
- return true;
- };
- } else if (options.backwards) {
- var matchIterator = function(line, row, startIndex) {
- var matches = lang.getMatchOffsets(line, re);
- for (var i = matches.length-1; i >= 0; i--)
- if (callback(matches[i], row, startIndex))
- return true;
- };
- } else {
- var matchIterator = function(line, row, startIndex) {
- var matches = lang.getMatchOffsets(line, re);
- for (var i = 0; i < matches.length; i++)
- if (callback(matches[i], row, startIndex))
- return true;
- };
- }
-
- var lineIterator = this.$lineIterator(session, options);
-
- return {
- forEach: function(_callback) {
- callback = _callback;
- lineIterator.forEach(matchIterator);
- }
- };
- };
-
- this.$assembleRegExp = function(options, $disableFakeMultiline) {
- if (options.needle instanceof RegExp)
- return options.re = options.needle;
-
- var needle = options.needle;
-
- if (!options.needle)
- return options.re = false;
-
- if (!options.regExp)
- needle = lang.escapeRegExp(needle);
-
- if (options.wholeWord)
- needle = "\\b" + needle + "\\b";
-
- var modifier = options.caseSensitive ? "gm" : "gmi";
-
- options.$isMultiLine = !$disableFakeMultiline && /[\n\r]/.test(needle);
- if (options.$isMultiLine)
- return options.re = this.$assembleMultilineRegExp(needle, modifier);
-
- try {
- var re = new RegExp(needle, modifier);
- } catch(e) {
- re = false;
- }
- return options.re = re;
- };
-
- this.$assembleMultilineRegExp = function(needle, modifier) {
- var parts = needle.replace(/\r\n|\r|\n/g, "$\n^").split("\n");
- var re = [];
- for (var i = 0; i < parts.length; i++) try {
- re.push(new RegExp(parts[i], modifier));
- } catch(e) {
- return false;
- }
- if (parts[0] == "") {
- re.shift();
- re.offset = 1;
- } else {
- re.offset = 0;
- }
- return re;
- };
-
- this.$lineIterator = function(session, options) {
- var backwards = options.backwards == true;
- var skipCurrent = options.skipCurrent != false;
-
- var range = options.range;
- var start = options.start;
- if (!start)
- start = range ? range[backwards ? "end" : "start"] : session.selection.getRange();
-
- if (start.start)
- start = start[skipCurrent != backwards ? "end" : "start"];
-
- var firstRow = range ? range.start.row : 0;
- var lastRow = range ? range.end.row : session.getLength() - 1;
-
- var forEach = backwards ? function(callback) {
- var row = start.row;
-
- var line = session.getLine(row).substring(0, start.column);
- if (callback(line, row))
- return;
-
- for (row--; row >= firstRow; row--)
- if (callback(session.getLine(row), row))
- return;
-
- if (options.wrap == false)
- return;
-
- for (row = lastRow, firstRow = start.row; row >= firstRow; row--)
- if (callback(session.getLine(row), row))
- return;
- } : function(callback) {
- var row = start.row;
-
- var line = session.getLine(row).substr(start.column);
- if (callback(line, row, start.column))
- return;
-
- for (row = row+1; row <= lastRow; row++)
- if (callback(session.getLine(row), row))
- return;
-
- if (options.wrap == false)
- return;
-
- for (row = firstRow, lastRow = start.row; row <= lastRow; row++)
- if (callback(session.getLine(row), row))
- return;
- };
-
- return {forEach: forEach};
- };
-
-}).call(Search.prototype);
-
-exports.Search = Search;
-});
-
-ace.define("ace/keyboard/hash_handler",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(require, exports, module) {
-"use strict";
-
-var keyUtil = require("../lib/keys");
-var useragent = require("../lib/useragent");
-var KEY_MODS = keyUtil.KEY_MODS;
-
-function HashHandler(config, platform) {
- this.platform = platform || (useragent.isMac ? "mac" : "win");
- this.commands = {};
- this.commandKeyBinding = {};
- this.addCommands(config);
- this.$singleCommand = true;
-}
-
-function MultiHashHandler(config, platform) {
- HashHandler.call(this, config, platform);
- this.$singleCommand = false;
-}
-
-MultiHashHandler.prototype = HashHandler.prototype;
-
-(function() {
-
-
- this.addCommand = function(command) {
- if (this.commands[command.name])
- this.removeCommand(command);
-
- this.commands[command.name] = command;
-
- if (command.bindKey)
- this._buildKeyHash(command);
- };
-
- this.removeCommand = function(command, keepCommand) {
- var name = command && (typeof command === 'string' ? command : command.name);
- command = this.commands[name];
- if (!keepCommand)
- delete this.commands[name];
- var ckb = this.commandKeyBinding;
- for (var keyId in ckb) {
- var cmdGroup = ckb[keyId];
- if (cmdGroup == command) {
- delete ckb[keyId];
- } else if (Array.isArray(cmdGroup)) {
- var i = cmdGroup.indexOf(command);
- if (i != -1) {
- cmdGroup.splice(i, 1);
- if (cmdGroup.length == 1)
- ckb[keyId] = cmdGroup[0];
- }
- }
- }
- };
-
- this.bindKey = function(key, command, position) {
- if (typeof key == "object" && key) {
- if (position == undefined)
- position = key.position;
- key = key[this.platform];
- }
- if (!key)
- return;
- if (typeof command == "function")
- return this.addCommand({exec: command, bindKey: key, name: command.name || key});
-
- key.split("|").forEach(function(keyPart) {
- var chain = "";
- if (keyPart.indexOf(" ") != -1) {
- var parts = keyPart.split(/\s+/);
- keyPart = parts.pop();
- parts.forEach(function(keyPart) {
- var binding = this.parseKeys(keyPart);
- var id = KEY_MODS[binding.hashId] + binding.key;
- chain += (chain ? " " : "") + id;
- this._addCommandToBinding(chain, "chainKeys");
- }, this);
- chain += " ";
- }
- var binding = this.parseKeys(keyPart);
- var id = KEY_MODS[binding.hashId] + binding.key;
- this._addCommandToBinding(chain + id, command, position);
- }, this);
- };
-
- function getPosition(command) {
- return typeof command == "object" && command.bindKey
- && command.bindKey.position || 0;
- }
- this._addCommandToBinding = function(keyId, command, position) {
- var ckb = this.commandKeyBinding, i;
- if (!command) {
- delete ckb[keyId];
- } else if (!ckb[keyId] || this.$singleCommand) {
- ckb[keyId] = command;
- } else {
- if (!Array.isArray(ckb[keyId])) {
- ckb[keyId] = [ckb[keyId]];
- } else if ((i = ckb[keyId].indexOf(command)) != -1) {
- ckb[keyId].splice(i, 1);
- }
-
- if (typeof position != "number") {
- if (position || command.isDefault)
- position = -100;
- else
- position = getPosition(command);
- }
- var commands = ckb[keyId];
- for (i = 0; i < commands.length; i++) {
- var other = commands[i];
- var otherPos = getPosition(other);
- if (otherPos > position)
- break;
- }
- commands.splice(i, 0, command);
- }
- };
-
- this.addCommands = function(commands) {
- commands && Object.keys(commands).forEach(function(name) {
- var command = commands[name];
- if (!command)
- return;
-
- if (typeof command === "string")
- return this.bindKey(command, name);
-
- if (typeof command === "function")
- command = { exec: command };
-
- if (typeof command !== "object")
- return;
-
- if (!command.name)
- command.name = name;
-
- this.addCommand(command);
- }, this);
- };
-
- this.removeCommands = function(commands) {
- Object.keys(commands).forEach(function(name) {
- this.removeCommand(commands[name]);
- }, this);
- };
-
- this.bindKeys = function(keyList) {
- Object.keys(keyList).forEach(function(key) {
- this.bindKey(key, keyList[key]);
- }, this);
- };
-
- this._buildKeyHash = function(command) {
- this.bindKey(command.bindKey, command);
- };
- this.parseKeys = function(keys) {
- var parts = keys.toLowerCase().split(/[\-\+]([\-\+])?/).filter(function(x){return x});
- var key = parts.pop();
-
- var keyCode = keyUtil[key];
- if (keyUtil.FUNCTION_KEYS[keyCode])
- key = keyUtil.FUNCTION_KEYS[keyCode].toLowerCase();
- else if (!parts.length)
- return {key: key, hashId: -1};
- else if (parts.length == 1 && parts[0] == "shift")
- return {key: key.toUpperCase(), hashId: -1};
-
- var hashId = 0;
- for (var i = parts.length; i--;) {
- var modifier = keyUtil.KEY_MODS[parts[i]];
- if (modifier == null) {
- if (typeof console != "undefined")
- console.error("invalid modifier " + parts[i] + " in " + keys);
- return false;
- }
- hashId |= modifier;
- }
- return {key: key, hashId: hashId};
- };
-
- this.findKeyCommand = function findKeyCommand(hashId, keyString) {
- var key = KEY_MODS[hashId] + keyString;
- return this.commandKeyBinding[key];
- };
-
- this.handleKeyboard = function(data, hashId, keyString, keyCode) {
- if (keyCode < 0) return;
- var key = KEY_MODS[hashId] + keyString;
- var command = this.commandKeyBinding[key];
- if (data.$keyChain) {
- data.$keyChain += " " + key;
- command = this.commandKeyBinding[data.$keyChain] || command;
- }
-
- if (command) {
- if (command == "chainKeys" || command[command.length - 1] == "chainKeys") {
- data.$keyChain = data.$keyChain || key;
- return {command: "null"};
- }
- }
-
- if (data.$keyChain) {
- if ((!hashId || hashId == 4) && keyString.length == 1)
- data.$keyChain = data.$keyChain.slice(0, -key.length - 1); // wait for input
- else if (hashId == -1 || keyCode > 0)
- data.$keyChain = ""; // reset keyChain
- }
- return {command: command};
- };
-
- this.getStatusText = function(editor, data) {
- return data.$keyChain || "";
- };
-
-}).call(HashHandler.prototype);
-
-exports.HashHandler = HashHandler;
-exports.MultiHashHandler = MultiHashHandler;
-});
-
-ace.define("ace/commands/command_manager",["require","exports","module","ace/lib/oop","ace/keyboard/hash_handler","ace/lib/event_emitter"], function(require, exports, module) {
-"use strict";
-
-var oop = require("../lib/oop");
-var MultiHashHandler = require("../keyboard/hash_handler").MultiHashHandler;
-var EventEmitter = require("../lib/event_emitter").EventEmitter;
-
-var CommandManager = function(platform, commands) {
- MultiHashHandler.call(this, commands, platform);
- this.byName = this.commands;
- this.setDefaultHandler("exec", function(e) {
- return e.command.exec(e.editor, e.args || {});
- });
-};
-
-oop.inherits(CommandManager, MultiHashHandler);
-
-(function() {
-
- oop.implement(this, EventEmitter);
-
- this.exec = function(command, editor, args) {
- if (Array.isArray(command)) {
- for (var i = command.length; i--; ) {
- if (this.exec(command[i], editor, args)) return true;
- }
- return false;
- }
-
- if (typeof command === "string")
- command = this.commands[command];
-
- if (!command)
- return false;
-
- if (editor && editor.$readOnly && !command.readOnly)
- return false;
-
- var e = {editor: editor, command: command, args: args};
- e.returnValue = this._emit("exec", e);
- this._signal("afterExec", e);
-
- return e.returnValue === false ? false : true;
- };
-
- this.toggleRecording = function(editor) {
- if (this.$inReplay)
- return;
-
- editor && editor._emit("changeStatus");
- if (this.recording) {
- this.macro.pop();
- this.removeEventListener("exec", this.$addCommandToMacro);
-
- if (!this.macro.length)
- this.macro = this.oldMacro;
-
- return this.recording = false;
- }
- if (!this.$addCommandToMacro) {
- this.$addCommandToMacro = function(e) {
- this.macro.push([e.command, e.args]);
- }.bind(this);
- }
-
- this.oldMacro = this.macro;
- this.macro = [];
- this.on("exec", this.$addCommandToMacro);
- return this.recording = true;
- };
-
- this.replay = function(editor) {
- if (this.$inReplay || !this.macro)
- return;
-
- if (this.recording)
- return this.toggleRecording(editor);
-
- try {
- this.$inReplay = true;
- this.macro.forEach(function(x) {
- if (typeof x == "string")
- this.exec(x, editor);
- else
- this.exec(x[0], editor, x[1]);
- }, this);
- } finally {
- this.$inReplay = false;
- }
- };
-
- this.trimMacro = function(m) {
- return m.map(function(x){
- if (typeof x[0] != "string")
- x[0] = x[0].name;
- if (!x[1])
- x = x[0];
- return x;
- });
- };
-
-}).call(CommandManager.prototype);
-
-exports.CommandManager = CommandManager;
-
-});
-
-ace.define("ace/commands/default_commands",["require","exports","module","ace/lib/lang","ace/config","ace/range"], function(require, exports, module) {
-"use strict";
-
-var lang = require("../lib/lang");
-var config = require("../config");
-var Range = require("../range").Range;
-
-function bindKey(win, mac) {
- return {win: win, mac: mac};
-}
-exports.commands = [{
- name: "showSettingsMenu",
- bindKey: bindKey("Ctrl-,", "Command-,"),
- exec: function(editor) {
- config.loadModule("ace/ext/settings_menu", function(module) {
- module.init(editor);
- editor.showSettingsMenu();
- });
- },
- readOnly: true
-}, {
- name: "goToNextError",
- bindKey: bindKey("Alt-E", "Ctrl-E"),
- exec: function(editor) {
- config.loadModule("ace/ext/error_marker", function(module) {
- module.showErrorMarker(editor, 1);
- });
- },
- scrollIntoView: "animate",
- readOnly: true
-}, {
- name: "goToPreviousError",
- bindKey: bindKey("Alt-Shift-E", "Ctrl-Shift-E"),
- exec: function(editor) {
- config.loadModule("ace/ext/error_marker", function(module) {
- module.showErrorMarker(editor, -1);
- });
- },
- scrollIntoView: "animate",
- readOnly: true
-}, {
- name: "selectall",
- bindKey: bindKey("Ctrl-A", "Command-A"),
- exec: function(editor) { editor.selectAll(); },
- readOnly: true
-}, {
- name: "centerselection",
- bindKey: bindKey(null, "Ctrl-L"),
- exec: function(editor) { editor.centerSelection(); },
- readOnly: true
-}, {
- name: "gotoline",
- bindKey: bindKey("Ctrl-L", "Command-L"),
- exec: function(editor) {
- var line = parseInt(prompt("Enter line number:"), 10);
- if (!isNaN(line)) {
- editor.gotoLine(line);
- }
- },
- readOnly: true
-}, {
- name: "fold",
- bindKey: bindKey("Alt-L|Ctrl-F1", "Command-Alt-L|Command-F1"),
- exec: function(editor) { editor.session.toggleFold(false); },
- multiSelectAction: "forEach",
- scrollIntoView: "center",
- readOnly: true
-}, {
- name: "unfold",
- bindKey: bindKey("Alt-Shift-L|Ctrl-Shift-F1", "Command-Alt-Shift-L|Command-Shift-F1"),
- exec: function(editor) { editor.session.toggleFold(true); },
- multiSelectAction: "forEach",
- scrollIntoView: "center",
- readOnly: true
-}, {
- name: "toggleFoldWidget",
- bindKey: bindKey("F2", "F2"),
- exec: function(editor) { editor.session.toggleFoldWidget(); },
- multiSelectAction: "forEach",
- scrollIntoView: "center",
- readOnly: true
-}, {
- name: "toggleParentFoldWidget",
- bindKey: bindKey("Alt-F2", "Alt-F2"),
- exec: function(editor) { editor.session.toggleFoldWidget(true); },
- multiSelectAction: "forEach",
- scrollIntoView: "center",
- readOnly: true
-}, {
- name: "foldall",
- bindKey: bindKey(null, "Ctrl-Command-Option-0"),
- exec: function(editor) { editor.session.foldAll(); },
- scrollIntoView: "center",
- readOnly: true
-}, {
- name: "foldOther",
- bindKey: bindKey("Alt-0", "Command-Option-0"),
- exec: function(editor) {
- editor.session.foldAll();
- editor.session.unfold(editor.selection.getAllRanges());
- },
- scrollIntoView: "center",
- readOnly: true
-}, {
- name: "unfoldall",
- bindKey: bindKey("Alt-Shift-0", "Command-Option-Shift-0"),
- exec: function(editor) { editor.session.unfold(); },
- scrollIntoView: "center",
- readOnly: true
-}, {
- name: "findnext",
- bindKey: bindKey("Ctrl-K", "Command-G"),
- exec: function(editor) { editor.findNext(); },
- multiSelectAction: "forEach",
- scrollIntoView: "center",
- readOnly: true
-}, {
- name: "findprevious",
- bindKey: bindKey("Ctrl-Shift-K", "Command-Shift-G"),
- exec: function(editor) { editor.findPrevious(); },
- multiSelectAction: "forEach",
- scrollIntoView: "center",
- readOnly: true
-}, {
- name: "selectOrFindNext",
- bindKey: bindKey("Alt-K", "Ctrl-G"),
- exec: function(editor) {
- if (editor.selection.isEmpty())
- editor.selection.selectWord();
- else
- editor.findNext();
- },
- readOnly: true
-}, {
- name: "selectOrFindPrevious",
- bindKey: bindKey("Alt-Shift-K", "Ctrl-Shift-G"),
- exec: function(editor) {
- if (editor.selection.isEmpty())
- editor.selection.selectWord();
- else
- editor.findPrevious();
- },
- readOnly: true
-}, {
- name: "find",
- bindKey: bindKey("Ctrl-F", "Command-F"),
- exec: function(editor) {
- config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor)});
- },
- readOnly: true
-}, {
- name: "overwrite",
- bindKey: "Insert",
- exec: function(editor) { editor.toggleOverwrite(); },
- readOnly: true
-}, {
- name: "selecttostart",
- bindKey: bindKey("Ctrl-Shift-Home", "Command-Shift-Up"),
- exec: function(editor) { editor.getSelection().selectFileStart(); },
- multiSelectAction: "forEach",
- readOnly: true,
- scrollIntoView: "animate",
- aceCommandGroup: "fileJump"
-}, {
- name: "gotostart",
- bindKey: bindKey("Ctrl-Home", "Command-Home|Command-Up"),
- exec: function(editor) { editor.navigateFileStart(); },
- multiSelectAction: "forEach",
- readOnly: true,
- scrollIntoView: "animate",
- aceCommandGroup: "fileJump"
-}, {
- name: "selectup",
- bindKey: bindKey("Shift-Up", "Shift-Up"),
- exec: function(editor) { editor.getSelection().selectUp(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "golineup",
- bindKey: bindKey("Up", "Up|Ctrl-P"),
- exec: function(editor, args) { editor.navigateUp(args.times); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selecttoend",
- bindKey: bindKey("Ctrl-Shift-End", "Command-Shift-Down"),
- exec: function(editor) { editor.getSelection().selectFileEnd(); },
- multiSelectAction: "forEach",
- readOnly: true,
- scrollIntoView: "animate",
- aceCommandGroup: "fileJump"
-}, {
- name: "gotoend",
- bindKey: bindKey("Ctrl-End", "Command-End|Command-Down"),
- exec: function(editor) { editor.navigateFileEnd(); },
- multiSelectAction: "forEach",
- readOnly: true,
- scrollIntoView: "animate",
- aceCommandGroup: "fileJump"
-}, {
- name: "selectdown",
- bindKey: bindKey("Shift-Down", "Shift-Down"),
- exec: function(editor) { editor.getSelection().selectDown(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "golinedown",
- bindKey: bindKey("Down", "Down|Ctrl-N"),
- exec: function(editor, args) { editor.navigateDown(args.times); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selectwordleft",
- bindKey: bindKey("Ctrl-Shift-Left", "Option-Shift-Left"),
- exec: function(editor) { editor.getSelection().selectWordLeft(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "gotowordleft",
- bindKey: bindKey("Ctrl-Left", "Option-Left"),
- exec: function(editor) { editor.navigateWordLeft(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selecttolinestart",
- bindKey: bindKey("Alt-Shift-Left", "Command-Shift-Left"),
- exec: function(editor) { editor.getSelection().selectLineStart(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "gotolinestart",
- bindKey: bindKey("Alt-Left|Home", "Command-Left|Home|Ctrl-A"),
- exec: function(editor) { editor.navigateLineStart(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selectleft",
- bindKey: bindKey("Shift-Left", "Shift-Left"),
- exec: function(editor) { editor.getSelection().selectLeft(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "gotoleft",
- bindKey: bindKey("Left", "Left|Ctrl-B"),
- exec: function(editor, args) { editor.navigateLeft(args.times); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selectwordright",
- bindKey: bindKey("Ctrl-Shift-Right", "Option-Shift-Right"),
- exec: function(editor) { editor.getSelection().selectWordRight(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "gotowordright",
- bindKey: bindKey("Ctrl-Right", "Option-Right"),
- exec: function(editor) { editor.navigateWordRight(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selecttolineend",
- bindKey: bindKey("Alt-Shift-Right", "Command-Shift-Right"),
- exec: function(editor) { editor.getSelection().selectLineEnd(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "gotolineend",
- bindKey: bindKey("Alt-Right|End", "Command-Right|End|Ctrl-E"),
- exec: function(editor) { editor.navigateLineEnd(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selectright",
- bindKey: bindKey("Shift-Right", "Shift-Right"),
- exec: function(editor) { editor.getSelection().selectRight(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "gotoright",
- bindKey: bindKey("Right", "Right|Ctrl-F"),
- exec: function(editor, args) { editor.navigateRight(args.times); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selectpagedown",
- bindKey: "Shift-PageDown",
- exec: function(editor) { editor.selectPageDown(); },
- readOnly: true
-}, {
- name: "pagedown",
- bindKey: bindKey(null, "Option-PageDown"),
- exec: function(editor) { editor.scrollPageDown(); },
- readOnly: true
-}, {
- name: "gotopagedown",
- bindKey: bindKey("PageDown", "PageDown|Ctrl-V"),
- exec: function(editor) { editor.gotoPageDown(); },
- readOnly: true
-}, {
- name: "selectpageup",
- bindKey: "Shift-PageUp",
- exec: function(editor) { editor.selectPageUp(); },
- readOnly: true
-}, {
- name: "pageup",
- bindKey: bindKey(null, "Option-PageUp"),
- exec: function(editor) { editor.scrollPageUp(); },
- readOnly: true
-}, {
- name: "gotopageup",
- bindKey: "PageUp",
- exec: function(editor) { editor.gotoPageUp(); },
- readOnly: true
-}, {
- name: "scrollup",
- bindKey: bindKey("Ctrl-Up", null),
- exec: function(e) { e.renderer.scrollBy(0, -2 * e.renderer.layerConfig.lineHeight); },
- readOnly: true
-}, {
- name: "scrolldown",
- bindKey: bindKey("Ctrl-Down", null),
- exec: function(e) { e.renderer.scrollBy(0, 2 * e.renderer.layerConfig.lineHeight); },
- readOnly: true
-}, {
- name: "selectlinestart",
- bindKey: "Shift-Home",
- exec: function(editor) { editor.getSelection().selectLineStart(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selectlineend",
- bindKey: "Shift-End",
- exec: function(editor) { editor.getSelection().selectLineEnd(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "togglerecording",
- bindKey: bindKey("Ctrl-Alt-E", "Command-Option-E"),
- exec: function(editor) { editor.commands.toggleRecording(editor); },
- readOnly: true
-}, {
- name: "replaymacro",
- bindKey: bindKey("Ctrl-Shift-E", "Command-Shift-E"),
- exec: function(editor) { editor.commands.replay(editor); },
- readOnly: true
-}, {
- name: "jumptomatching",
- bindKey: bindKey("Ctrl-P", "Ctrl-P"),
- exec: function(editor) { editor.jumpToMatching(); },
- multiSelectAction: "forEach",
- scrollIntoView: "animate",
- readOnly: true
-}, {
- name: "selecttomatching",
- bindKey: bindKey("Ctrl-Shift-P", "Ctrl-Shift-P"),
- exec: function(editor) { editor.jumpToMatching(true); },
- multiSelectAction: "forEach",
- scrollIntoView: "animate",
- readOnly: true
-}, {
- name: "expandToMatching",
- bindKey: bindKey("Ctrl-Shift-M", "Ctrl-Shift-M"),
- exec: function(editor) { editor.jumpToMatching(true, true); },
- multiSelectAction: "forEach",
- scrollIntoView: "animate",
- readOnly: true
-}, {
- name: "passKeysToBrowser",
- bindKey: bindKey(null, null),
- exec: function() {},
- passEvent: true,
- readOnly: true
-}, {
- name: "copy",
- exec: function(editor) {
- },
- readOnly: true
-},
-{
- name: "cut",
- exec: function(editor) {
- var range = editor.getSelectionRange();
- editor._emit("cut", range);
-
- if (!editor.selection.isEmpty()) {
- editor.session.remove(range);
- editor.clearSelection();
- }
- },
- scrollIntoView: "cursor",
- multiSelectAction: "forEach"
-}, {
- name: "paste",
- exec: function(editor, args) {
- editor.$handlePaste(args);
- },
- scrollIntoView: "cursor"
-}, {
- name: "removeline",
- bindKey: bindKey("Ctrl-D", "Command-D"),
- exec: function(editor) { editor.removeLines(); },
- scrollIntoView: "cursor",
- multiSelectAction: "forEachLine"
-}, {
- name: "duplicateSelection",
- bindKey: bindKey("Ctrl-Shift-D", "Command-Shift-D"),
- exec: function(editor) { editor.duplicateSelection(); },
- scrollIntoView: "cursor",
- multiSelectAction: "forEach"
-}, {
- name: "sortlines",
- bindKey: bindKey("Ctrl-Alt-S", "Command-Alt-S"),
- exec: function(editor) { editor.sortLines(); },
- scrollIntoView: "selection",
- multiSelectAction: "forEachLine"
-}, {
- name: "togglecomment",
- bindKey: bindKey("Ctrl-/", "Command-/"),
- exec: function(editor) { editor.toggleCommentLines(); },
- multiSelectAction: "forEachLine",
- scrollIntoView: "selectionPart"
-}, {
- name: "toggleBlockComment",
- bindKey: bindKey("Ctrl-Shift-/", "Command-Shift-/"),
- exec: function(editor) { editor.toggleBlockComment(); },
- multiSelectAction: "forEach",
- scrollIntoView: "selectionPart"
-}, {
- name: "modifyNumberUp",
- bindKey: bindKey("Ctrl-Shift-Up", "Alt-Shift-Up"),
- exec: function(editor) { editor.modifyNumber(1); },
- scrollIntoView: "cursor",
- multiSelectAction: "forEach"
-}, {
- name: "modifyNumberDown",
- bindKey: bindKey("Ctrl-Shift-Down", "Alt-Shift-Down"),
- exec: function(editor) { editor.modifyNumber(-1); },
- scrollIntoView: "cursor",
- multiSelectAction: "forEach"
-}, {
- name: "replace",
- bindKey: bindKey("Ctrl-H", "Command-Option-F"),
- exec: function(editor) {
- config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor, true)});
- }
-}, {
- name: "undo",
- bindKey: bindKey("Ctrl-Z", "Command-Z"),
- exec: function(editor) { editor.undo(); }
-}, {
- name: "redo",
- bindKey: bindKey("Ctrl-Shift-Z|Ctrl-Y", "Command-Shift-Z|Command-Y"),
- exec: function(editor) { editor.redo(); }
-}, {
- name: "copylinesup",
- bindKey: bindKey("Alt-Shift-Up", "Command-Option-Up"),
- exec: function(editor) { editor.copyLinesUp(); },
- scrollIntoView: "cursor"
-}, {
- name: "movelinesup",
- bindKey: bindKey("Alt-Up", "Option-Up"),
- exec: function(editor) { editor.moveLinesUp(); },
- scrollIntoView: "cursor"
-}, {
- name: "copylinesdown",
- bindKey: bindKey("Alt-Shift-Down", "Command-Option-Down"),
- exec: function(editor) { editor.copyLinesDown(); },
- scrollIntoView: "cursor"
-}, {
- name: "movelinesdown",
- bindKey: bindKey("Alt-Down", "Option-Down"),
- exec: function(editor) { editor.moveLinesDown(); },
- scrollIntoView: "cursor"
-}, {
- name: "del",
- bindKey: bindKey("Delete", "Delete|Ctrl-D|Shift-Delete"),
- exec: function(editor) { editor.remove("right"); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor"
-}, {
- name: "backspace",
- bindKey: bindKey(
- "Shift-Backspace|Backspace",
- "Ctrl-Backspace|Shift-Backspace|Backspace|Ctrl-H"
- ),
- exec: function(editor) { editor.remove("left"); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor"
-}, {
- name: "cut_or_delete",
- bindKey: bindKey("Shift-Delete", null),
- exec: function(editor) {
- if (editor.selection.isEmpty()) {
- editor.remove("left");
- } else {
- return false;
- }
- },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor"
-}, {
- name: "removetolinestart",
- bindKey: bindKey("Alt-Backspace", "Command-Backspace"),
- exec: function(editor) { editor.removeToLineStart(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor"
-}, {
- name: "removetolineend",
- bindKey: bindKey("Alt-Delete", "Ctrl-K"),
- exec: function(editor) { editor.removeToLineEnd(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor"
-}, {
- name: "removewordleft",
- bindKey: bindKey("Ctrl-Backspace", "Alt-Backspace|Ctrl-Alt-Backspace"),
- exec: function(editor) { editor.removeWordLeft(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor"
-}, {
- name: "removewordright",
- bindKey: bindKey("Ctrl-Delete", "Alt-Delete"),
- exec: function(editor) { editor.removeWordRight(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor"
-}, {
- name: "outdent",
- bindKey: bindKey("Shift-Tab", "Shift-Tab"),
- exec: function(editor) { editor.blockOutdent(); },
- multiSelectAction: "forEach",
- scrollIntoView: "selectionPart"
-}, {
- name: "indent",
- bindKey: bindKey("Tab", "Tab"),
- exec: function(editor) { editor.indent(); },
- multiSelectAction: "forEach",
- scrollIntoView: "selectionPart"
-}, {
- name: "blockoutdent",
- bindKey: bindKey("Ctrl-[", "Ctrl-["),
- exec: function(editor) { editor.blockOutdent(); },
- multiSelectAction: "forEachLine",
- scrollIntoView: "selectionPart"
-}, {
- name: "blockindent",
- bindKey: bindKey("Ctrl-]", "Ctrl-]"),
- exec: function(editor) { editor.blockIndent(); },
- multiSelectAction: "forEachLine",
- scrollIntoView: "selectionPart"
-}, {
- name: "insertstring",
- exec: function(editor, str) { editor.insert(str); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor"
-}, {
- name: "inserttext",
- exec: function(editor, args) {
- editor.insert(lang.stringRepeat(args.text || "", args.times || 1));
- },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor"
-}, {
- name: "splitline",
- bindKey: bindKey(null, "Ctrl-O"),
- exec: function(editor) { editor.splitLine(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor"
-}, {
- name: "transposeletters",
- bindKey: bindKey("Ctrl-T", "Ctrl-T"),
- exec: function(editor) { editor.transposeLetters(); },
- multiSelectAction: function(editor) {editor.transposeSelections(1); },
- scrollIntoView: "cursor"
-}, {
- name: "touppercase",
- bindKey: bindKey("Ctrl-U", "Ctrl-U"),
- exec: function(editor) { editor.toUpperCase(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor"
-}, {
- name: "tolowercase",
- bindKey: bindKey("Ctrl-Shift-U", "Ctrl-Shift-U"),
- exec: function(editor) { editor.toLowerCase(); },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor"
-}, {
- name: "expandtoline",
- bindKey: bindKey("Ctrl-Shift-L", "Command-Shift-L"),
- exec: function(editor) {
- var range = editor.selection.getRange();
-
- range.start.column = range.end.column = 0;
- range.end.row++;
- editor.selection.setRange(range, false);
- },
- multiSelectAction: "forEach",
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "joinlines",
- bindKey: bindKey(null, null),
- exec: function(editor) {
- var isBackwards = editor.selection.isBackwards();
- var selectionStart = isBackwards ? editor.selection.getSelectionLead() : editor.selection.getSelectionAnchor();
- var selectionEnd = isBackwards ? editor.selection.getSelectionAnchor() : editor.selection.getSelectionLead();
- var firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length;
- var selectedText = editor.session.doc.getTextRange(editor.selection.getRange());
- var selectedCount = selectedText.replace(/\n\s*/, " ").length;
- var insertLine = editor.session.doc.getLine(selectionStart.row);
-
- for (var i = selectionStart.row + 1; i <= selectionEnd.row + 1; i++) {
- var curLine = lang.stringTrimLeft(lang.stringTrimRight(editor.session.doc.getLine(i)));
- if (curLine.length !== 0) {
- curLine = " " + curLine;
- }
- insertLine += curLine;
- }
-
- if (selectionEnd.row + 1 < (editor.session.doc.getLength() - 1)) {
- insertLine += editor.session.doc.getNewLineCharacter();
- }
-
- editor.clearSelection();
- editor.session.doc.replace(new Range(selectionStart.row, 0, selectionEnd.row + 2, 0), insertLine);
-
- if (selectedCount > 0) {
- editor.selection.moveCursorTo(selectionStart.row, selectionStart.column);
- editor.selection.selectTo(selectionStart.row, selectionStart.column + selectedCount);
- } else {
- firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length > firstLineEndCol ? (firstLineEndCol + 1) : firstLineEndCol;
- editor.selection.moveCursorTo(selectionStart.row, firstLineEndCol);
- }
- },
- multiSelectAction: "forEach",
- readOnly: true
-}, {
- name: "invertSelection",
- bindKey: bindKey(null, null),
- exec: function(editor) {
- var endRow = editor.session.doc.getLength() - 1;
- var endCol = editor.session.doc.getLine(endRow).length;
- var ranges = editor.selection.rangeList.ranges;
- var newRanges = [];
- if (ranges.length < 1) {
- ranges = [editor.selection.getRange()];
- }
-
- for (var i = 0; i < ranges.length; i++) {
- if (i == (ranges.length - 1)) {
- if (!(ranges[i].end.row === endRow && ranges[i].end.column === endCol)) {
- newRanges.push(new Range(ranges[i].end.row, ranges[i].end.column, endRow, endCol));
- }
- }
-
- if (i === 0) {
- if (!(ranges[i].start.row === 0 && ranges[i].start.column === 0)) {
- newRanges.push(new Range(0, 0, ranges[i].start.row, ranges[i].start.column));
- }
- } else {
- newRanges.push(new Range(ranges[i-1].end.row, ranges[i-1].end.column, ranges[i].start.row, ranges[i].start.column));
- }
- }
-
- editor.exitMultiSelectMode();
- editor.clearSelection();
-
- for(var i = 0; i < newRanges.length; i++) {
- editor.selection.addRange(newRanges[i], false);
- }
- },
- readOnly: true,
- scrollIntoView: "none"
-}];
-
-});
-
-ace.define("ace/editor",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/keyboard/textinput","ace/mouse/mouse_handler","ace/mouse/fold_handler","ace/keyboard/keybinding","ace/edit_session","ace/search","ace/range","ace/lib/event_emitter","ace/commands/command_manager","ace/commands/default_commands","ace/config","ace/token_iterator"], function(require, exports, module) {
-"use strict";
-
-require("./lib/fixoldbrowsers");
-
-var oop = require("./lib/oop");
-var dom = require("./lib/dom");
-var lang = require("./lib/lang");
-var useragent = require("./lib/useragent");
-var TextInput = require("./keyboard/textinput").TextInput;
-var MouseHandler = require("./mouse/mouse_handler").MouseHandler;
-var FoldHandler = require("./mouse/fold_handler").FoldHandler;
-var KeyBinding = require("./keyboard/keybinding").KeyBinding;
-var EditSession = require("./edit_session").EditSession;
-var Search = require("./search").Search;
-var Range = require("./range").Range;
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-var CommandManager = require("./commands/command_manager").CommandManager;
-var defaultCommands = require("./commands/default_commands").commands;
-var config = require("./config");
-var TokenIterator = require("./token_iterator").TokenIterator;
-var Editor = function(renderer, session) {
- var container = renderer.getContainerElement();
- this.container = container;
- this.renderer = renderer;
-
- this.commands = new CommandManager(useragent.isMac ? "mac" : "win", defaultCommands);
- this.textInput = new TextInput(renderer.getTextAreaContainer(), this);
- this.renderer.textarea = this.textInput.getElement();
- this.keyBinding = new KeyBinding(this);
- this.$mouseHandler = new MouseHandler(this);
- new FoldHandler(this);
-
- this.$blockScrolling = Infinity;
- this.$search = new Search().set({
- wrap: true
- });
-
- this.$historyTracker = this.$historyTracker.bind(this);
- this.commands.on("exec", this.$historyTracker);
-
- this.$initOperationListeners();
-
- this._$emitInputEvent = lang.delayedCall(function() {
- this._signal("input", {});
- if (this.session && this.session.bgTokenizer)
- this.session.bgTokenizer.scheduleStart();
- }.bind(this));
-
- this.on("change", function(_, _self) {
- _self._$emitInputEvent.schedule(31);
- });
-
- this.setSession(session || new EditSession(""));
- config.resetOptions(this);
- config._signal("editor", this);
-};
-
-(function(){
-
- oop.implement(this, EventEmitter);
-
- this.$initOperationListeners = function() {
- function last(a) {return a[a.length - 1]}
-
- this.selections = [];
- this.commands.on("exec", this.startOperation.bind(this), true);
- this.commands.on("afterExec", this.endOperation.bind(this), true);
-
- this.$opResetTimer = lang.delayedCall(this.endOperation.bind(this));
-
- this.on("change", function() {
- this.curOp || this.startOperation();
- this.curOp.docChanged = true;
- }.bind(this), true);
-
- this.on("changeSelection", function() {
- this.curOp || this.startOperation();
- this.curOp.selectionChanged = true;
- }.bind(this), true);
- };
-
- this.curOp = null;
- this.prevOp = {};
- this.startOperation = function(commadEvent) {
- if (this.curOp) {
- if (!commadEvent || this.curOp.command)
- return;
- this.prevOp = this.curOp;
- }
- if (!commadEvent) {
- this.previousCommand = null;
- commadEvent = {};
- }
-
- this.$opResetTimer.schedule();
- this.curOp = {
- command: commadEvent.command || {},
- args: commadEvent.args,
- scrollTop: this.renderer.scrollTop
- };
- if (this.curOp.command.name && this.curOp.command.scrollIntoView !== undefined)
- this.$blockScrolling++;
- };
-
- this.endOperation = function(e) {
- if (this.curOp) {
- if (e && e.returnValue === false)
- return this.curOp = null;
- this._signal("beforeEndOperation");
- var command = this.curOp.command;
- if (command.name && this.$blockScrolling > 0)
- this.$blockScrolling--;
- var scrollIntoView = command && command.scrollIntoView;
- if (scrollIntoView) {
- switch (scrollIntoView) {
- case "center-animate":
- scrollIntoView = "animate";
- case "center":
- this.renderer.scrollCursorIntoView(null, 0.5);
- break;
- case "animate":
- case "cursor":
- this.renderer.scrollCursorIntoView();
- break;
- case "selectionPart":
- var range = this.selection.getRange();
- var config = this.renderer.layerConfig;
- if (range.start.row >= config.lastRow || range.end.row <= config.firstRow) {
- this.renderer.scrollSelectionIntoView(this.selection.anchor, this.selection.lead);
- }
- break;
- default:
- break;
- }
- if (scrollIntoView == "animate")
- this.renderer.animateScrolling(this.curOp.scrollTop);
- }
-
- this.prevOp = this.curOp;
- this.curOp = null;
- }
- };
- this.$mergeableCommands = ["backspace", "del", "insertstring"];
- this.$historyTracker = function(e) {
- if (!this.$mergeUndoDeltas)
- return;
-
- var prev = this.prevOp;
- var mergeableCommands = this.$mergeableCommands;
- var shouldMerge = prev.command && (e.command.name == prev.command.name);
- if (e.command.name == "insertstring") {
- var text = e.args;
- if (this.mergeNextCommand === undefined)
- this.mergeNextCommand = true;
-
- shouldMerge = shouldMerge
- && this.mergeNextCommand // previous command allows to coalesce with
- && (!/\s/.test(text) || /\s/.test(prev.args)); // previous insertion was of same type
-
- this.mergeNextCommand = true;
- } else {
- shouldMerge = shouldMerge
- && mergeableCommands.indexOf(e.command.name) !== -1; // the command is mergeable
- }
-
- if (
- this.$mergeUndoDeltas != "always"
- && Date.now() - this.sequenceStartTime > 2000
- ) {
- shouldMerge = false; // the sequence is too long
- }
-
- if (shouldMerge)
- this.session.mergeUndoDeltas = true;
- else if (mergeableCommands.indexOf(e.command.name) !== -1)
- this.sequenceStartTime = Date.now();
- };
- this.setKeyboardHandler = function(keyboardHandler, cb) {
- if (keyboardHandler && typeof keyboardHandler === "string") {
- this.$keybindingId = keyboardHandler;
- var _self = this;
- config.loadModule(["keybinding", keyboardHandler], function(module) {
- if (_self.$keybindingId == keyboardHandler)
- _self.keyBinding.setKeyboardHandler(module && module.handler);
- cb && cb();
- });
- } else {
- this.$keybindingId = null;
- this.keyBinding.setKeyboardHandler(keyboardHandler);
- cb && cb();
- }
- };
- this.getKeyboardHandler = function() {
- return this.keyBinding.getKeyboardHandler();
- };
- this.setSession = function(session) {
- if (this.session == session)
- return;
- if (this.curOp) this.endOperation();
- this.curOp = {};
-
- var oldSession = this.session;
- if (oldSession) {
- this.session.off("change", this.$onDocumentChange);
- this.session.off("changeMode", this.$onChangeMode);
- this.session.off("tokenizerUpdate", this.$onTokenizerUpdate);
- this.session.off("changeTabSize", this.$onChangeTabSize);
- this.session.off("changeWrapLimit", this.$onChangeWrapLimit);
- this.session.off("changeWrapMode", this.$onChangeWrapMode);
- this.session.off("changeFold", this.$onChangeFold);
- this.session.off("changeFrontMarker", this.$onChangeFrontMarker);
- this.session.off("changeBackMarker", this.$onChangeBackMarker);
- this.session.off("changeBreakpoint", this.$onChangeBreakpoint);
- this.session.off("changeAnnotation", this.$onChangeAnnotation);
- this.session.off("changeOverwrite", this.$onCursorChange);
- this.session.off("changeScrollTop", this.$onScrollTopChange);
- this.session.off("changeScrollLeft", this.$onScrollLeftChange);
-
- var selection = this.session.getSelection();
- selection.off("changeCursor", this.$onCursorChange);
- selection.off("changeSelection", this.$onSelectionChange);
- }
-
- this.session = session;
- if (session) {
- this.$onDocumentChange = this.onDocumentChange.bind(this);
- session.on("change", this.$onDocumentChange);
- this.renderer.setSession(session);
-
- this.$onChangeMode = this.onChangeMode.bind(this);
- session.on("changeMode", this.$onChangeMode);
-
- this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this);
- session.on("tokenizerUpdate", this.$onTokenizerUpdate);
-
- this.$onChangeTabSize = this.renderer.onChangeTabSize.bind(this.renderer);
- session.on("changeTabSize", this.$onChangeTabSize);
-
- this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this);
- session.on("changeWrapLimit", this.$onChangeWrapLimit);
-
- this.$onChangeWrapMode = this.onChangeWrapMode.bind(this);
- session.on("changeWrapMode", this.$onChangeWrapMode);
-
- this.$onChangeFold = this.onChangeFold.bind(this);
- session.on("changeFold", this.$onChangeFold);
-
- this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this);
- this.session.on("changeFrontMarker", this.$onChangeFrontMarker);
-
- this.$onChangeBackMarker = this.onChangeBackMarker.bind(this);
- this.session.on("changeBackMarker", this.$onChangeBackMarker);
-
- this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this);
- this.session.on("changeBreakpoint", this.$onChangeBreakpoint);
-
- this.$onChangeAnnotation = this.onChangeAnnotation.bind(this);
- this.session.on("changeAnnotation", this.$onChangeAnnotation);
-
- this.$onCursorChange = this.onCursorChange.bind(this);
- this.session.on("changeOverwrite", this.$onCursorChange);
-
- this.$onScrollTopChange = this.onScrollTopChange.bind(this);
- this.session.on("changeScrollTop", this.$onScrollTopChange);
-
- this.$onScrollLeftChange = this.onScrollLeftChange.bind(this);
- this.session.on("changeScrollLeft", this.$onScrollLeftChange);
-
- this.selection = session.getSelection();
- this.selection.on("changeCursor", this.$onCursorChange);
-
- this.$onSelectionChange = this.onSelectionChange.bind(this);
- this.selection.on("changeSelection", this.$onSelectionChange);
-
- this.onChangeMode();
-
- this.$blockScrolling += 1;
- this.onCursorChange();
- this.$blockScrolling -= 1;
-
- this.onScrollTopChange();
- this.onScrollLeftChange();
- this.onSelectionChange();
- this.onChangeFrontMarker();
- this.onChangeBackMarker();
- this.onChangeBreakpoint();
- this.onChangeAnnotation();
- this.session.getUseWrapMode() && this.renderer.adjustWrapLimit();
- this.renderer.updateFull();
- } else {
- this.selection = null;
- this.renderer.setSession(session);
- }
-
- this._signal("changeSession", {
- session: session,
- oldSession: oldSession
- });
-
- this.curOp = null;
-
- oldSession && oldSession._signal("changeEditor", {oldEditor: this});
- session && session._signal("changeEditor", {editor: this});
- };
- this.getSession = function() {
- return this.session;
- };
- this.setValue = function(val, cursorPos) {
- this.session.doc.setValue(val);
-
- if (!cursorPos)
- this.selectAll();
- else if (cursorPos == 1)
- this.navigateFileEnd();
- else if (cursorPos == -1)
- this.navigateFileStart();
-
- return val;
- };
- this.getValue = function() {
- return this.session.getValue();
- };
- this.getSelection = function() {
- return this.selection;
- };
- this.resize = function(force) {
- this.renderer.onResize(force);
- };
- this.setTheme = function(theme, cb) {
- this.renderer.setTheme(theme, cb);
- };
- this.getTheme = function() {
- return this.renderer.getTheme();
- };
- this.setStyle = function(style) {
- this.renderer.setStyle(style);
- };
- this.unsetStyle = function(style) {
- this.renderer.unsetStyle(style);
- };
- this.getFontSize = function () {
- return this.getOption("fontSize") ||
- dom.computedStyle(this.container, "fontSize");
- };
- this.setFontSize = function(size) {
- this.setOption("fontSize", size);
- };
-
- this.$highlightBrackets = function() {
- if (this.session.$bracketHighlight) {
- this.session.removeMarker(this.session.$bracketHighlight);
- this.session.$bracketHighlight = null;
- }
-
- if (this.$highlightPending) {
- return;
- }
- var self = this;
- this.$highlightPending = true;
- setTimeout(function() {
- self.$highlightPending = false;
- var session = self.session;
- if (!session || !session.bgTokenizer) return;
- var pos = session.findMatchingBracket(self.getCursorPosition());
- if (pos) {
- var range = new Range(pos.row, pos.column, pos.row, pos.column + 1);
- } else if (session.$mode.getMatching) {
- var range = session.$mode.getMatching(self.session);
- }
- if (range)
- session.$bracketHighlight = session.addMarker(range, "ace_bracket", "text");
- }, 50);
- };
- this.$highlightTags = function() {
- if (this.$highlightTagPending)
- return;
- var self = this;
- this.$highlightTagPending = true;
- setTimeout(function() {
- self.$highlightTagPending = false;
-
- var session = self.session;
- if (!session || !session.bgTokenizer) return;
-
- var pos = self.getCursorPosition();
- var iterator = new TokenIterator(self.session, pos.row, pos.column);
- var token = iterator.getCurrentToken();
-
- if (!token || !/\b(?:tag-open|tag-name)/.test(token.type)) {
- session.removeMarker(session.$tagHighlight);
- session.$tagHighlight = null;
- return;
- }
-
- if (token.type.indexOf("tag-open") != -1) {
- token = iterator.stepForward();
- if (!token)
- return;
- }
-
- var tag = token.value;
- var depth = 0;
- var prevToken = iterator.stepBackward();
-
- if (prevToken.value == '<'){
- do {
- prevToken = token;
- token = iterator.stepForward();
-
- if (token && token.value === tag && token.type.indexOf('tag-name') !== -1) {
- if (prevToken.value === '<'){
- depth++;
- } else if (prevToken.value === ''){
- depth--;
- }
- }
-
- } while (token && depth >= 0);
- } else {
- do {
- token = prevToken;
- prevToken = iterator.stepBackward();
-
- if (token && token.value === tag && token.type.indexOf('tag-name') !== -1) {
- if (prevToken.value === '<') {
- depth++;
- } else if (prevToken.value === '') {
- depth--;
- }
- }
- } while (prevToken && depth <= 0);
- iterator.stepForward();
- }
-
- if (!token) {
- session.removeMarker(session.$tagHighlight);
- session.$tagHighlight = null;
- return;
- }
-
- var row = iterator.getCurrentTokenRow();
- var column = iterator.getCurrentTokenColumn();
- var range = new Range(row, column, row, column+token.value.length);
- if (session.$tagHighlight && range.compareRange(session.$backMarkers[session.$tagHighlight].range)!==0) {
- session.removeMarker(session.$tagHighlight);
- session.$tagHighlight = null;
- }
-
- if (range && !session.$tagHighlight)
- session.$tagHighlight = session.addMarker(range, "ace_bracket", "text");
- }, 50);
- };
- this.focus = function() {
- var _self = this;
- setTimeout(function() {
- _self.textInput.focus();
- });
- this.textInput.focus();
- };
- this.isFocused = function() {
- return this.textInput.isFocused();
- };
- this.blur = function() {
- this.textInput.blur();
- };
- this.onFocus = function(e) {
- if (this.$isFocused)
- return;
- this.$isFocused = true;
- this.renderer.showCursor();
- this.renderer.visualizeFocus();
- this._emit("focus", e);
- };
- this.onBlur = function(e) {
- if (!this.$isFocused)
- return;
- this.$isFocused = false;
- this.renderer.hideCursor();
- this.renderer.visualizeBlur();
- this._emit("blur", e);
- };
-
- this.$cursorChange = function() {
- this.renderer.updateCursor();
- };
- this.onDocumentChange = function(delta) {
- var wrap = this.session.$useWrapMode;
- var lastRow = (delta.start.row == delta.end.row ? delta.end.row : Infinity);
- this.renderer.updateLines(delta.start.row, lastRow, wrap);
-
- this._signal("change", delta);
- this.$cursorChange();
- this.$updateHighlightActiveLine();
- };
-
- this.onTokenizerUpdate = function(e) {
- var rows = e.data;
- this.renderer.updateLines(rows.first, rows.last);
- };
-
-
- this.onScrollTopChange = function() {
- this.renderer.scrollToY(this.session.getScrollTop());
- };
-
- this.onScrollLeftChange = function() {
- this.renderer.scrollToX(this.session.getScrollLeft());
- };
- this.onCursorChange = function() {
- this.$cursorChange();
-
- if (!this.$blockScrolling) {
- config.warn("Automatically scrolling cursor into view after selection change",
- "this will be disabled in the next version",
- "set editor.$blockScrolling = Infinity to disable this message"
- );
- this.renderer.scrollCursorIntoView();
- }
-
- this.$highlightBrackets();
- this.$highlightTags();
- this.$updateHighlightActiveLine();
- this._signal("changeSelection");
- };
-
- this.$updateHighlightActiveLine = function() {
- var session = this.getSession();
-
- var highlight;
- if (this.$highlightActiveLine) {
- if ((this.$selectionStyle != "line" || !this.selection.isMultiLine()))
- highlight = this.getCursorPosition();
- if (this.renderer.$maxLines && this.session.getLength() === 1 && !(this.renderer.$minLines > 1))
- highlight = false;
- }
-
- if (session.$highlightLineMarker && !highlight) {
- session.removeMarker(session.$highlightLineMarker.id);
- session.$highlightLineMarker = null;
- } else if (!session.$highlightLineMarker && highlight) {
- var range = new Range(highlight.row, highlight.column, highlight.row, Infinity);
- range.id = session.addMarker(range, "ace_active-line", "screenLine");
- session.$highlightLineMarker = range;
- } else if (highlight) {
- session.$highlightLineMarker.start.row = highlight.row;
- session.$highlightLineMarker.end.row = highlight.row;
- session.$highlightLineMarker.start.column = highlight.column;
- session._signal("changeBackMarker");
- }
- };
-
- this.onSelectionChange = function(e) {
- var session = this.session;
-
- if (session.$selectionMarker) {
- session.removeMarker(session.$selectionMarker);
- }
- session.$selectionMarker = null;
-
- if (!this.selection.isEmpty()) {
- var range = this.selection.getRange();
- var style = this.getSelectionStyle();
- session.$selectionMarker = session.addMarker(range, "ace_selection", style);
- } else {
- this.$updateHighlightActiveLine();
- }
-
- var re = this.$highlightSelectedWord && this.$getSelectionHighLightRegexp();
- this.session.highlight(re);
-
- this._signal("changeSelection");
- };
-
- this.$getSelectionHighLightRegexp = function() {
- var session = this.session;
-
- var selection = this.getSelectionRange();
- if (selection.isEmpty() || selection.isMultiLine())
- return;
-
- var startOuter = selection.start.column - 1;
- var endOuter = selection.end.column + 1;
- var line = session.getLine(selection.start.row);
- var lineCols = line.length;
- var needle = line.substring(Math.max(startOuter, 0),
- Math.min(endOuter, lineCols));
- if ((startOuter >= 0 && /^[\w\d]/.test(needle)) ||
- (endOuter <= lineCols && /[\w\d]$/.test(needle)))
- return;
-
- needle = line.substring(selection.start.column, selection.end.column);
- if (!/^[\w\d]+$/.test(needle))
- return;
-
- var re = this.$search.$assembleRegExp({
- wholeWord: true,
- caseSensitive: true,
- needle: needle
- });
-
- return re;
- };
-
-
- this.onChangeFrontMarker = function() {
- this.renderer.updateFrontMarkers();
- };
-
- this.onChangeBackMarker = function() {
- this.renderer.updateBackMarkers();
- };
-
-
- this.onChangeBreakpoint = function() {
- this.renderer.updateBreakpoints();
- };
-
- this.onChangeAnnotation = function() {
- this.renderer.setAnnotations(this.session.getAnnotations());
- };
-
-
- this.onChangeMode = function(e) {
- this.renderer.updateText();
- this._emit("changeMode", e);
- };
-
-
- this.onChangeWrapLimit = function() {
- this.renderer.updateFull();
- };
-
- this.onChangeWrapMode = function() {
- this.renderer.onResize(true);
- };
-
-
- this.onChangeFold = function() {
- this.$updateHighlightActiveLine();
- this.renderer.updateFull();
- };
- this.getSelectedText = function() {
- return this.session.getTextRange(this.getSelectionRange());
- };
- this.getCopyText = function() {
- var text = this.getSelectedText();
- this._signal("copy", text);
- return text;
- };
- this.onCopy = function() {
- this.commands.exec("copy", this);
- };
- this.onCut = function() {
- this.commands.exec("cut", this);
- };
- this.onPaste = function(text, event) {
- var e = {text: text, event: event};
- this.commands.exec("paste", this, e);
- };
-
- this.$handlePaste = function(e) {
- if (typeof e == "string")
- e = {text: e};
- this._signal("paste", e);
- var text = e.text;
- if (!this.inMultiSelectMode || this.inVirtualSelectionMode) {
- this.insert(text);
- } else {
- var lines = text.split(/\r\n|\r|\n/);
- var ranges = this.selection.rangeList.ranges;
-
- if (lines.length > ranges.length || lines.length < 2 || !lines[1])
- return this.commands.exec("insertstring", this, text);
-
- for (var i = ranges.length; i--;) {
- var range = ranges[i];
- if (!range.isEmpty())
- this.session.remove(range);
-
- this.session.insert(range.start, lines[i]);
- }
- }
- };
-
- this.execCommand = function(command, args) {
- return this.commands.exec(command, this, args);
- };
- this.insert = function(text, pasted) {
- var session = this.session;
- var mode = session.getMode();
- var cursor = this.getCursorPosition();
-
- if (this.getBehavioursEnabled() && !pasted) {
- var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text);
- if (transform) {
- if (text !== transform.text) {
- this.session.mergeUndoDeltas = false;
- this.$mergeNextCommand = false;
- }
- text = transform.text;
-
- }
- }
-
- if (text == "\t")
- text = this.session.getTabString();
- if (!this.selection.isEmpty()) {
- var range = this.getSelectionRange();
- cursor = this.session.remove(range);
- this.clearSelection();
- }
- else if (this.session.getOverwrite()) {
- var range = new Range.fromPoints(cursor, cursor);
- range.end.column += text.length;
- this.session.remove(range);
- }
-
- if (text == "\n" || text == "\r\n") {
- var line = session.getLine(cursor.row);
- if (cursor.column > line.search(/\S|$/)) {
- var d = line.substr(cursor.column).search(/\S|$/);
- session.doc.removeInLine(cursor.row, cursor.column, cursor.column + d);
- }
- }
- this.clearSelection();
-
- var start = cursor.column;
- var lineState = session.getState(cursor.row);
- var line = session.getLine(cursor.row);
- var shouldOutdent = mode.checkOutdent(lineState, line, text);
- var end = session.insert(cursor, text);
-
- if (transform && transform.selection) {
- if (transform.selection.length == 2) { // Transform relative to the current column
- this.selection.setSelectionRange(
- new Range(cursor.row, start + transform.selection[0],
- cursor.row, start + transform.selection[1]));
- } else { // Transform relative to the current row.
- this.selection.setSelectionRange(
- new Range(cursor.row + transform.selection[0],
- transform.selection[1],
- cursor.row + transform.selection[2],
- transform.selection[3]));
- }
- }
-
- if (session.getDocument().isNewLine(text)) {
- var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString());
-
- session.insert({row: cursor.row+1, column: 0}, lineIndent);
- }
- if (shouldOutdent)
- mode.autoOutdent(lineState, session, cursor.row);
- };
-
- this.onTextInput = function(text) {
- this.keyBinding.onTextInput(text);
- };
-
- this.onCommandKey = function(e, hashId, keyCode) {
- this.keyBinding.onCommandKey(e, hashId, keyCode);
- };
- this.setOverwrite = function(overwrite) {
- this.session.setOverwrite(overwrite);
- };
- this.getOverwrite = function() {
- return this.session.getOverwrite();
- };
- this.toggleOverwrite = function() {
- this.session.toggleOverwrite();
- };
- this.setScrollSpeed = function(speed) {
- this.setOption("scrollSpeed", speed);
- };
- this.getScrollSpeed = function() {
- return this.getOption("scrollSpeed");
- };
- this.setDragDelay = function(dragDelay) {
- this.setOption("dragDelay", dragDelay);
- };
- this.getDragDelay = function() {
- return this.getOption("dragDelay");
- };
- this.setSelectionStyle = function(val) {
- this.setOption("selectionStyle", val);
- };
- this.getSelectionStyle = function() {
- return this.getOption("selectionStyle");
- };
- this.setHighlightActiveLine = function(shouldHighlight) {
- this.setOption("highlightActiveLine", shouldHighlight);
- };
- this.getHighlightActiveLine = function() {
- return this.getOption("highlightActiveLine");
- };
- this.setHighlightGutterLine = function(shouldHighlight) {
- this.setOption("highlightGutterLine", shouldHighlight);
- };
-
- this.getHighlightGutterLine = function() {
- return this.getOption("highlightGutterLine");
- };
- this.setHighlightSelectedWord = function(shouldHighlight) {
- this.setOption("highlightSelectedWord", shouldHighlight);
- };
- this.getHighlightSelectedWord = function() {
- return this.$highlightSelectedWord;
- };
-
- this.setAnimatedScroll = function(shouldAnimate){
- this.renderer.setAnimatedScroll(shouldAnimate);
- };
-
- this.getAnimatedScroll = function(){
- return this.renderer.getAnimatedScroll();
- };
- this.setShowInvisibles = function(showInvisibles) {
- this.renderer.setShowInvisibles(showInvisibles);
- };
- this.getShowInvisibles = function() {
- return this.renderer.getShowInvisibles();
- };
-
- this.setDisplayIndentGuides = function(display) {
- this.renderer.setDisplayIndentGuides(display);
- };
-
- this.getDisplayIndentGuides = function() {
- return this.renderer.getDisplayIndentGuides();
- };
- this.setShowPrintMargin = function(showPrintMargin) {
- this.renderer.setShowPrintMargin(showPrintMargin);
- };
- this.getShowPrintMargin = function() {
- return this.renderer.getShowPrintMargin();
- };
- this.setPrintMarginColumn = function(showPrintMargin) {
- this.renderer.setPrintMarginColumn(showPrintMargin);
- };
- this.getPrintMarginColumn = function() {
- return this.renderer.getPrintMarginColumn();
- };
- this.setReadOnly = function(readOnly) {
- this.setOption("readOnly", readOnly);
- };
- this.getReadOnly = function() {
- return this.getOption("readOnly");
- };
- this.setBehavioursEnabled = function (enabled) {
- this.setOption("behavioursEnabled", enabled);
- };
- this.getBehavioursEnabled = function () {
- return this.getOption("behavioursEnabled");
- };
- this.setWrapBehavioursEnabled = function (enabled) {
- this.setOption("wrapBehavioursEnabled", enabled);
- };
- this.getWrapBehavioursEnabled = function () {
- return this.getOption("wrapBehavioursEnabled");
- };
- this.setShowFoldWidgets = function(show) {
- this.setOption("showFoldWidgets", show);
-
- };
- this.getShowFoldWidgets = function() {
- return this.getOption("showFoldWidgets");
- };
-
- this.setFadeFoldWidgets = function(fade) {
- this.setOption("fadeFoldWidgets", fade);
- };
-
- this.getFadeFoldWidgets = function() {
- return this.getOption("fadeFoldWidgets");
- };
- this.remove = function(dir) {
- if (this.selection.isEmpty()){
- if (dir == "left")
- this.selection.selectLeft();
- else
- this.selection.selectRight();
- }
-
- var range = this.getSelectionRange();
- if (this.getBehavioursEnabled()) {
- var session = this.session;
- var state = session.getState(range.start.row);
- var new_range = session.getMode().transformAction(state, 'deletion', this, session, range);
-
- if (range.end.column === 0) {
- var text = session.getTextRange(range);
- if (text[text.length - 1] == "\n") {
- var line = session.getLine(range.end.row);
- if (/^\s+$/.test(line)) {
- range.end.column = line.length;
- }
- }
- }
- if (new_range)
- range = new_range;
- }
-
- this.session.remove(range);
- this.clearSelection();
- };
- this.removeWordRight = function() {
- if (this.selection.isEmpty())
- this.selection.selectWordRight();
-
- this.session.remove(this.getSelectionRange());
- this.clearSelection();
- };
- this.removeWordLeft = function() {
- if (this.selection.isEmpty())
- this.selection.selectWordLeft();
-
- this.session.remove(this.getSelectionRange());
- this.clearSelection();
- };
- this.removeToLineStart = function() {
- if (this.selection.isEmpty())
- this.selection.selectLineStart();
-
- this.session.remove(this.getSelectionRange());
- this.clearSelection();
- };
- this.removeToLineEnd = function() {
- if (this.selection.isEmpty())
- this.selection.selectLineEnd();
-
- var range = this.getSelectionRange();
- if (range.start.column == range.end.column && range.start.row == range.end.row) {
- range.end.column = 0;
- range.end.row++;
- }
-
- this.session.remove(range);
- this.clearSelection();
- };
- this.splitLine = function() {
- if (!this.selection.isEmpty()) {
- this.session.remove(this.getSelectionRange());
- this.clearSelection();
- }
-
- var cursor = this.getCursorPosition();
- this.insert("\n");
- this.moveCursorToPosition(cursor);
- };
- this.transposeLetters = function() {
- if (!this.selection.isEmpty()) {
- return;
- }
-
- var cursor = this.getCursorPosition();
- var column = cursor.column;
- if (column === 0)
- return;
-
- var line = this.session.getLine(cursor.row);
- var swap, range;
- if (column < line.length) {
- swap = line.charAt(column) + line.charAt(column-1);
- range = new Range(cursor.row, column-1, cursor.row, column+1);
- }
- else {
- swap = line.charAt(column-1) + line.charAt(column-2);
- range = new Range(cursor.row, column-2, cursor.row, column);
- }
- this.session.replace(range, swap);
- };
- this.toLowerCase = function() {
- var originalRange = this.getSelectionRange();
- if (this.selection.isEmpty()) {
- this.selection.selectWord();
- }
-
- var range = this.getSelectionRange();
- var text = this.session.getTextRange(range);
- this.session.replace(range, text.toLowerCase());
- this.selection.setSelectionRange(originalRange);
- };
- this.toUpperCase = function() {
- var originalRange = this.getSelectionRange();
- if (this.selection.isEmpty()) {
- this.selection.selectWord();
- }
-
- var range = this.getSelectionRange();
- var text = this.session.getTextRange(range);
- this.session.replace(range, text.toUpperCase());
- this.selection.setSelectionRange(originalRange);
- };
- this.indent = function() {
- var session = this.session;
- var range = this.getSelectionRange();
-
- if (range.start.row < range.end.row) {
- var rows = this.$getSelectedRows();
- session.indentRows(rows.first, rows.last, "\t");
- return;
- } else if (range.start.column < range.end.column) {
- var text = session.getTextRange(range);
- if (!/^\s+$/.test(text)) {
- var rows = this.$getSelectedRows();
- session.indentRows(rows.first, rows.last, "\t");
- return;
- }
- }
-
- var line = session.getLine(range.start.row);
- var position = range.start;
- var size = session.getTabSize();
- var column = session.documentToScreenColumn(position.row, position.column);
-
- if (this.session.getUseSoftTabs()) {
- var count = (size - column % size);
- var indentString = lang.stringRepeat(" ", count);
- } else {
- var count = column % size;
- while (line[range.start.column] == " " && count) {
- range.start.column--;
- count--;
- }
- this.selection.setSelectionRange(range);
- indentString = "\t";
- }
- return this.insert(indentString);
- };
- this.blockIndent = function() {
- var rows = this.$getSelectedRows();
- this.session.indentRows(rows.first, rows.last, "\t");
- };
- this.blockOutdent = function() {
- var selection = this.session.getSelection();
- this.session.outdentRows(selection.getRange());
- };
- this.sortLines = function() {
- var rows = this.$getSelectedRows();
- var session = this.session;
-
- var lines = [];
- for (i = rows.first; i <= rows.last; i++)
- lines.push(session.getLine(i));
-
- lines.sort(function(a, b) {
- if (a.toLowerCase() < b.toLowerCase()) return -1;
- if (a.toLowerCase() > b.toLowerCase()) return 1;
- return 0;
- });
-
- var deleteRange = new Range(0, 0, 0, 0);
- for (var i = rows.first; i <= rows.last; i++) {
- var line = session.getLine(i);
- deleteRange.start.row = i;
- deleteRange.end.row = i;
- deleteRange.end.column = line.length;
- session.replace(deleteRange, lines[i-rows.first]);
- }
- };
- this.toggleCommentLines = function() {
- var state = this.session.getState(this.getCursorPosition().row);
- var rows = this.$getSelectedRows();
- this.session.getMode().toggleCommentLines(state, this.session, rows.first, rows.last);
- };
-
- this.toggleBlockComment = function() {
- var cursor = this.getCursorPosition();
- var state = this.session.getState(cursor.row);
- var range = this.getSelectionRange();
- this.session.getMode().toggleBlockComment(state, this.session, range, cursor);
- };
- this.getNumberAt = function(row, column) {
- var _numberRx = /[\-]?[0-9]+(?:\.[0-9]+)?/g;
- _numberRx.lastIndex = 0;
-
- var s = this.session.getLine(row);
- while (_numberRx.lastIndex < column) {
- var m = _numberRx.exec(s);
- if(m.index <= column && m.index+m[0].length >= column){
- var number = {
- value: m[0],
- start: m.index,
- end: m.index+m[0].length
- };
- return number;
- }
- }
- return null;
- };
- this.modifyNumber = function(amount) {
- var row = this.selection.getCursor().row;
- var column = this.selection.getCursor().column;
- var charRange = new Range(row, column-1, row, column);
-
- var c = this.session.getTextRange(charRange);
- if (!isNaN(parseFloat(c)) && isFinite(c)) {
- var nr = this.getNumberAt(row, column);
- if (nr) {
- var fp = nr.value.indexOf(".") >= 0 ? nr.start + nr.value.indexOf(".") + 1 : nr.end;
- var decimals = nr.start + nr.value.length - fp;
-
- var t = parseFloat(nr.value);
- t *= Math.pow(10, decimals);
-
-
- if(fp !== nr.end && column < fp){
- amount *= Math.pow(10, nr.end - column - 1);
- } else {
- amount *= Math.pow(10, nr.end - column);
- }
-
- t += amount;
- t /= Math.pow(10, decimals);
- var nnr = t.toFixed(decimals);
- var replaceRange = new Range(row, nr.start, row, nr.end);
- this.session.replace(replaceRange, nnr);
- this.moveCursorTo(row, Math.max(nr.start +1, column + nnr.length - nr.value.length));
-
- }
- }
- };
- this.removeLines = function() {
- var rows = this.$getSelectedRows();
- this.session.removeFullLines(rows.first, rows.last);
- this.clearSelection();
- };
-
- this.duplicateSelection = function() {
- var sel = this.selection;
- var doc = this.session;
- var range = sel.getRange();
- var reverse = sel.isBackwards();
- if (range.isEmpty()) {
- var row = range.start.row;
- doc.duplicateLines(row, row);
- } else {
- var point = reverse ? range.start : range.end;
- var endPoint = doc.insert(point, doc.getTextRange(range), false);
- range.start = point;
- range.end = endPoint;
-
- sel.setSelectionRange(range, reverse);
- }
- };
- this.moveLinesDown = function() {
- this.$moveLines(1, false);
- };
- this.moveLinesUp = function() {
- this.$moveLines(-1, false);
- };
- this.moveText = function(range, toPosition, copy) {
- return this.session.moveText(range, toPosition, copy);
- };
- this.copyLinesUp = function() {
- this.$moveLines(-1, true);
- };
- this.copyLinesDown = function() {
- this.$moveLines(1, true);
- };
- this.$moveLines = function(dir, copy) {
- var rows, moved;
- var selection = this.selection;
- if (!selection.inMultiSelectMode || this.inVirtualSelectionMode) {
- var range = selection.toOrientedRange();
- rows = this.$getSelectedRows(range);
- moved = this.session.$moveLines(rows.first, rows.last, copy ? 0 : dir);
- if (copy && dir == -1) moved = 0;
- range.moveBy(moved, 0);
- selection.fromOrientedRange(range);
- } else {
- var ranges = selection.rangeList.ranges;
- selection.rangeList.detach(this.session);
- this.inVirtualSelectionMode = true;
-
- var diff = 0;
- var totalDiff = 0;
- var l = ranges.length;
- for (var i = 0; i < l; i++) {
- var rangeIndex = i;
- ranges[i].moveBy(diff, 0);
- rows = this.$getSelectedRows(ranges[i]);
- var first = rows.first;
- var last = rows.last;
- while (++i < l) {
- if (totalDiff) ranges[i].moveBy(totalDiff, 0);
- var subRows = this.$getSelectedRows(ranges[i]);
- if (copy && subRows.first != last)
- break;
- else if (!copy && subRows.first > last + 1)
- break;
- last = subRows.last;
- }
- i--;
- diff = this.session.$moveLines(first, last, copy ? 0 : dir);
- if (copy && dir == -1) rangeIndex = i + 1;
- while (rangeIndex <= i) {
- ranges[rangeIndex].moveBy(diff, 0);
- rangeIndex++;
- }
- if (!copy) diff = 0;
- totalDiff += diff;
- }
-
- selection.fromOrientedRange(selection.ranges[0]);
- selection.rangeList.attach(this.session);
- this.inVirtualSelectionMode = false;
- }
- };
- this.$getSelectedRows = function(range) {
- range = (range || this.getSelectionRange()).collapseRows();
-
- return {
- first: this.session.getRowFoldStart(range.start.row),
- last: this.session.getRowFoldEnd(range.end.row)
- };
- };
-
- this.onCompositionStart = function(text) {
- this.renderer.showComposition(this.getCursorPosition());
- };
-
- this.onCompositionUpdate = function(text) {
- this.renderer.setCompositionText(text);
- };
-
- this.onCompositionEnd = function() {
- this.renderer.hideComposition();
- };
- this.getFirstVisibleRow = function() {
- return this.renderer.getFirstVisibleRow();
- };
- this.getLastVisibleRow = function() {
- return this.renderer.getLastVisibleRow();
- };
- this.isRowVisible = function(row) {
- return (row >= this.getFirstVisibleRow() && row <= this.getLastVisibleRow());
- };
- this.isRowFullyVisible = function(row) {
- return (row >= this.renderer.getFirstFullyVisibleRow() && row <= this.renderer.getLastFullyVisibleRow());
- };
- this.$getVisibleRowCount = function() {
- return this.renderer.getScrollBottomRow() - this.renderer.getScrollTopRow() + 1;
- };
-
- this.$moveByPage = function(dir, select) {
- var renderer = this.renderer;
- var config = this.renderer.layerConfig;
- var rows = dir * Math.floor(config.height / config.lineHeight);
-
- this.$blockScrolling++;
- if (select === true) {
- this.selection.$moveSelection(function(){
- this.moveCursorBy(rows, 0);
- });
- } else if (select === false) {
- this.selection.moveCursorBy(rows, 0);
- this.selection.clearSelection();
- }
- this.$blockScrolling--;
-
- var scrollTop = renderer.scrollTop;
-
- renderer.scrollBy(0, rows * config.lineHeight);
- if (select != null)
- renderer.scrollCursorIntoView(null, 0.5);
-
- renderer.animateScrolling(scrollTop);
- };
- this.selectPageDown = function() {
- this.$moveByPage(1, true);
- };
- this.selectPageUp = function() {
- this.$moveByPage(-1, true);
- };
- this.gotoPageDown = function() {
- this.$moveByPage(1, false);
- };
- this.gotoPageUp = function() {
- this.$moveByPage(-1, false);
- };
- this.scrollPageDown = function() {
- this.$moveByPage(1);
- };
- this.scrollPageUp = function() {
- this.$moveByPage(-1);
- };
- this.scrollToRow = function(row) {
- this.renderer.scrollToRow(row);
- };
- this.scrollToLine = function(line, center, animate, callback) {
- this.renderer.scrollToLine(line, center, animate, callback);
- };
- this.centerSelection = function() {
- var range = this.getSelectionRange();
- var pos = {
- row: Math.floor(range.start.row + (range.end.row - range.start.row) / 2),
- column: Math.floor(range.start.column + (range.end.column - range.start.column) / 2)
- };
- this.renderer.alignCursor(pos, 0.5);
- };
- this.getCursorPosition = function() {
- return this.selection.getCursor();
- };
- this.getCursorPositionScreen = function() {
- return this.session.documentToScreenPosition(this.getCursorPosition());
- };
- this.getSelectionRange = function() {
- return this.selection.getRange();
- };
- this.selectAll = function() {
- this.$blockScrolling += 1;
- this.selection.selectAll();
- this.$blockScrolling -= 1;
- };
- this.clearSelection = function() {
- this.selection.clearSelection();
- };
- this.moveCursorTo = function(row, column) {
- this.selection.moveCursorTo(row, column);
- };
- this.moveCursorToPosition = function(pos) {
- this.selection.moveCursorToPosition(pos);
- };
- this.jumpToMatching = function(select, expand) {
- var cursor = this.getCursorPosition();
- var iterator = new TokenIterator(this.session, cursor.row, cursor.column);
- var prevToken = iterator.getCurrentToken();
- var token = prevToken || iterator.stepForward();
-
- if (!token) return;
- var matchType;
- var found = false;
- var depth = {};
- var i = cursor.column - token.start;
- var bracketType;
- var brackets = {
- ")": "(",
- "(": "(",
- "]": "[",
- "[": "[",
- "{": "{",
- "}": "{"
- };
-
- do {
- if (token.value.match(/[{}()\[\]]/g)) {
- for (; i < token.value.length && !found; i++) {
- if (!brackets[token.value[i]]) {
- continue;
- }
-
- bracketType = brackets[token.value[i]] + '.' + token.type.replace("rparen", "lparen");
-
- if (isNaN(depth[bracketType])) {
- depth[bracketType] = 0;
- }
-
- switch (token.value[i]) {
- case '(':
- case '[':
- case '{':
- depth[bracketType]++;
- break;
- case ')':
- case ']':
- case '}':
- depth[bracketType]--;
-
- if (depth[bracketType] === -1) {
- matchType = 'bracket';
- found = true;
- }
- break;
- }
- }
- }
- else if (token && token.type.indexOf('tag-name') !== -1) {
- if (isNaN(depth[token.value])) {
- depth[token.value] = 0;
- }
-
- if (prevToken.value === '<') {
- depth[token.value]++;
- }
- else if (prevToken.value === '') {
- depth[token.value]--;
- }
-
- if (depth[token.value] === -1) {
- matchType = 'tag';
- found = true;
- }
- }
-
- if (!found) {
- prevToken = token;
- token = iterator.stepForward();
- i = 0;
- }
- } while (token && !found);
- if (!matchType)
- return;
-
- var range, pos;
- if (matchType === 'bracket') {
- range = this.session.getBracketRange(cursor);
- if (!range) {
- range = new Range(
- iterator.getCurrentTokenRow(),
- iterator.getCurrentTokenColumn() + i - 1,
- iterator.getCurrentTokenRow(),
- iterator.getCurrentTokenColumn() + i - 1
- );
- pos = range.start;
- if (expand || pos.row === cursor.row && Math.abs(pos.column - cursor.column) < 2)
- range = this.session.getBracketRange(pos);
- }
- }
- else if (matchType === 'tag') {
- if (token && token.type.indexOf('tag-name') !== -1)
- var tag = token.value;
- else
- return;
-
- range = new Range(
- iterator.getCurrentTokenRow(),
- iterator.getCurrentTokenColumn() - 2,
- iterator.getCurrentTokenRow(),
- iterator.getCurrentTokenColumn() - 2
- );
- if (range.compare(cursor.row, cursor.column) === 0) {
- found = false;
- do {
- token = prevToken;
- prevToken = iterator.stepBackward();
-
- if (prevToken) {
- if (prevToken.type.indexOf('tag-close') !== -1) {
- range.setEnd(iterator.getCurrentTokenRow(), iterator.getCurrentTokenColumn() + 1);
- }
-
- if (token.value === tag && token.type.indexOf('tag-name') !== -1) {
- if (prevToken.value === '<') {
- depth[tag]++;
- }
- else if (prevToken.value === '') {
- depth[tag]--;
- }
-
- if (depth[tag] === 0)
- found = true;
- }
- }
- } while (prevToken && !found);
- }
- if (token && token.type.indexOf('tag-name')) {
- pos = range.start;
- if (pos.row == cursor.row && Math.abs(pos.column - cursor.column) < 2)
- pos = range.end;
- }
- }
-
- pos = range && range.cursor || pos;
- if (pos) {
- if (select) {
- if (range && expand) {
- this.selection.setRange(range);
- } else if (range && range.isEqual(this.getSelectionRange())) {
- this.clearSelection();
- } else {
- this.selection.selectTo(pos.row, pos.column);
- }
- } else {
- this.selection.moveTo(pos.row, pos.column);
- }
- }
- };
- this.gotoLine = function(lineNumber, column, animate) {
- this.selection.clearSelection();
- this.session.unfold({row: lineNumber - 1, column: column || 0});
-
- this.$blockScrolling += 1;
- this.exitMultiSelectMode && this.exitMultiSelectMode();
- this.moveCursorTo(lineNumber - 1, column || 0);
- this.$blockScrolling -= 1;
-
- if (!this.isRowFullyVisible(lineNumber - 1))
- this.scrollToLine(lineNumber - 1, true, animate);
- };
- this.navigateTo = function(row, column) {
- this.selection.moveTo(row, column);
- };
- this.navigateUp = function(times) {
- if (this.selection.isMultiLine() && !this.selection.isBackwards()) {
- var selectionStart = this.selection.anchor.getPosition();
- return this.moveCursorToPosition(selectionStart);
- }
- this.selection.clearSelection();
- this.selection.moveCursorBy(-times || -1, 0);
- };
- this.navigateDown = function(times) {
- if (this.selection.isMultiLine() && this.selection.isBackwards()) {
- var selectionEnd = this.selection.anchor.getPosition();
- return this.moveCursorToPosition(selectionEnd);
- }
- this.selection.clearSelection();
- this.selection.moveCursorBy(times || 1, 0);
- };
- this.navigateLeft = function(times) {
- if (!this.selection.isEmpty()) {
- var selectionStart = this.getSelectionRange().start;
- this.moveCursorToPosition(selectionStart);
- }
- else {
- times = times || 1;
- while (times--) {
- this.selection.moveCursorLeft();
- }
- }
- this.clearSelection();
- };
- this.navigateRight = function(times) {
- if (!this.selection.isEmpty()) {
- var selectionEnd = this.getSelectionRange().end;
- this.moveCursorToPosition(selectionEnd);
- }
- else {
- times = times || 1;
- while (times--) {
- this.selection.moveCursorRight();
- }
- }
- this.clearSelection();
- };
- this.navigateLineStart = function() {
- this.selection.moveCursorLineStart();
- this.clearSelection();
- };
- this.navigateLineEnd = function() {
- this.selection.moveCursorLineEnd();
- this.clearSelection();
- };
- this.navigateFileEnd = function() {
- this.selection.moveCursorFileEnd();
- this.clearSelection();
- };
- this.navigateFileStart = function() {
- this.selection.moveCursorFileStart();
- this.clearSelection();
- };
- this.navigateWordRight = function() {
- this.selection.moveCursorWordRight();
- this.clearSelection();
- };
- this.navigateWordLeft = function() {
- this.selection.moveCursorWordLeft();
- this.clearSelection();
- };
- this.replace = function(replacement, options) {
- if (options)
- this.$search.set(options);
-
- var range = this.$search.find(this.session);
- var replaced = 0;
- if (!range)
- return replaced;
-
- if (this.$tryReplace(range, replacement)) {
- replaced = 1;
- }
- if (range !== null) {
- this.selection.setSelectionRange(range);
- this.renderer.scrollSelectionIntoView(range.start, range.end);
- }
-
- return replaced;
- };
- this.replaceAll = function(replacement, options) {
- if (options) {
- this.$search.set(options);
- }
-
- var ranges = this.$search.findAll(this.session);
- var replaced = 0;
- if (!ranges.length)
- return replaced;
-
- this.$blockScrolling += 1;
-
- var selection = this.getSelectionRange();
- this.selection.moveTo(0, 0);
-
- for (var i = ranges.length - 1; i >= 0; --i) {
- if(this.$tryReplace(ranges[i], replacement)) {
- replaced++;
- }
- }
-
- this.selection.setSelectionRange(selection);
- this.$blockScrolling -= 1;
-
- return replaced;
- };
-
- this.$tryReplace = function(range, replacement) {
- var input = this.session.getTextRange(range);
- replacement = this.$search.replace(input, replacement);
- if (replacement !== null) {
- range.end = this.session.replace(range, replacement);
- return range;
- } else {
- return null;
- }
- };
- this.getLastSearchOptions = function() {
- return this.$search.getOptions();
- };
- this.find = function(needle, options, animate) {
- if (!options)
- options = {};
-
- if (typeof needle == "string" || needle instanceof RegExp)
- options.needle = needle;
- else if (typeof needle == "object")
- oop.mixin(options, needle);
-
- var range = this.selection.getRange();
- if (options.needle == null) {
- needle = this.session.getTextRange(range)
- || this.$search.$options.needle;
- if (!needle) {
- range = this.session.getWordRange(range.start.row, range.start.column);
- needle = this.session.getTextRange(range);
- }
- this.$search.set({needle: needle});
- }
-
- this.$search.set(options);
- if (!options.start)
- this.$search.set({start: range});
-
- var newRange = this.$search.find(this.session);
- if (options.preventScroll)
- return newRange;
- if (newRange) {
- this.revealRange(newRange, animate);
- return newRange;
- }
- if (options.backwards)
- range.start = range.end;
- else
- range.end = range.start;
- this.selection.setRange(range);
- };
- this.findNext = function(options, animate) {
- this.find({skipCurrent: true, backwards: false}, options, animate);
- };
- this.findPrevious = function(options, animate) {
- this.find(options, {skipCurrent: true, backwards: true}, animate);
- };
-
- this.revealRange = function(range, animate) {
- this.$blockScrolling += 1;
- this.session.unfold(range);
- this.selection.setSelectionRange(range);
- this.$blockScrolling -= 1;
-
- var scrollTop = this.renderer.scrollTop;
- this.renderer.scrollSelectionIntoView(range.start, range.end, 0.5);
- if (animate !== false)
- this.renderer.animateScrolling(scrollTop);
- };
- this.undo = function() {
- this.$blockScrolling++;
- this.session.getUndoManager().undo();
- this.$blockScrolling--;
- this.renderer.scrollCursorIntoView(null, 0.5);
- };
- this.redo = function() {
- this.$blockScrolling++;
- this.session.getUndoManager().redo();
- this.$blockScrolling--;
- this.renderer.scrollCursorIntoView(null, 0.5);
- };
- this.destroy = function() {
- this.renderer.destroy();
- this._signal("destroy", this);
- if (this.session) {
- this.session.destroy();
- }
- };
- this.setAutoScrollEditorIntoView = function(enable) {
- if (!enable)
- return;
- var rect;
- var self = this;
- var shouldScroll = false;
- if (!this.$scrollAnchor)
- this.$scrollAnchor = document.createElement("div");
- var scrollAnchor = this.$scrollAnchor;
- scrollAnchor.style.cssText = "position:absolute";
- this.container.insertBefore(scrollAnchor, this.container.firstChild);
- var onChangeSelection = this.on("changeSelection", function() {
- shouldScroll = true;
- });
- var onBeforeRender = this.renderer.on("beforeRender", function() {
- if (shouldScroll)
- rect = self.renderer.container.getBoundingClientRect();
- });
- var onAfterRender = this.renderer.on("afterRender", function() {
- if (shouldScroll && rect && (self.isFocused()
- || self.searchBox && self.searchBox.isFocused())
- ) {
- var renderer = self.renderer;
- var pos = renderer.$cursorLayer.$pixelPos;
- var config = renderer.layerConfig;
- var top = pos.top - config.offset;
- if (pos.top >= 0 && top + rect.top < 0) {
- shouldScroll = true;
- } else if (pos.top < config.height &&
- pos.top + rect.top + config.lineHeight > window.innerHeight) {
- shouldScroll = false;
- } else {
- shouldScroll = null;
- }
- if (shouldScroll != null) {
- scrollAnchor.style.top = top + "px";
- scrollAnchor.style.left = pos.left + "px";
- scrollAnchor.style.height = config.lineHeight + "px";
- scrollAnchor.scrollIntoView(shouldScroll);
- }
- shouldScroll = rect = null;
- }
- });
- this.setAutoScrollEditorIntoView = function(enable) {
- if (enable)
- return;
- delete this.setAutoScrollEditorIntoView;
- this.off("changeSelection", onChangeSelection);
- this.renderer.off("afterRender", onAfterRender);
- this.renderer.off("beforeRender", onBeforeRender);
- };
- };
-
-
- this.$resetCursorStyle = function() {
- var style = this.$cursorStyle || "ace";
- var cursorLayer = this.renderer.$cursorLayer;
- if (!cursorLayer)
- return;
- cursorLayer.setSmoothBlinking(/smooth/.test(style));
- cursorLayer.isBlinking = !this.$readOnly && style != "wide";
- dom.setCssClass(cursorLayer.element, "ace_slim-cursors", /slim/.test(style));
- };
-
-}).call(Editor.prototype);
-
-
-
-config.defineOptions(Editor.prototype, "editor", {
- selectionStyle: {
- set: function(style) {
- this.onSelectionChange();
- this._signal("changeSelectionStyle", {data: style});
- },
- initialValue: "line"
- },
- highlightActiveLine: {
- set: function() {this.$updateHighlightActiveLine();},
- initialValue: true
- },
- highlightSelectedWord: {
- set: function(shouldHighlight) {this.$onSelectionChange();},
- initialValue: true
- },
- readOnly: {
- set: function(readOnly) {
- this.$resetCursorStyle();
- },
- initialValue: false
- },
- cursorStyle: {
- set: function(val) { this.$resetCursorStyle(); },
- values: ["ace", "slim", "smooth", "wide"],
- initialValue: "ace"
- },
- mergeUndoDeltas: {
- values: [false, true, "always"],
- initialValue: true
- },
- behavioursEnabled: {initialValue: true},
- wrapBehavioursEnabled: {initialValue: true},
- autoScrollEditorIntoView: {
- set: function(val) {this.setAutoScrollEditorIntoView(val)}
- },
- keyboardHandler: {
- set: function(val) { this.setKeyboardHandler(val); },
- get: function() { return this.keybindingId; },
- handlesSet: true
- },
-
- hScrollBarAlwaysVisible: "renderer",
- vScrollBarAlwaysVisible: "renderer",
- highlightGutterLine: "renderer",
- animatedScroll: "renderer",
- showInvisibles: "renderer",
- showPrintMargin: "renderer",
- printMarginColumn: "renderer",
- printMargin: "renderer",
- fadeFoldWidgets: "renderer",
- showFoldWidgets: "renderer",
- showLineNumbers: "renderer",
- showGutter: "renderer",
- displayIndentGuides: "renderer",
- fontSize: "renderer",
- fontFamily: "renderer",
- maxLines: "renderer",
- minLines: "renderer",
- scrollPastEnd: "renderer",
- fixedWidthGutter: "renderer",
- theme: "renderer",
-
- scrollSpeed: "$mouseHandler",
- dragDelay: "$mouseHandler",
- dragEnabled: "$mouseHandler",
- focusTimout: "$mouseHandler",
- tooltipFollowsMouse: "$mouseHandler",
-
- firstLineNumber: "session",
- overwrite: "session",
- newLineMode: "session",
- useWorker: "session",
- useSoftTabs: "session",
- tabSize: "session",
- wrap: "session",
- indentedSoftWrap: "session",
- foldStyle: "session",
- mode: "session"
-});
-
-exports.Editor = Editor;
-});
-
-ace.define("ace/undomanager",["require","exports","module"], function(require, exports, module) {
-"use strict";
-var UndoManager = function() {
- this.reset();
-};
-
-(function() {
- this.execute = function(options) {
- var deltaSets = options.args[0];
- this.$doc = options.args[1];
- if (options.merge && this.hasUndo()){
- this.dirtyCounter--;
- deltaSets = this.$undoStack.pop().concat(deltaSets);
- }
- this.$undoStack.push(deltaSets);
- this.$redoStack = [];
- if (this.dirtyCounter < 0) {
- this.dirtyCounter = NaN;
- }
- this.dirtyCounter++;
- };
- this.undo = function(dontSelect) {
- var deltaSets = this.$undoStack.pop();
- var undoSelectionRange = null;
- if (deltaSets) {
- undoSelectionRange = this.$doc.undoChanges(deltaSets, dontSelect);
- this.$redoStack.push(deltaSets);
- this.dirtyCounter--;
- }
-
- return undoSelectionRange;
- };
- this.redo = function(dontSelect) {
- var deltaSets = this.$redoStack.pop();
- var redoSelectionRange = null;
- if (deltaSets) {
- redoSelectionRange =
- this.$doc.redoChanges(this.$deserializeDeltas(deltaSets), dontSelect);
- this.$undoStack.push(deltaSets);
- this.dirtyCounter++;
- }
- return redoSelectionRange;
- };
- this.reset = function() {
- this.$undoStack = [];
- this.$redoStack = [];
- this.dirtyCounter = 0;
- };
- this.hasUndo = function() {
- return this.$undoStack.length > 0;
- };
- this.hasRedo = function() {
- return this.$redoStack.length > 0;
- };
- this.markClean = function() {
- this.dirtyCounter = 0;
- };
- this.isClean = function() {
- return this.dirtyCounter === 0;
- };
- this.$serializeDeltas = function(deltaSets) {
- return cloneDeltaSetsObj(deltaSets, $serializeDelta);
- };
- this.$deserializeDeltas = function(deltaSets) {
- return cloneDeltaSetsObj(deltaSets, $deserializeDelta);
- };
-
- function $serializeDelta(delta){
- return {
- action: delta.action,
- start: delta.start,
- end: delta.end,
- lines: delta.lines.length == 1 ? null : delta.lines,
- text: delta.lines.length == 1 ? delta.lines[0] : null
- };
- }
-
- function $deserializeDelta(delta) {
- return {
- action: delta.action,
- start: delta.start,
- end: delta.end,
- lines: delta.lines || [delta.text]
- };
- }
-
- function cloneDeltaSetsObj(deltaSets_old, fnGetModifiedDelta) {
- var deltaSets_new = new Array(deltaSets_old.length);
- for (var i = 0; i < deltaSets_old.length; i++) {
- var deltaSet_old = deltaSets_old[i];
- var deltaSet_new = { group: deltaSet_old.group, deltas: new Array(deltaSet_old.length)};
-
- for (var j = 0; j < deltaSet_old.deltas.length; j++) {
- var delta_old = deltaSet_old.deltas[j];
- deltaSet_new.deltas[j] = fnGetModifiedDelta(delta_old);
- }
-
- deltaSets_new[i] = deltaSet_new;
- }
- return deltaSets_new;
- }
-
-}).call(UndoManager.prototype);
-
-exports.UndoManager = UndoManager;
-});
-
-ace.define("ace/layer/gutter",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter"], function(require, exports, module) {
-"use strict";
-
-var dom = require("../lib/dom");
-var oop = require("../lib/oop");
-var lang = require("../lib/lang");
-var EventEmitter = require("../lib/event_emitter").EventEmitter;
-
-var Gutter = function(parentEl) {
- this.element = dom.createElement("div");
- this.element.className = "ace_layer ace_gutter-layer";
- parentEl.appendChild(this.element);
- this.setShowFoldWidgets(this.$showFoldWidgets);
-
- this.gutterWidth = 0;
-
- this.$annotations = [];
- this.$updateAnnotations = this.$updateAnnotations.bind(this);
-
- this.$cells = [];
-};
-
-(function() {
-
- oop.implement(this, EventEmitter);
-
- this.setSession = function(session) {
- if (this.session)
- this.session.removeEventListener("change", this.$updateAnnotations);
- this.session = session;
- if (session)
- session.on("change", this.$updateAnnotations);
- };
-
- this.addGutterDecoration = function(row, className){
- if (window.console)
- console.warn && console.warn("deprecated use session.addGutterDecoration");
- this.session.addGutterDecoration(row, className);
- };
-
- this.removeGutterDecoration = function(row, className){
- if (window.console)
- console.warn && console.warn("deprecated use session.removeGutterDecoration");
- this.session.removeGutterDecoration(row, className);
- };
-
- this.setAnnotations = function(annotations) {
- this.$annotations = [];
- for (var i = 0; i < annotations.length; i++) {
- var annotation = annotations[i];
- var row = annotation.row;
- var rowInfo = this.$annotations[row];
- if (!rowInfo)
- rowInfo = this.$annotations[row] = {text: []};
-
- var annoText = annotation.text;
- annoText = annoText ? lang.escapeHTML(annoText) : annotation.html || "";
-
- if (rowInfo.text.indexOf(annoText) === -1)
- rowInfo.text.push(annoText);
-
- var type = annotation.type;
- if (type == "error")
- rowInfo.className = " ace_error";
- else if (type == "warning" && rowInfo.className != " ace_error")
- rowInfo.className = " ace_warning";
- else if (type == "info" && (!rowInfo.className))
- rowInfo.className = " ace_info";
- }
- };
-
- this.$updateAnnotations = function (delta) {
- if (!this.$annotations.length)
- return;
- var firstRow = delta.start.row;
- var len = delta.end.row - firstRow;
- if (len === 0) {
- } else if (delta.action == 'remove') {
- this.$annotations.splice(firstRow, len + 1, null);
- } else {
- var args = new Array(len + 1);
- args.unshift(firstRow, 1);
- this.$annotations.splice.apply(this.$annotations, args);
- }
- };
-
- this.update = function(config) {
- var session = this.session;
- var firstRow = config.firstRow;
- var lastRow = Math.min(config.lastRow + config.gutterOffset, // needed to compensate for hor scollbar
- session.getLength() - 1);
- var fold = session.getNextFoldLine(firstRow);
- var foldStart = fold ? fold.start.row : Infinity;
- var foldWidgets = this.$showFoldWidgets && session.foldWidgets;
- var breakpoints = session.$breakpoints;
- var decorations = session.$decorations;
- var firstLineNumber = session.$firstLineNumber;
- var lastLineNumber = 0;
-
- var gutterRenderer = session.gutterRenderer || this.$renderer;
-
- var cell = null;
- var index = -1;
- var row = firstRow;
- while (true) {
- if (row > foldStart) {
- row = fold.end.row + 1;
- fold = session.getNextFoldLine(row, fold);
- foldStart = fold ? fold.start.row : Infinity;
- }
- if (row > lastRow) {
- while (this.$cells.length > index + 1) {
- cell = this.$cells.pop();
- this.element.removeChild(cell.element);
- }
- break;
- }
-
- cell = this.$cells[++index];
- if (!cell) {
- cell = {element: null, textNode: null, foldWidget: null};
- cell.element = dom.createElement("div");
- cell.textNode = document.createTextNode('');
- cell.element.appendChild(cell.textNode);
- this.element.appendChild(cell.element);
- this.$cells[index] = cell;
- }
-
- var className = "ace_gutter-cell ";
- if (breakpoints[row])
- className += breakpoints[row];
- if (decorations[row])
- className += decorations[row];
- if (this.$annotations[row])
- className += this.$annotations[row].className;
- if (cell.element.className != className)
- cell.element.className = className;
-
- var height = session.getRowLength(row) * config.lineHeight + "px";
- if (height != cell.element.style.height)
- cell.element.style.height = height;
-
- if (foldWidgets) {
- var c = foldWidgets[row];
- if (c == null)
- c = foldWidgets[row] = session.getFoldWidget(row);
- }
-
- if (c) {
- if (!cell.foldWidget) {
- cell.foldWidget = dom.createElement("span");
- cell.element.appendChild(cell.foldWidget);
- }
- var className = "ace_fold-widget ace_" + c;
- if (c == "start" && row == foldStart && row < fold.end.row)
- className += " ace_closed";
- else
- className += " ace_open";
- if (cell.foldWidget.className != className)
- cell.foldWidget.className = className;
-
- var height = config.lineHeight + "px";
- if (cell.foldWidget.style.height != height)
- cell.foldWidget.style.height = height;
- } else {
- if (cell.foldWidget) {
- cell.element.removeChild(cell.foldWidget);
- cell.foldWidget = null;
- }
- }
-
- var text = lastLineNumber = gutterRenderer
- ? gutterRenderer.getText(session, row)
- : row + firstLineNumber;
- if (text != cell.textNode.data)
- cell.textNode.data = text;
-
- row++;
- }
-
- this.element.style.height = config.minHeight + "px";
-
- if (this.$fixedWidth || session.$useWrapMode)
- lastLineNumber = session.getLength() + firstLineNumber;
-
- var gutterWidth = gutterRenderer
- ? gutterRenderer.getWidth(session, lastLineNumber, config)
- : lastLineNumber.toString().length * config.characterWidth;
-
- var padding = this.$padding || this.$computePadding();
- gutterWidth += padding.left + padding.right;
- if (gutterWidth !== this.gutterWidth && !isNaN(gutterWidth)) {
- this.gutterWidth = gutterWidth;
- this.element.style.width = Math.ceil(this.gutterWidth) + "px";
- this._emit("changeGutterWidth", gutterWidth);
- }
- };
-
- this.$fixedWidth = false;
-
- this.$showLineNumbers = true;
- this.$renderer = "";
- this.setShowLineNumbers = function(show) {
- this.$renderer = !show && {
- getWidth: function() {return ""},
- getText: function() {return ""}
- };
- };
-
- this.getShowLineNumbers = function() {
- return this.$showLineNumbers;
- };
-
- this.$showFoldWidgets = true;
- this.setShowFoldWidgets = function(show) {
- if (show)
- dom.addCssClass(this.element, "ace_folding-enabled");
- else
- dom.removeCssClass(this.element, "ace_folding-enabled");
-
- this.$showFoldWidgets = show;
- this.$padding = null;
- };
-
- this.getShowFoldWidgets = function() {
- return this.$showFoldWidgets;
- };
-
- this.$computePadding = function() {
- if (!this.element.firstChild)
- return {left: 0, right: 0};
- var style = dom.computedStyle(this.element.firstChild);
- this.$padding = {};
- this.$padding.left = parseInt(style.paddingLeft) + 1 || 0;
- this.$padding.right = parseInt(style.paddingRight) || 0;
- return this.$padding;
- };
-
- this.getRegion = function(point) {
- var padding = this.$padding || this.$computePadding();
- var rect = this.element.getBoundingClientRect();
- if (point.x < padding.left + rect.left)
- return "markers";
- if (this.$showFoldWidgets && point.x > rect.right - padding.right)
- return "foldWidgets";
- };
-
-}).call(Gutter.prototype);
-
-exports.Gutter = Gutter;
-
-});
-
-ace.define("ace/layer/marker",["require","exports","module","ace/range","ace/lib/dom"], function(require, exports, module) {
-"use strict";
-
-var Range = require("../range").Range;
-var dom = require("../lib/dom");
-
-var Marker = function(parentEl) {
- this.element = dom.createElement("div");
- this.element.className = "ace_layer ace_marker-layer";
- parentEl.appendChild(this.element);
-};
-
-(function() {
-
- this.$padding = 0;
-
- this.setPadding = function(padding) {
- this.$padding = padding;
- };
- this.setSession = function(session) {
- this.session = session;
- };
-
- this.setMarkers = function(markers) {
- this.markers = markers;
- };
-
- this.update = function(config) {
- var config = config || this.config;
- if (!config)
- return;
-
- this.config = config;
-
-
- var html = [];
- for (var key in this.markers) {
- var marker = this.markers[key];
-
- if (!marker.range) {
- marker.update(html, this, this.session, config);
- continue;
- }
-
- var range = marker.range.clipRows(config.firstRow, config.lastRow);
- if (range.isEmpty()) continue;
-
- range = range.toScreenRange(this.session);
- if (marker.renderer) {
- var top = this.$getTop(range.start.row, config);
- var left = this.$padding + range.start.column * config.characterWidth;
- marker.renderer(html, range, left, top, config);
- } else if (marker.type == "fullLine") {
- this.drawFullLineMarker(html, range, marker.clazz, config);
- } else if (marker.type == "screenLine") {
- this.drawScreenLineMarker(html, range, marker.clazz, config);
- } else if (range.isMultiLine()) {
- if (marker.type == "text")
- this.drawTextMarker(html, range, marker.clazz, config);
- else
- this.drawMultiLineMarker(html, range, marker.clazz, config);
- } else {
- this.drawSingleLineMarker(html, range, marker.clazz + " ace_start" + " ace_br15", config);
- }
- }
- this.element.innerHTML = html.join("");
- };
-
- this.$getTop = function(row, layerConfig) {
- return (row - layerConfig.firstRowScreen) * layerConfig.lineHeight;
- };
-
- function getBorderClass(tl, tr, br, bl) {
- return (tl ? 1 : 0) | (tr ? 2 : 0) | (br ? 4 : 0) | (bl ? 8 : 0);
- }
- this.drawTextMarker = function(stringBuilder, range, clazz, layerConfig, extraStyle) {
- var session = this.session;
- var start = range.start.row;
- var end = range.end.row;
- var row = start;
- var prev = 0;
- var curr = 0;
- var next = session.getScreenLastRowColumn(row);
- var lineRange = new Range(row, range.start.column, row, curr);
- for (; row <= end; row++) {
- lineRange.start.row = lineRange.end.row = row;
- lineRange.start.column = row == start ? range.start.column : session.getRowWrapIndent(row);
- lineRange.end.column = next;
- prev = curr;
- curr = next;
- next = row + 1 < end ? session.getScreenLastRowColumn(row + 1) : row == end ? 0 : range.end.column;
- this.drawSingleLineMarker(stringBuilder, lineRange,
- clazz + (row == start ? " ace_start" : "") + " ace_br"
- + getBorderClass(row == start || row == start + 1 && range.start.column, prev < curr, curr > next, row == end),
- layerConfig, row == end ? 0 : 1, extraStyle);
- }
- };
- this.drawMultiLineMarker = function(stringBuilder, range, clazz, config, extraStyle) {
- var padding = this.$padding;
- var height = config.lineHeight;
- var top = this.$getTop(range.start.row, config);
- var left = padding + range.start.column * config.characterWidth;
- extraStyle = extraStyle || "";
-
- stringBuilder.push(
- ""
- );
- top = this.$getTop(range.end.row, config);
- var width = range.end.column * config.characterWidth;
-
- stringBuilder.push(
- ""
- );
- height = (range.end.row - range.start.row - 1) * config.lineHeight;
- if (height <= 0)
- return;
- top = this.$getTop(range.start.row + 1, config);
-
- var radiusClass = (range.start.column ? 1 : 0) | (range.end.column ? 0 : 8);
-
- stringBuilder.push(
- ""
- );
- };
- this.drawSingleLineMarker = function(stringBuilder, range, clazz, config, extraLength, extraStyle) {
- var height = config.lineHeight;
- var width = (range.end.column + (extraLength || 0) - range.start.column) * config.characterWidth;
-
- var top = this.$getTop(range.start.row, config);
- var left = this.$padding + range.start.column * config.characterWidth;
-
- stringBuilder.push(
- ""
- );
- };
-
- this.drawFullLineMarker = function(stringBuilder, range, clazz, config, extraStyle) {
- var top = this.$getTop(range.start.row, config);
- var height = config.lineHeight;
- if (range.start.row != range.end.row)
- height += this.$getTop(range.end.row, config) - top;
-
- stringBuilder.push(
- ""
- );
- };
-
- this.drawScreenLineMarker = function(stringBuilder, range, clazz, config, extraStyle) {
- var top = this.$getTop(range.start.row, config);
- var height = config.lineHeight;
-
- stringBuilder.push(
- ""
- );
- };
-
-}).call(Marker.prototype);
-
-exports.Marker = Marker;
-
-});
-
-ace.define("ace/layer/text",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"], function(require, exports, module) {
-"use strict";
-
-var oop = require("../lib/oop");
-var dom = require("../lib/dom");
-var lang = require("../lib/lang");
-var useragent = require("../lib/useragent");
-var EventEmitter = require("../lib/event_emitter").EventEmitter;
-
-var Text = function(parentEl) {
- this.element = dom.createElement("div");
- this.element.className = "ace_layer ace_text-layer";
- parentEl.appendChild(this.element);
- this.$updateEolChar = this.$updateEolChar.bind(this);
-};
-
-(function() {
-
- oop.implement(this, EventEmitter);
-
- this.EOF_CHAR = "\xB6";
- this.EOL_CHAR_LF = "\xAC";
- this.EOL_CHAR_CRLF = "\xa4";
- this.EOL_CHAR = this.EOL_CHAR_LF;
- this.TAB_CHAR = "\u2014"; //"\u21E5";
- this.SPACE_CHAR = "\xB7";
- this.$padding = 0;
-
- this.$updateEolChar = function() {
- var EOL_CHAR = this.session.doc.getNewLineCharacter() == "\n"
- ? this.EOL_CHAR_LF
- : this.EOL_CHAR_CRLF;
- if (this.EOL_CHAR != EOL_CHAR) {
- this.EOL_CHAR = EOL_CHAR;
- return true;
- }
- }
-
- this.setPadding = function(padding) {
- this.$padding = padding;
- this.element.style.padding = "0 " + padding + "px";
- };
-
- this.getLineHeight = function() {
- return this.$fontMetrics.$characterSize.height || 0;
- };
-
- this.getCharacterWidth = function() {
- return this.$fontMetrics.$characterSize.width || 0;
- };
-
- this.$setFontMetrics = function(measure) {
- this.$fontMetrics = measure;
- this.$fontMetrics.on("changeCharacterSize", function(e) {
- this._signal("changeCharacterSize", e);
- }.bind(this));
- this.$pollSizeChanges();
- }
-
- this.checkForSizeChanges = function() {
- this.$fontMetrics.checkForSizeChanges();
- };
- this.$pollSizeChanges = function() {
- return this.$pollSizeChangesTimer = this.$fontMetrics.$pollSizeChanges();
- };
- this.setSession = function(session) {
- this.session = session;
- if (session)
- this.$computeTabString();
- };
-
- this.showInvisibles = false;
- this.setShowInvisibles = function(showInvisibles) {
- if (this.showInvisibles == showInvisibles)
- return false;
-
- this.showInvisibles = showInvisibles;
- this.$computeTabString();
- return true;
- };
-
- this.displayIndentGuides = true;
- this.setDisplayIndentGuides = function(display) {
- if (this.displayIndentGuides == display)
- return false;
-
- this.displayIndentGuides = display;
- this.$computeTabString();
- return true;
- };
-
- this.$tabStrings = [];
- this.onChangeTabSize =
- this.$computeTabString = function() {
- var tabSize = this.session.getTabSize();
- this.tabSize = tabSize;
- var tabStr = this.$tabStrings = [0];
- for (var i = 1; i < tabSize + 1; i++) {
- if (this.showInvisibles) {
- tabStr.push(""
- + lang.stringRepeat(this.TAB_CHAR, i)
- + "");
- } else {
- tabStr.push(lang.stringRepeat(" ", i));
- }
- }
- if (this.displayIndentGuides) {
- this.$indentGuideRe = /\s\S| \t|\t |\s$/;
- var className = "ace_indent-guide";
- var spaceClass = "";
- var tabClass = "";
- if (this.showInvisibles) {
- className += " ace_invisible";
- spaceClass = " ace_invisible_space";
- tabClass = " ace_invisible_tab";
- var spaceContent = lang.stringRepeat(this.SPACE_CHAR, this.tabSize);
- var tabContent = lang.stringRepeat(this.TAB_CHAR, this.tabSize);
- } else{
- var spaceContent = lang.stringRepeat(" ", this.tabSize);
- var tabContent = spaceContent;
- }
-
- this.$tabStrings[" "] = "" + spaceContent + "";
- this.$tabStrings["\t"] = "" + tabContent + "";
- }
- };
-
- this.updateLines = function(config, firstRow, lastRow) {
- if (this.config.lastRow != config.lastRow ||
- this.config.firstRow != config.firstRow) {
- this.scrollLines(config);
- }
- this.config = config;
-
- var first = Math.max(firstRow, config.firstRow);
- var last = Math.min(lastRow, config.lastRow);
-
- var lineElements = this.element.childNodes;
- var lineElementsIdx = 0;
-
- for (var row = config.firstRow; row < first; row++) {
- var foldLine = this.session.getFoldLine(row);
- if (foldLine) {
- if (foldLine.containsRow(first)) {
- first = foldLine.start.row;
- break;
- } else {
- row = foldLine.end.row;
- }
- }
- lineElementsIdx ++;
- }
-
- var row = first;
- var foldLine = this.session.getNextFoldLine(row);
- var foldStart = foldLine ? foldLine.start.row : Infinity;
-
- while (true) {
- if (row > foldStart) {
- row = foldLine.end.row+1;
- foldLine = this.session.getNextFoldLine(row, foldLine);
- foldStart = foldLine ? foldLine.start.row :Infinity;
- }
- if (row > last)
- break;
-
- var lineElement = lineElements[lineElementsIdx++];
- if (lineElement) {
- var html = [];
- this.$renderLine(
- html, row, !this.$useLineGroups(), row == foldStart ? foldLine : false
- );
- lineElement.style.height = config.lineHeight * this.session.getRowLength(row) + "px";
- lineElement.innerHTML = html.join("");
- }
- row++;
- }
- };
-
- this.scrollLines = function(config) {
- var oldConfig = this.config;
- this.config = config;
-
- if (!oldConfig || oldConfig.lastRow < config.firstRow)
- return this.update(config);
-
- if (config.lastRow < oldConfig.firstRow)
- return this.update(config);
-
- var el = this.element;
- if (oldConfig.firstRow < config.firstRow)
- for (var row=this.session.getFoldedRowCount(oldConfig.firstRow, config.firstRow - 1); row>0; row--)
- el.removeChild(el.firstChild);
-
- if (oldConfig.lastRow > config.lastRow)
- for (var row=this.session.getFoldedRowCount(config.lastRow + 1, oldConfig.lastRow); row>0; row--)
- el.removeChild(el.lastChild);
-
- if (config.firstRow < oldConfig.firstRow) {
- var fragment = this.$renderLinesFragment(config, config.firstRow, oldConfig.firstRow - 1);
- if (el.firstChild)
- el.insertBefore(fragment, el.firstChild);
- else
- el.appendChild(fragment);
- }
-
- if (config.lastRow > oldConfig.lastRow) {
- var fragment = this.$renderLinesFragment(config, oldConfig.lastRow + 1, config.lastRow);
- el.appendChild(fragment);
- }
- };
-
- this.$renderLinesFragment = function(config, firstRow, lastRow) {
- var fragment = this.element.ownerDocument.createDocumentFragment();
- var row = firstRow;
- var foldLine = this.session.getNextFoldLine(row);
- var foldStart = foldLine ? foldLine.start.row : Infinity;
-
- while (true) {
- if (row > foldStart) {
- row = foldLine.end.row+1;
- foldLine = this.session.getNextFoldLine(row, foldLine);
- foldStart = foldLine ? foldLine.start.row : Infinity;
- }
- if (row > lastRow)
- break;
-
- var container = dom.createElement("div");
-
- var html = [];
- this.$renderLine(html, row, false, row == foldStart ? foldLine : false);
- container.innerHTML = html.join("");
- if (this.$useLineGroups()) {
- container.className = 'ace_line_group';
- fragment.appendChild(container);
- container.style.height = config.lineHeight * this.session.getRowLength(row) + "px";
-
- } else {
- while(container.firstChild)
- fragment.appendChild(container.firstChild);
- }
-
- row++;
- }
- return fragment;
- };
-
- this.update = function(config) {
- this.config = config;
-
- var html = [];
- var firstRow = config.firstRow, lastRow = config.lastRow;
-
- var row = firstRow;
- var foldLine = this.session.getNextFoldLine(row);
- var foldStart = foldLine ? foldLine.start.row : Infinity;
-
- while (true) {
- if (row > foldStart) {
- row = foldLine.end.row+1;
- foldLine = this.session.getNextFoldLine(row, foldLine);
- foldStart = foldLine ? foldLine.start.row :Infinity;
- }
- if (row > lastRow)
- break;
-
- if (this.$useLineGroups())
- html.push("")
-
- this.$renderLine(html, row, false, row == foldStart ? foldLine : false);
-
- if (this.$useLineGroups())
- html.push("
"); // end the line group
-
- row++;
- }
- this.element.innerHTML = html.join("");
- };
-
- this.$textToken = {
- "text": true,
- "rparen": true,
- "lparen": true
- };
-
- this.$renderToken = function(stringBuilder, screenColumn, token, value) {
- var self = this;
- var replaceReg = /\t|&|<|>|( +)|([\x00-\x1f\x80-\xa0\xad\u1680\u180E\u2000-\u200f\u2028\u2029\u202F\u205F\u3000\uFEFF\uFFF9-\uFFFC])|[\u1100-\u115F\u11A3-\u11A7\u11FA-\u11FF\u2329-\u232A\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3000-\u303E\u3041-\u3096\u3099-\u30FF\u3105-\u312D\u3131-\u318E\u3190-\u31BA\u31C0-\u31E3\u31F0-\u321E\u3220-\u3247\u3250-\u32FE\u3300-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFF01-\uFF60\uFFE0-\uFFE6]/g;
- var replaceFunc = function(c, a, b, tabIdx, idx4) {
- if (a) {
- return self.showInvisibles
- ? "" + lang.stringRepeat(self.SPACE_CHAR, c.length) + ""
- : c;
- } else if (c == "&") {
- return "&";
- } else if (c == "<") {
- return "<";
- } else if (c == ">") {
- return ">";
- } else if (c == "\t") {
- var tabSize = self.session.getScreenTabSize(screenColumn + tabIdx);
- screenColumn += tabSize - 1;
- return self.$tabStrings[tabSize];
- } else if (c == "\u3000") {
- var classToUse = self.showInvisibles ? "ace_cjk ace_invisible ace_invisible_space" : "ace_cjk";
- var space = self.showInvisibles ? self.SPACE_CHAR : "";
- screenColumn += 1;
- return "" + space + "";
- } else if (b) {
- return "" + self.SPACE_CHAR + "";
- } else {
- screenColumn += 1;
- return "" + c + "";
- }
- };
-
- var output = value.replace(replaceReg, replaceFunc);
-
- if (!this.$textToken[token.type]) {
- var classes = "ace_" + token.type.replace(/\./g, " ace_");
- var style = "";
- if (token.type == "fold")
- style = " style='width:" + (token.value.length * this.config.characterWidth) + "px;' ";
- stringBuilder.push("", output, "");
- }
- else {
- stringBuilder.push(output);
- }
- return screenColumn + value.length;
- };
-
- this.renderIndentGuide = function(stringBuilder, value, max) {
- var cols = value.search(this.$indentGuideRe);
- if (cols <= 0 || cols >= max)
- return value;
- if (value[0] == " ") {
- cols -= cols % this.tabSize;
- stringBuilder.push(lang.stringRepeat(this.$tabStrings[" "], cols/this.tabSize));
- return value.substr(cols);
- } else if (value[0] == "\t") {
- stringBuilder.push(lang.stringRepeat(this.$tabStrings["\t"], cols));
- return value.substr(cols);
- }
- return value;
- };
-
- this.$renderWrappedLine = function(stringBuilder, tokens, splits, onlyContents) {
- var chars = 0;
- var split = 0;
- var splitChars = splits[0];
- var screenColumn = 0;
-
- for (var i = 0; i < tokens.length; i++) {
- var token = tokens[i];
- var value = token.value;
- if (i == 0 && this.displayIndentGuides) {
- chars = value.length;
- value = this.renderIndentGuide(stringBuilder, value, splitChars);
- if (!value)
- continue;
- chars -= value.length;
- }
-
- if (chars + value.length < splitChars) {
- screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value);
- chars += value.length;
- } else {
- while (chars + value.length >= splitChars) {
- screenColumn = this.$renderToken(
- stringBuilder, screenColumn,
- token, value.substring(0, splitChars - chars)
- );
- value = value.substring(splitChars - chars);
- chars = splitChars;
-
- if (!onlyContents) {
- stringBuilder.push("",
- "
"
- );
- }
-
- stringBuilder.push(lang.stringRepeat("\xa0", splits.indent));
-
- split ++;
- screenColumn = 0;
- splitChars = splits[split] || Number.MAX_VALUE;
- }
- if (value.length != 0) {
- chars += value.length;
- screenColumn = this.$renderToken(
- stringBuilder, screenColumn, token, value
- );
- }
- }
- }
- };
-
- this.$renderSimpleLine = function(stringBuilder, tokens) {
- var screenColumn = 0;
- var token = tokens[0];
- var value = token.value;
- if (this.displayIndentGuides)
- value = this.renderIndentGuide(stringBuilder, value);
- if (value)
- screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value);
- for (var i = 1; i < tokens.length; i++) {
- token = tokens[i];
- value = token.value;
- screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value);
- }
- };
- this.$renderLine = function(stringBuilder, row, onlyContents, foldLine) {
- if (!foldLine && foldLine != false)
- foldLine = this.session.getFoldLine(row);
-
- if (foldLine)
- var tokens = this.$getFoldLineTokens(row, foldLine);
- else
- var tokens = this.session.getTokens(row);
-
-
- if (!onlyContents) {
- stringBuilder.push(
- "
"
- );
- }
-
- if (tokens.length) {
- var splits = this.session.getRowSplitData(row);
- if (splits && splits.length)
- this.$renderWrappedLine(stringBuilder, tokens, splits, onlyContents);
- else
- this.$renderSimpleLine(stringBuilder, tokens);
- }
-
- if (this.showInvisibles) {
- if (foldLine)
- row = foldLine.end.row
-
- stringBuilder.push(
- "",
- row == this.session.getLength() - 1 ? this.EOF_CHAR : this.EOL_CHAR,
- ""
- );
- }
- if (!onlyContents)
- stringBuilder.push("
");
- };
-
- this.$getFoldLineTokens = function(row, foldLine) {
- var session = this.session;
- var renderTokens = [];
-
- function addTokens(tokens, from, to) {
- var idx = 0, col = 0;
- while ((col + tokens[idx].value.length) < from) {
- col += tokens[idx].value.length;
- idx++;
-
- if (idx == tokens.length)
- return;
- }
- if (col != from) {
- var value = tokens[idx].value.substring(from - col);
- if (value.length > (to - from))
- value = value.substring(0, to - from);
-
- renderTokens.push({
- type: tokens[idx].type,
- value: value
- });
-
- col = from + value.length;
- idx += 1;
- }
-
- while (col < to && idx < tokens.length) {
- var value = tokens[idx].value;
- if (value.length + col > to) {
- renderTokens.push({
- type: tokens[idx].type,
- value: value.substring(0, to - col)
- });
- } else
- renderTokens.push(tokens[idx]);
- col += value.length;
- idx += 1;
- }
- }
-
- var tokens = session.getTokens(row);
- foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) {
- if (placeholder != null) {
- renderTokens.push({
- type: "fold",
- value: placeholder
- });
- } else {
- if (isNewRow)
- tokens = session.getTokens(row);
-
- if (tokens.length)
- addTokens(tokens, lastColumn, column);
- }
- }, foldLine.end.row, this.session.getLine(foldLine.end.row).length);
-
- return renderTokens;
- };
-
- this.$useLineGroups = function() {
- return this.session.getUseWrapMode();
- };
-
- this.destroy = function() {
- clearInterval(this.$pollSizeChangesTimer);
- if (this.$measureNode)
- this.$measureNode.parentNode.removeChild(this.$measureNode);
- delete this.$measureNode;
- };
-
-}).call(Text.prototype);
-
-exports.Text = Text;
-
-});
-
-ace.define("ace/layer/cursor",["require","exports","module","ace/lib/dom"], function(require, exports, module) {
-"use strict";
-
-var dom = require("../lib/dom");
-var isIE8;
-
-var Cursor = function(parentEl) {
- this.element = dom.createElement("div");
- this.element.className = "ace_layer ace_cursor-layer";
- parentEl.appendChild(this.element);
-
- if (isIE8 === undefined)
- isIE8 = !("opacity" in this.element.style);
-
- this.isVisible = false;
- this.isBlinking = true;
- this.blinkInterval = 1000;
- this.smoothBlinking = false;
-
- this.cursors = [];
- this.cursor = this.addCursor();
- dom.addCssClass(this.element, "ace_hidden-cursors");
- this.$updateCursors = (isIE8
- ? this.$updateVisibility
- : this.$updateOpacity).bind(this);
-};
-
-(function() {
-
- this.$updateVisibility = function(val) {
- var cursors = this.cursors;
- for (var i = cursors.length; i--; )
- cursors[i].style.visibility = val ? "" : "hidden";
- };
- this.$updateOpacity = function(val) {
- var cursors = this.cursors;
- for (var i = cursors.length; i--; )
- cursors[i].style.opacity = val ? "" : "0";
- };
-
-
- this.$padding = 0;
- this.setPadding = function(padding) {
- this.$padding = padding;
- };
-
- this.setSession = function(session) {
- this.session = session;
- };
-
- this.setBlinking = function(blinking) {
- if (blinking != this.isBlinking){
- this.isBlinking = blinking;
- this.restartTimer();
- }
- };
-
- this.setBlinkInterval = function(blinkInterval) {
- if (blinkInterval != this.blinkInterval){
- this.blinkInterval = blinkInterval;
- this.restartTimer();
- }
- };
-
- this.setSmoothBlinking = function(smoothBlinking) {
- if (smoothBlinking != this.smoothBlinking && !isIE8) {
- this.smoothBlinking = smoothBlinking;
- dom.setCssClass(this.element, "ace_smooth-blinking", smoothBlinking);
- this.$updateCursors(true);
- this.$updateCursors = (this.$updateOpacity).bind(this);
- this.restartTimer();
- }
- };
-
- this.addCursor = function() {
- var el = dom.createElement("div");
- el.className = "ace_cursor";
- this.element.appendChild(el);
- this.cursors.push(el);
- return el;
- };
-
- this.removeCursor = function() {
- if (this.cursors.length > 1) {
- var el = this.cursors.pop();
- el.parentNode.removeChild(el);
- return el;
- }
- };
-
- this.hideCursor = function() {
- this.isVisible = false;
- dom.addCssClass(this.element, "ace_hidden-cursors");
- this.restartTimer();
- };
-
- this.showCursor = function() {
- this.isVisible = true;
- dom.removeCssClass(this.element, "ace_hidden-cursors");
- this.restartTimer();
- };
-
- this.restartTimer = function() {
- var update = this.$updateCursors;
- clearInterval(this.intervalId);
- clearTimeout(this.timeoutId);
- if (this.smoothBlinking) {
- dom.removeCssClass(this.element, "ace_smooth-blinking");
- }
-
- update(true);
-
- if (!this.isBlinking || !this.blinkInterval || !this.isVisible)
- return;
-
- if (this.smoothBlinking) {
- setTimeout(function(){
- dom.addCssClass(this.element, "ace_smooth-blinking");
- }.bind(this));
- }
-
- var blink = function(){
- this.timeoutId = setTimeout(function() {
- update(false);
- }, 0.6 * this.blinkInterval);
- }.bind(this);
-
- this.intervalId = setInterval(function() {
- update(true);
- blink();
- }, this.blinkInterval);
-
- blink();
- };
-
- this.getPixelPosition = function(position, onScreen) {
- if (!this.config || !this.session)
- return {left : 0, top : 0};
-
- if (!position)
- position = this.session.selection.getCursor();
- var pos = this.session.documentToScreenPosition(position);
- var cursorLeft = this.$padding + pos.column * this.config.characterWidth;
- var cursorTop = (pos.row - (onScreen ? this.config.firstRowScreen : 0)) *
- this.config.lineHeight;
-
- return {left : cursorLeft, top : cursorTop};
- };
-
- this.update = function(config) {
- this.config = config;
-
- var selections = this.session.$selectionMarkers;
- var i = 0, cursorIndex = 0;
-
- if (selections === undefined || selections.length === 0){
- selections = [{cursor: null}];
- }
-
- for (var i = 0, n = selections.length; i < n; i++) {
- var pixelPos = this.getPixelPosition(selections[i].cursor, true);
- if ((pixelPos.top > config.height + config.offset ||
- pixelPos.top < 0) && i > 1) {
- continue;
- }
-
- var style = (this.cursors[cursorIndex++] || this.addCursor()).style;
-
- if (!this.drawCursor) {
- style.left = pixelPos.left + "px";
- style.top = pixelPos.top + "px";
- style.width = config.characterWidth + "px";
- style.height = config.lineHeight + "px";
- } else {
- this.drawCursor(style, pixelPos, config, selections[i], this.session);
- }
- }
- while (this.cursors.length > cursorIndex)
- this.removeCursor();
-
- var overwrite = this.session.getOverwrite();
- this.$setOverwrite(overwrite);
- this.$pixelPos = pixelPos;
- this.restartTimer();
- };
-
- this.drawCursor = null;
-
- this.$setOverwrite = function(overwrite) {
- if (overwrite != this.overwrite) {
- this.overwrite = overwrite;
- if (overwrite)
- dom.addCssClass(this.element, "ace_overwrite-cursors");
- else
- dom.removeCssClass(this.element, "ace_overwrite-cursors");
- }
- };
-
- this.destroy = function() {
- clearInterval(this.intervalId);
- clearTimeout(this.timeoutId);
- };
-
-}).call(Cursor.prototype);
-
-exports.Cursor = Cursor;
-
-});
-
-ace.define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"], function(require, exports, module) {
-"use strict";
-
-var oop = require("./lib/oop");
-var dom = require("./lib/dom");
-var event = require("./lib/event");
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-var ScrollBar = function(parent) {
- this.element = dom.createElement("div");
- this.element.className = "ace_scrollbar ace_scrollbar" + this.classSuffix;
-
- this.inner = dom.createElement("div");
- this.inner.className = "ace_scrollbar-inner";
- this.element.appendChild(this.inner);
-
- parent.appendChild(this.element);
-
- this.setVisible(false);
- this.skipEvent = false;
-
- event.addListener(this.element, "scroll", this.onScroll.bind(this));
- event.addListener(this.element, "mousedown", event.preventDefault);
-};
-
-(function() {
- oop.implement(this, EventEmitter);
-
- this.setVisible = function(isVisible) {
- this.element.style.display = isVisible ? "" : "none";
- this.isVisible = isVisible;
- };
-}).call(ScrollBar.prototype);
-var VScrollBar = function(parent, renderer) {
- ScrollBar.call(this, parent);
- this.scrollTop = 0;
- renderer.$scrollbarWidth =
- this.width = dom.scrollbarWidth(parent.ownerDocument);
- this.inner.style.width =
- this.element.style.width = (this.width || 15) + 5 + "px";
-};
-
-oop.inherits(VScrollBar, ScrollBar);
-
-(function() {
-
- this.classSuffix = '-v';
- this.onScroll = function() {
- if (!this.skipEvent) {
- this.scrollTop = this.element.scrollTop;
- this._emit("scroll", {data: this.scrollTop});
- }
- this.skipEvent = false;
- };
- this.getWidth = function() {
- return this.isVisible ? this.width : 0;
- };
- this.setHeight = function(height) {
- this.element.style.height = height + "px";
- };
- this.setInnerHeight = function(height) {
- this.inner.style.height = height + "px";
- };
- this.setScrollHeight = function(height) {
- this.inner.style.height = height + "px";
- };
- this.setScrollTop = function(scrollTop) {
- if (this.scrollTop != scrollTop) {
- this.skipEvent = true;
- this.scrollTop = this.element.scrollTop = scrollTop;
- }
- };
-
-}).call(VScrollBar.prototype);
-var HScrollBar = function(parent, renderer) {
- ScrollBar.call(this, parent);
- this.scrollLeft = 0;
- this.height = renderer.$scrollbarWidth;
- this.inner.style.height =
- this.element.style.height = (this.height || 15) + 5 + "px";
-};
-
-oop.inherits(HScrollBar, ScrollBar);
-
-(function() {
-
- this.classSuffix = '-h';
- this.onScroll = function() {
- if (!this.skipEvent) {
- this.scrollLeft = this.element.scrollLeft;
- this._emit("scroll", {data: this.scrollLeft});
- }
- this.skipEvent = false;
- };
- this.getHeight = function() {
- return this.isVisible ? this.height : 0;
- };
- this.setWidth = function(width) {
- this.element.style.width = width + "px";
- };
- this.setInnerWidth = function(width) {
- this.inner.style.width = width + "px";
- };
- this.setScrollWidth = function(width) {
- this.inner.style.width = width + "px";
- };
- this.setScrollLeft = function(scrollLeft) {
- if (this.scrollLeft != scrollLeft) {
- this.skipEvent = true;
- this.scrollLeft = this.element.scrollLeft = scrollLeft;
- }
- };
-
-}).call(HScrollBar.prototype);
-
-
-exports.ScrollBar = VScrollBar; // backward compatibility
-exports.ScrollBarV = VScrollBar; // backward compatibility
-exports.ScrollBarH = HScrollBar; // backward compatibility
-
-exports.VScrollBar = VScrollBar;
-exports.HScrollBar = HScrollBar;
-});
-
-ace.define("ace/renderloop",["require","exports","module","ace/lib/event"], function(require, exports, module) {
-"use strict";
-
-var event = require("./lib/event");
-
-
-var RenderLoop = function(onRender, win) {
- this.onRender = onRender;
- this.pending = false;
- this.changes = 0;
- this.window = win || window;
-};
-
-(function() {
-
-
- this.schedule = function(change) {
- this.changes = this.changes | change;
- if (!this.pending && this.changes) {
- this.pending = true;
- var _self = this;
- event.nextFrame(function() {
- _self.pending = false;
- var changes;
- while (changes = _self.changes) {
- _self.changes = 0;
- _self.onRender(changes);
- }
- }, this.window);
- }
- };
-
-}).call(RenderLoop.prototype);
-
-exports.RenderLoop = RenderLoop;
-});
-
-ace.define("ace/layer/font_metrics",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"], function(require, exports, module) {
-
-var oop = require("../lib/oop");
-var dom = require("../lib/dom");
-var lang = require("../lib/lang");
-var useragent = require("../lib/useragent");
-var EventEmitter = require("../lib/event_emitter").EventEmitter;
-
-var CHAR_COUNT = 0;
-
-var FontMetrics = exports.FontMetrics = function(parentEl) {
- this.el = dom.createElement("div");
- this.$setMeasureNodeStyles(this.el.style, true);
-
- this.$main = dom.createElement("div");
- this.$setMeasureNodeStyles(this.$main.style);
-
- this.$measureNode = dom.createElement("div");
- this.$setMeasureNodeStyles(this.$measureNode.style);
-
-
- this.el.appendChild(this.$main);
- this.el.appendChild(this.$measureNode);
- parentEl.appendChild(this.el);
-
- if (!CHAR_COUNT)
- this.$testFractionalRect();
- this.$measureNode.innerHTML = lang.stringRepeat("X", CHAR_COUNT);
-
- this.$characterSize = {width: 0, height: 0};
- this.checkForSizeChanges();
-};
-
-(function() {
-
- oop.implement(this, EventEmitter);
-
- this.$characterSize = {width: 0, height: 0};
-
- this.$testFractionalRect = function() {
- var el = dom.createElement("div");
- this.$setMeasureNodeStyles(el.style);
- el.style.width = "0.2px";
- document.documentElement.appendChild(el);
- var w = el.getBoundingClientRect().width;
- if (w > 0 && w < 1)
- CHAR_COUNT = 50;
- else
- CHAR_COUNT = 100;
- el.parentNode.removeChild(el);
- };
-
- this.$setMeasureNodeStyles = function(style, isRoot) {
- style.width = style.height = "auto";
- style.left = style.top = "0px";
- style.visibility = "hidden";
- style.position = "absolute";
- style.whiteSpace = "pre";
-
- if (useragent.isIE < 8) {
- style["font-family"] = "inherit";
- } else {
- style.font = "inherit";
- }
- style.overflow = isRoot ? "hidden" : "visible";
- };
-
- this.checkForSizeChanges = function() {
- var size = this.$measureSizes();
- if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) {
- this.$measureNode.style.fontWeight = "bold";
- var boldSize = this.$measureSizes();
- this.$measureNode.style.fontWeight = "";
- this.$characterSize = size;
- this.charSizes = Object.create(null);
- this.allowBoldFonts = boldSize && boldSize.width === size.width && boldSize.height === size.height;
- this._emit("changeCharacterSize", {data: size});
- }
- };
-
- this.$pollSizeChanges = function() {
- if (this.$pollSizeChangesTimer)
- return this.$pollSizeChangesTimer;
- var self = this;
- return this.$pollSizeChangesTimer = setInterval(function() {
- self.checkForSizeChanges();
- }, 500);
- };
-
- this.setPolling = function(val) {
- if (val) {
- this.$pollSizeChanges();
- } else if (this.$pollSizeChangesTimer) {
- clearInterval(this.$pollSizeChangesTimer);
- this.$pollSizeChangesTimer = 0;
- }
- };
-
- this.$measureSizes = function() {
- if (CHAR_COUNT === 50) {
- var rect = null;
- try {
- rect = this.$measureNode.getBoundingClientRect();
- } catch(e) {
- rect = {width: 0, height:0 };
- }
- var size = {
- height: rect.height,
- width: rect.width / CHAR_COUNT
- };
- } else {
- var size = {
- height: this.$measureNode.clientHeight,
- width: this.$measureNode.clientWidth / CHAR_COUNT
- };
- }
- if (size.width === 0 || size.height === 0)
- return null;
- return size;
- };
-
- this.$measureCharWidth = function(ch) {
- this.$main.innerHTML = lang.stringRepeat(ch, CHAR_COUNT);
- var rect = this.$main.getBoundingClientRect();
- return rect.width / CHAR_COUNT;
- };
-
- this.getCharacterWidth = function(ch) {
- var w = this.charSizes[ch];
- if (w === undefined) {
- w = this.charSizes[ch] = this.$measureCharWidth(ch) / this.$characterSize.width;
- }
- return w;
- };
-
- this.destroy = function() {
- clearInterval(this.$pollSizeChangesTimer);
- if (this.el && this.el.parentNode)
- this.el.parentNode.removeChild(this.el);
- };
-
-}).call(FontMetrics.prototype);
-
-});
-
-ace.define("ace/virtual_renderer",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/config","ace/lib/useragent","ace/layer/gutter","ace/layer/marker","ace/layer/text","ace/layer/cursor","ace/scrollbar","ace/scrollbar","ace/renderloop","ace/layer/font_metrics","ace/lib/event_emitter"], function(require, exports, module) {
-"use strict";
-
-var oop = require("./lib/oop");
-var dom = require("./lib/dom");
-var config = require("./config");
-var useragent = require("./lib/useragent");
-var GutterLayer = require("./layer/gutter").Gutter;
-var MarkerLayer = require("./layer/marker").Marker;
-var TextLayer = require("./layer/text").Text;
-var CursorLayer = require("./layer/cursor").Cursor;
-var HScrollBar = require("./scrollbar").HScrollBar;
-var VScrollBar = require("./scrollbar").VScrollBar;
-var RenderLoop = require("./renderloop").RenderLoop;
-var FontMetrics = require("./layer/font_metrics").FontMetrics;
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-var editorCss = ".ace_editor {\
-position: relative;\
-overflow: hidden;\
-font: 12px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\
-direction: ltr;\
-}\
-.ace_scroller {\
-position: absolute;\
-overflow: hidden;\
-top: 0;\
-bottom: 0;\
-background-color: inherit;\
--ms-user-select: none;\
--moz-user-select: none;\
--webkit-user-select: none;\
-user-select: none;\
-cursor: text;\
-}\
-.ace_content {\
-position: absolute;\
--moz-box-sizing: border-box;\
--webkit-box-sizing: border-box;\
-box-sizing: border-box;\
-min-width: 100%;\
-}\
-.ace_dragging .ace_scroller:before{\
-position: absolute;\
-top: 0;\
-left: 0;\
-right: 0;\
-bottom: 0;\
-content: '';\
-background: rgba(250, 250, 250, 0.01);\
-z-index: 1000;\
-}\
-.ace_dragging.ace_dark .ace_scroller:before{\
-background: rgba(0, 0, 0, 0.01);\
-}\
-.ace_selecting, .ace_selecting * {\
-cursor: text !important;\
-}\
-.ace_gutter {\
-position: absolute;\
-overflow : hidden;\
-width: auto;\
-top: 0;\
-bottom: 0;\
-left: 0;\
-cursor: default;\
-z-index: 4;\
--ms-user-select: none;\
--moz-user-select: none;\
--webkit-user-select: none;\
-user-select: none;\
-}\
-.ace_gutter-active-line {\
-position: absolute;\
-left: 0;\
-right: 0;\
-}\
-.ace_scroller.ace_scroll-left {\
-box-shadow: 17px 0 16px -16px rgba(0, 0, 0, 0.4) inset;\
-}\
-.ace_gutter-cell {\
-padding-left: 19px;\
-padding-right: 6px;\
-background-repeat: no-repeat;\
-}\
-.ace_gutter-cell.ace_error {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAABOFBMVEX/////////QRswFAb/Ui4wFAYwFAYwFAaWGAfDRymzOSH/PxswFAb/SiUwFAYwFAbUPRvjQiDllog5HhHdRybsTi3/Tyv9Tir+Syj/UC3////XurebMBIwFAb/RSHbPx/gUzfdwL3kzMivKBAwFAbbvbnhPx66NhowFAYwFAaZJg8wFAaxKBDZurf/RB6mMxb/SCMwFAYwFAbxQB3+RB4wFAb/Qhy4Oh+4QifbNRcwFAYwFAYwFAb/QRzdNhgwFAYwFAbav7v/Uy7oaE68MBK5LxLewr/r2NXewLswFAaxJw4wFAbkPRy2PyYwFAaxKhLm1tMwFAazPiQwFAaUGAb/QBrfOx3bvrv/VC/maE4wFAbRPBq6MRO8Qynew8Dp2tjfwb0wFAbx6eju5+by6uns4uH9/f36+vr/GkHjAAAAYnRSTlMAGt+64rnWu/bo8eAA4InH3+DwoN7j4eLi4xP99Nfg4+b+/u9B/eDs1MD1mO7+4PHg2MXa347g7vDizMLN4eG+Pv7i5evs/v79yu7S3/DV7/498Yv24eH+4ufQ3Ozu/v7+y13sRqwAAADLSURBVHjaZc/XDsFgGIBhtDrshlitmk2IrbHFqL2pvXf/+78DPokj7+Fz9qpU/9UXJIlhmPaTaQ6QPaz0mm+5gwkgovcV6GZzd5JtCQwgsxoHOvJO15kleRLAnMgHFIESUEPmawB9ngmelTtipwwfASilxOLyiV5UVUyVAfbG0cCPHig+GBkzAENHS0AstVF6bacZIOzgLmxsHbt2OecNgJC83JERmePUYq8ARGkJx6XtFsdddBQgZE2nPR6CICZhawjA4Fb/chv+399kfR+MMMDGOQAAAABJRU5ErkJggg==\");\
-background-repeat: no-repeat;\
-background-position: 2px center;\
-}\
-.ace_gutter-cell.ace_warning {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAmVBMVEX///8AAAD///8AAAAAAABPSzb/5sAAAAB/blH/73z/ulkAAAAAAAD85pkAAAAAAAACAgP/vGz/rkDerGbGrV7/pkQICAf////e0IsAAAD/oED/qTvhrnUAAAD/yHD/njcAAADuv2r/nz//oTj/p064oGf/zHAAAAA9Nir/tFIAAAD/tlTiuWf/tkIAAACynXEAAAAAAAAtIRW7zBpBAAAAM3RSTlMAABR1m7RXO8Ln31Z36zT+neXe5OzooRDfn+TZ4p3h2hTf4t3k3ucyrN1K5+Xaks52Sfs9CXgrAAAAjklEQVR42o3PbQ+CIBQFYEwboPhSYgoYunIqqLn6/z8uYdH8Vmdnu9vz4WwXgN/xTPRD2+sgOcZjsge/whXZgUaYYvT8QnuJaUrjrHUQreGczuEafQCO/SJTufTbroWsPgsllVhq3wJEk2jUSzX3CUEDJC84707djRc5MTAQxoLgupWRwW6UB5fS++NV8AbOZgnsC7BpEAAAAABJRU5ErkJggg==\");\
-background-position: 2px center;\
-}\
-.ace_gutter-cell.ace_info {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAJ0Uk5TAAB2k804AAAAPklEQVQY02NgIB68QuO3tiLznjAwpKTgNyDbMegwisCHZUETUZV0ZqOquBpXj2rtnpSJT1AEnnRmL2OgGgAAIKkRQap2htgAAAAASUVORK5CYII=\");\
-background-position: 2px center;\
-}\
-.ace_dark .ace_gutter-cell.ace_info {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAJFBMVEUAAAChoaGAgIAqKiq+vr6tra1ZWVmUlJSbm5s8PDxubm56enrdgzg3AAAAAXRSTlMAQObYZgAAAClJREFUeNpjYMAPdsMYHegyJZFQBlsUlMFVCWUYKkAZMxZAGdxlDMQBAG+TBP4B6RyJAAAAAElFTkSuQmCC\");\
-}\
-.ace_scrollbar {\
-position: absolute;\
-right: 0;\
-bottom: 0;\
-z-index: 6;\
-}\
-.ace_scrollbar-inner {\
-position: absolute;\
-cursor: text;\
-left: 0;\
-top: 0;\
-}\
-.ace_scrollbar-v{\
-overflow-x: hidden;\
-overflow-y: scroll;\
-top: 0;\
-}\
-.ace_scrollbar-h {\
-overflow-x: scroll;\
-overflow-y: hidden;\
-left: 0;\
-}\
-.ace_print-margin {\
-position: absolute;\
-height: 100%;\
-}\
-.ace_text-input {\
-position: absolute;\
-z-index: 0;\
-width: 0.5em;\
-height: 1em;\
-opacity: 0;\
-background: transparent;\
--moz-appearance: none;\
-appearance: none;\
-border: none;\
-resize: none;\
-outline: none;\
-overflow: hidden;\
-font: inherit;\
-padding: 0 1px;\
-margin: 0 -1px;\
-text-indent: -1em;\
--ms-user-select: text;\
--moz-user-select: text;\
--webkit-user-select: text;\
-user-select: text;\
-white-space: pre!important;\
-}\
-.ace_text-input.ace_composition {\
-background: inherit;\
-color: inherit;\
-z-index: 1000;\
-opacity: 1;\
-text-indent: 0;\
-}\
-.ace_layer {\
-z-index: 1;\
-position: absolute;\
-overflow: hidden;\
-word-wrap: normal;\
-white-space: pre;\
-height: 100%;\
-width: 100%;\
--moz-box-sizing: border-box;\
--webkit-box-sizing: border-box;\
-box-sizing: border-box;\
-pointer-events: none;\
-}\
-.ace_gutter-layer {\
-position: relative;\
-width: auto;\
-text-align: right;\
-pointer-events: auto;\
-}\
-.ace_text-layer {\
-font: inherit !important;\
-}\
-.ace_cjk {\
-display: inline-block;\
-text-align: center;\
-}\
-.ace_cursor-layer {\
-z-index: 4;\
-}\
-.ace_cursor {\
-z-index: 4;\
-position: absolute;\
--moz-box-sizing: border-box;\
--webkit-box-sizing: border-box;\
-box-sizing: border-box;\
-border-left: 2px solid;\
-transform: translatez(0);\
-}\
-.ace_slim-cursors .ace_cursor {\
-border-left-width: 1px;\
-}\
-.ace_overwrite-cursors .ace_cursor {\
-border-left-width: 0;\
-border-bottom: 1px solid;\
-}\
-.ace_hidden-cursors .ace_cursor {\
-opacity: 0.2;\
-}\
-.ace_smooth-blinking .ace_cursor {\
--webkit-transition: opacity 0.18s;\
-transition: opacity 0.18s;\
-}\
-.ace_editor.ace_multiselect .ace_cursor {\
-border-left-width: 1px;\
-}\
-.ace_marker-layer .ace_step, .ace_marker-layer .ace_stack {\
-position: absolute;\
-z-index: 3;\
-}\
-.ace_marker-layer .ace_selection {\
-position: absolute;\
-z-index: 5;\
-}\
-.ace_marker-layer .ace_bracket {\
-position: absolute;\
-z-index: 6;\
-}\
-.ace_marker-layer .ace_active-line {\
-position: absolute;\
-z-index: 2;\
-}\
-.ace_marker-layer .ace_selected-word {\
-position: absolute;\
-z-index: 4;\
--moz-box-sizing: border-box;\
--webkit-box-sizing: border-box;\
-box-sizing: border-box;\
-}\
-.ace_line .ace_fold {\
--moz-box-sizing: border-box;\
--webkit-box-sizing: border-box;\
-box-sizing: border-box;\
-display: inline-block;\
-height: 11px;\
-margin-top: -2px;\
-vertical-align: middle;\
-background-image:\
-url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\
-url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi+P//fxgTAwPDBxDxD078RSX+YeEyDFMCIMAAI3INmXiwf2YAAAAASUVORK5CYII=\");\
-background-repeat: no-repeat, repeat-x;\
-background-position: center center, top left;\
-color: transparent;\
-border: 1px solid black;\
-border-radius: 2px;\
-cursor: pointer;\
-pointer-events: auto;\
-}\
-.ace_dark .ace_fold {\
-}\
-.ace_fold:hover{\
-background-image:\
-url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\
-url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACBJREFUeNpi+P//fz4TAwPDZxDxD5X4i5fLMEwJgAADAEPVDbjNw87ZAAAAAElFTkSuQmCC\");\
-}\
-.ace_tooltip {\
-background-color: #FFF;\
-background-image: -webkit-linear-gradient(top, transparent, rgba(0, 0, 0, 0.1));\
-background-image: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.1));\
-border: 1px solid gray;\
-border-radius: 1px;\
-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);\
-color: black;\
-max-width: 100%;\
-padding: 3px 4px;\
-position: fixed;\
-z-index: 999999;\
--moz-box-sizing: border-box;\
--webkit-box-sizing: border-box;\
-box-sizing: border-box;\
-cursor: default;\
-white-space: pre;\
-word-wrap: break-word;\
-line-height: normal;\
-font-style: normal;\
-font-weight: normal;\
-letter-spacing: normal;\
-pointer-events: none;\
-}\
-.ace_folding-enabled > .ace_gutter-cell {\
-padding-right: 13px;\
-}\
-.ace_fold-widget {\
--moz-box-sizing: border-box;\
--webkit-box-sizing: border-box;\
-box-sizing: border-box;\
-margin: 0 -12px 0 1px;\
-display: none;\
-width: 11px;\
-vertical-align: top;\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42mWKsQ0AMAzC8ixLlrzQjzmBiEjp0A6WwBCSPgKAXoLkqSot7nN3yMwR7pZ32NzpKkVoDBUxKAAAAABJRU5ErkJggg==\");\
-background-repeat: no-repeat;\
-background-position: center;\
-border-radius: 3px;\
-border: 1px solid transparent;\
-cursor: pointer;\
-}\
-.ace_folding-enabled .ace_fold-widget {\
-display: inline-block; \
-}\
-.ace_fold-widget.ace_end {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42m3HwQkAMAhD0YzsRchFKI7sAikeWkrxwScEB0nh5e7KTPWimZki4tYfVbX+MNl4pyZXejUO1QAAAABJRU5ErkJggg==\");\
-}\
-.ace_fold-widget.ace_closed {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAGCAYAAAAG5SQMAAAAOUlEQVR42jXKwQkAMAgDwKwqKD4EwQ26sSOkVWjgIIHAzPiCgaqiqnJHZnKICBERHN194O5b9vbLuAVRL+l0YWnZAAAAAElFTkSuQmCCXA==\");\
-}\
-.ace_fold-widget:hover {\
-border: 1px solid rgba(0, 0, 0, 0.3);\
-background-color: rgba(255, 255, 255, 0.2);\
-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\
-}\
-.ace_fold-widget:active {\
-border: 1px solid rgba(0, 0, 0, 0.4);\
-background-color: rgba(0, 0, 0, 0.05);\
-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\
-}\
-.ace_dark .ace_fold-widget {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHklEQVQIW2P4//8/AzoGEQ7oGCaLLAhWiSwB146BAQCSTPYocqT0AAAAAElFTkSuQmCC\");\
-}\
-.ace_dark .ace_fold-widget.ace_end {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAH0lEQVQIW2P4//8/AxQ7wNjIAjDMgC4AxjCVKBirIAAF0kz2rlhxpAAAAABJRU5ErkJggg==\");\
-}\
-.ace_dark .ace_fold-widget.ace_closed {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAHElEQVQIW2P4//+/AxAzgDADlOOAznHAKgPWAwARji8UIDTfQQAAAABJRU5ErkJggg==\");\
-}\
-.ace_dark .ace_fold-widget:hover {\
-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\
-background-color: rgba(255, 255, 255, 0.1);\
-}\
-.ace_dark .ace_fold-widget:active {\
-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\
-}\
-.ace_fold-widget.ace_invalid {\
-background-color: #FFB4B4;\
-border-color: #DE5555;\
-}\
-.ace_fade-fold-widgets .ace_fold-widget {\
--webkit-transition: opacity 0.4s ease 0.05s;\
-transition: opacity 0.4s ease 0.05s;\
-opacity: 0;\
-}\
-.ace_fade-fold-widgets:hover .ace_fold-widget {\
--webkit-transition: opacity 0.05s ease 0.05s;\
-transition: opacity 0.05s ease 0.05s;\
-opacity:1;\
-}\
-.ace_underline {\
-text-decoration: underline;\
-}\
-.ace_bold {\
-font-weight: bold;\
-}\
-.ace_nobold .ace_bold {\
-font-weight: normal;\
-}\
-.ace_italic {\
-font-style: italic;\
-}\
-.ace_error-marker {\
-background-color: rgba(255, 0, 0,0.2);\
-position: absolute;\
-z-index: 9;\
-}\
-.ace_highlight-marker {\
-background-color: rgba(255, 255, 0,0.2);\
-position: absolute;\
-z-index: 8;\
-}\
-.ace_br1 {border-top-left-radius : 3px;}\
-.ace_br2 {border-top-right-radius : 3px;}\
-.ace_br3 {border-top-left-radius : 3px; border-top-right-radius: 3px;}\
-.ace_br4 {border-bottom-right-radius: 3px;}\
-.ace_br5 {border-top-left-radius : 3px; border-bottom-right-radius: 3px;}\
-.ace_br6 {border-top-right-radius : 3px; border-bottom-right-radius: 3px;}\
-.ace_br7 {border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px;}\
-.ace_br8 {border-bottom-left-radius : 3px;}\
-.ace_br9 {border-top-left-radius : 3px; border-bottom-left-radius: 3px;}\
-.ace_br10{border-top-right-radius : 3px; border-bottom-left-radius: 3px;}\
-.ace_br11{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-left-radius: 3px;}\
-.ace_br12{border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
-.ace_br13{border-top-left-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
-.ace_br14{border-top-right-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
-.ace_br15{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
-";
-
-dom.importCssString(editorCss, "ace_editor.css");
-
-var VirtualRenderer = function(container, theme) {
- var _self = this;
-
- this.container = container || dom.createElement("div");
- this.$keepTextAreaAtCursor = !useragent.isOldIE;
-
- dom.addCssClass(this.container, "ace_editor");
-
- this.setTheme(theme);
-
- this.$gutter = dom.createElement("div");
- this.$gutter.className = "ace_gutter";
- this.container.appendChild(this.$gutter);
-
- this.scroller = dom.createElement("div");
- this.scroller.className = "ace_scroller";
- this.container.appendChild(this.scroller);
-
- this.content = dom.createElement("div");
- this.content.className = "ace_content";
- this.scroller.appendChild(this.content);
-
- this.$gutterLayer = new GutterLayer(this.$gutter);
- this.$gutterLayer.on("changeGutterWidth", this.onGutterResize.bind(this));
-
- this.$markerBack = new MarkerLayer(this.content);
-
- var textLayer = this.$textLayer = new TextLayer(this.content);
- this.canvas = textLayer.element;
-
- this.$markerFront = new MarkerLayer(this.content);
-
- this.$cursorLayer = new CursorLayer(this.content);
- this.$horizScroll = false;
- this.$vScroll = false;
-
- this.scrollBar =
- this.scrollBarV = new VScrollBar(this.container, this);
- this.scrollBarH = new HScrollBar(this.container, this);
- this.scrollBarV.addEventListener("scroll", function(e) {
- if (!_self.$scrollAnimation)
- _self.session.setScrollTop(e.data - _self.scrollMargin.top);
- });
- this.scrollBarH.addEventListener("scroll", function(e) {
- if (!_self.$scrollAnimation)
- _self.session.setScrollLeft(e.data - _self.scrollMargin.left);
- });
-
- this.scrollTop = 0;
- this.scrollLeft = 0;
-
- this.cursorPos = {
- row : 0,
- column : 0
- };
-
- this.$fontMetrics = new FontMetrics(this.container);
- this.$textLayer.$setFontMetrics(this.$fontMetrics);
- this.$textLayer.addEventListener("changeCharacterSize", function(e) {
- _self.updateCharacterSize();
- _self.onResize(true, _self.gutterWidth, _self.$size.width, _self.$size.height);
- _self._signal("changeCharacterSize", e);
- });
-
- this.$size = {
- width: 0,
- height: 0,
- scrollerHeight: 0,
- scrollerWidth: 0,
- $dirty: true
- };
-
- this.layerConfig = {
- width : 1,
- padding : 0,
- firstRow : 0,
- firstRowScreen: 0,
- lastRow : 0,
- lineHeight : 0,
- characterWidth : 0,
- minHeight : 1,
- maxHeight : 1,
- offset : 0,
- height : 1,
- gutterOffset: 1
- };
-
- this.scrollMargin = {
- left: 0,
- right: 0,
- top: 0,
- bottom: 0,
- v: 0,
- h: 0
- };
-
- this.$loop = new RenderLoop(
- this.$renderChanges.bind(this),
- this.container.ownerDocument.defaultView
- );
- this.$loop.schedule(this.CHANGE_FULL);
-
- this.updateCharacterSize();
- this.setPadding(4);
- config.resetOptions(this);
- config._emit("renderer", this);
-};
-
-(function() {
-
- this.CHANGE_CURSOR = 1;
- this.CHANGE_MARKER = 2;
- this.CHANGE_GUTTER = 4;
- this.CHANGE_SCROLL = 8;
- this.CHANGE_LINES = 16;
- this.CHANGE_TEXT = 32;
- this.CHANGE_SIZE = 64;
- this.CHANGE_MARKER_BACK = 128;
- this.CHANGE_MARKER_FRONT = 256;
- this.CHANGE_FULL = 512;
- this.CHANGE_H_SCROLL = 1024;
-
- oop.implement(this, EventEmitter);
-
- this.updateCharacterSize = function() {
- if (this.$textLayer.allowBoldFonts != this.$allowBoldFonts) {
- this.$allowBoldFonts = this.$textLayer.allowBoldFonts;
- this.setStyle("ace_nobold", !this.$allowBoldFonts);
- }
-
- this.layerConfig.characterWidth =
- this.characterWidth = this.$textLayer.getCharacterWidth();
- this.layerConfig.lineHeight =
- this.lineHeight = this.$textLayer.getLineHeight();
- this.$updatePrintMargin();
- };
- this.setSession = function(session) {
- if (this.session)
- this.session.doc.off("changeNewLineMode", this.onChangeNewLineMode);
-
- this.session = session;
- if (session && this.scrollMargin.top && session.getScrollTop() <= 0)
- session.setScrollTop(-this.scrollMargin.top);
-
- this.$cursorLayer.setSession(session);
- this.$markerBack.setSession(session);
- this.$markerFront.setSession(session);
- this.$gutterLayer.setSession(session);
- this.$textLayer.setSession(session);
- if (!session)
- return;
-
- this.$loop.schedule(this.CHANGE_FULL);
- this.session.$setFontMetrics(this.$fontMetrics);
-
- this.onChangeNewLineMode = this.onChangeNewLineMode.bind(this);
- this.onChangeNewLineMode()
- this.session.doc.on("changeNewLineMode", this.onChangeNewLineMode);
- };
- this.updateLines = function(firstRow, lastRow, force) {
- if (lastRow === undefined)
- lastRow = Infinity;
-
- if (!this.$changedLines) {
- this.$changedLines = {
- firstRow: firstRow,
- lastRow: lastRow
- };
- }
- else {
- if (this.$changedLines.firstRow > firstRow)
- this.$changedLines.firstRow = firstRow;
-
- if (this.$changedLines.lastRow < lastRow)
- this.$changedLines.lastRow = lastRow;
- }
- if (this.$changedLines.lastRow < this.layerConfig.firstRow) {
- if (force)
- this.$changedLines.lastRow = this.layerConfig.lastRow;
- else
- return;
- }
- if (this.$changedLines.firstRow > this.layerConfig.lastRow)
- return;
- this.$loop.schedule(this.CHANGE_LINES);
- };
-
- this.onChangeNewLineMode = function() {
- this.$loop.schedule(this.CHANGE_TEXT);
- this.$textLayer.$updateEolChar();
- };
-
- this.onChangeTabSize = function() {
- this.$loop.schedule(this.CHANGE_TEXT | this.CHANGE_MARKER);
- this.$textLayer.onChangeTabSize();
- };
- this.updateText = function() {
- this.$loop.schedule(this.CHANGE_TEXT);
- };
- this.updateFull = function(force) {
- if (force)
- this.$renderChanges(this.CHANGE_FULL, true);
- else
- this.$loop.schedule(this.CHANGE_FULL);
- };
- this.updateFontSize = function() {
- this.$textLayer.checkForSizeChanges();
- };
-
- this.$changes = 0;
- this.$updateSizeAsync = function() {
- if (this.$loop.pending)
- this.$size.$dirty = true;
- else
- this.onResize();
- };
- this.onResize = function(force, gutterWidth, width, height) {
- if (this.resizing > 2)
- return;
- else if (this.resizing > 0)
- this.resizing++;
- else
- this.resizing = force ? 1 : 0;
- var el = this.container;
- if (!height)
- height = el.clientHeight || el.scrollHeight;
- if (!width)
- width = el.clientWidth || el.scrollWidth;
- var changes = this.$updateCachedSize(force, gutterWidth, width, height);
-
-
- if (!this.$size.scrollerHeight || (!width && !height))
- return this.resizing = 0;
-
- if (force)
- this.$gutterLayer.$padding = null;
-
- if (force)
- this.$renderChanges(changes | this.$changes, true);
- else
- this.$loop.schedule(changes | this.$changes);
-
- if (this.resizing)
- this.resizing = 0;
- this.scrollBarV.scrollLeft = this.scrollBarV.scrollTop = null;
- };
-
- this.$updateCachedSize = function(force, gutterWidth, width, height) {
- height -= (this.$extraHeight || 0);
- var changes = 0;
- var size = this.$size;
- var oldSize = {
- width: size.width,
- height: size.height,
- scrollerHeight: size.scrollerHeight,
- scrollerWidth: size.scrollerWidth
- };
- if (height && (force || size.height != height)) {
- size.height = height;
- changes |= this.CHANGE_SIZE;
-
- size.scrollerHeight = size.height;
- if (this.$horizScroll)
- size.scrollerHeight -= this.scrollBarH.getHeight();
- this.scrollBarV.element.style.bottom = this.scrollBarH.getHeight() + "px";
-
- changes = changes | this.CHANGE_SCROLL;
- }
-
- if (width && (force || size.width != width)) {
- changes |= this.CHANGE_SIZE;
- size.width = width;
-
- if (gutterWidth == null)
- gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0;
-
- this.gutterWidth = gutterWidth;
-
- this.scrollBarH.element.style.left =
- this.scroller.style.left = gutterWidth + "px";
- size.scrollerWidth = Math.max(0, width - gutterWidth - this.scrollBarV.getWidth());
-
- this.scrollBarH.element.style.right =
- this.scroller.style.right = this.scrollBarV.getWidth() + "px";
- this.scroller.style.bottom = this.scrollBarH.getHeight() + "px";
-
- if (this.session && this.session.getUseWrapMode() && this.adjustWrapLimit() || force)
- changes |= this.CHANGE_FULL;
- }
-
- size.$dirty = !width || !height;
-
- if (changes)
- this._signal("resize", oldSize);
-
- return changes;
- };
-
- this.onGutterResize = function() {
- var gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0;
- if (gutterWidth != this.gutterWidth)
- this.$changes |= this.$updateCachedSize(true, gutterWidth, this.$size.width, this.$size.height);
-
- if (this.session.getUseWrapMode() && this.adjustWrapLimit()) {
- this.$loop.schedule(this.CHANGE_FULL);
- } else if (this.$size.$dirty) {
- this.$loop.schedule(this.CHANGE_FULL);
- } else {
- this.$computeLayerConfig();
- this.$loop.schedule(this.CHANGE_MARKER);
- }
- };
- this.adjustWrapLimit = function() {
- var availableWidth = this.$size.scrollerWidth - this.$padding * 2;
- var limit = Math.floor(availableWidth / this.characterWidth);
- return this.session.adjustWrapLimit(limit, this.$showPrintMargin && this.$printMarginColumn);
- };
- this.setAnimatedScroll = function(shouldAnimate){
- this.setOption("animatedScroll", shouldAnimate);
- };
- this.getAnimatedScroll = function() {
- return this.$animatedScroll;
- };
- this.setShowInvisibles = function(showInvisibles) {
- this.setOption("showInvisibles", showInvisibles);
- };
- this.getShowInvisibles = function() {
- return this.getOption("showInvisibles");
- };
- this.getDisplayIndentGuides = function() {
- return this.getOption("displayIndentGuides");
- };
-
- this.setDisplayIndentGuides = function(display) {
- this.setOption("displayIndentGuides", display);
- };
- this.setShowPrintMargin = function(showPrintMargin) {
- this.setOption("showPrintMargin", showPrintMargin);
- };
- this.getShowPrintMargin = function() {
- return this.getOption("showPrintMargin");
- };
- this.setPrintMarginColumn = function(showPrintMargin) {
- this.setOption("printMarginColumn", showPrintMargin);
- };
- this.getPrintMarginColumn = function() {
- return this.getOption("printMarginColumn");
- };
- this.getShowGutter = function(){
- return this.getOption("showGutter");
- };
- this.setShowGutter = function(show){
- return this.setOption("showGutter", show);
- };
-
- this.getFadeFoldWidgets = function(){
- return this.getOption("fadeFoldWidgets")
- };
-
- this.setFadeFoldWidgets = function(show) {
- this.setOption("fadeFoldWidgets", show);
- };
-
- this.setHighlightGutterLine = function(shouldHighlight) {
- this.setOption("highlightGutterLine", shouldHighlight);
- };
-
- this.getHighlightGutterLine = function() {
- return this.getOption("highlightGutterLine");
- };
-
- this.$updateGutterLineHighlight = function() {
- var pos = this.$cursorLayer.$pixelPos;
- var height = this.layerConfig.lineHeight;
- if (this.session.getUseWrapMode()) {
- var cursor = this.session.selection.getCursor();
- cursor.column = 0;
- pos = this.$cursorLayer.getPixelPosition(cursor, true);
- height *= this.session.getRowLength(cursor.row);
- }
- this.$gutterLineHighlight.style.top = pos.top - this.layerConfig.offset + "px";
- this.$gutterLineHighlight.style.height = height + "px";
- };
-
- this.$updatePrintMargin = function() {
- if (!this.$showPrintMargin && !this.$printMarginEl)
- return;
-
- if (!this.$printMarginEl) {
- var containerEl = dom.createElement("div");
- containerEl.className = "ace_layer ace_print-margin-layer";
- this.$printMarginEl = dom.createElement("div");
- this.$printMarginEl.className = "ace_print-margin";
- containerEl.appendChild(this.$printMarginEl);
- this.content.insertBefore(containerEl, this.content.firstChild);
- }
-
- var style = this.$printMarginEl.style;
- style.left = ((this.characterWidth * this.$printMarginColumn) + this.$padding) + "px";
- style.visibility = this.$showPrintMargin ? "visible" : "hidden";
-
- if (this.session && this.session.$wrap == -1)
- this.adjustWrapLimit();
- };
- this.getContainerElement = function() {
- return this.container;
- };
- this.getMouseEventTarget = function() {
- return this.scroller;
- };
- this.getTextAreaContainer = function() {
- return this.container;
- };
- this.$moveTextAreaToCursor = function() {
- if (!this.$keepTextAreaAtCursor)
- return;
- var config = this.layerConfig;
- var posTop = this.$cursorLayer.$pixelPos.top;
- var posLeft = this.$cursorLayer.$pixelPos.left;
- posTop -= config.offset;
-
- var style = this.textarea.style;
- var h = this.lineHeight;
- if (posTop < 0 || posTop > config.height - h) {
- style.top = style.left = "0";
- return;
- }
-
- var w = this.characterWidth;
- if (this.$composition) {
- var val = this.textarea.value.replace(/^\x01+/, "");
- w *= (this.session.$getStringScreenWidth(val)[0]+2);
- h += 2;
- }
- posLeft -= this.scrollLeft;
- if (posLeft > this.$size.scrollerWidth - w)
- posLeft = this.$size.scrollerWidth - w;
-
- posLeft += this.gutterWidth;
- style.height = h + "px";
- style.width = w + "px";
- style.left = Math.min(posLeft, this.$size.scrollerWidth - w) + "px";
- style.top = Math.min(posTop, this.$size.height - h) + "px";
- };
- this.getFirstVisibleRow = function() {
- return this.layerConfig.firstRow;
- };
- this.getFirstFullyVisibleRow = function() {
- return this.layerConfig.firstRow + (this.layerConfig.offset === 0 ? 0 : 1);
- };
- this.getLastFullyVisibleRow = function() {
- var config = this.layerConfig;
- var lastRow = config.lastRow
- var top = this.session.documentToScreenRow(lastRow, 0) * config.lineHeight;
- if (top - this.session.getScrollTop() > config.height - config.lineHeight)
- return lastRow - 1;
- return lastRow;
- };
- this.getLastVisibleRow = function() {
- return this.layerConfig.lastRow;
- };
-
- this.$padding = null;
- this.setPadding = function(padding) {
- this.$padding = padding;
- this.$textLayer.setPadding(padding);
- this.$cursorLayer.setPadding(padding);
- this.$markerFront.setPadding(padding);
- this.$markerBack.setPadding(padding);
- this.$loop.schedule(this.CHANGE_FULL);
- this.$updatePrintMargin();
- };
-
- this.setScrollMargin = function(top, bottom, left, right) {
- var sm = this.scrollMargin;
- sm.top = top|0;
- sm.bottom = bottom|0;
- sm.right = right|0;
- sm.left = left|0;
- sm.v = sm.top + sm.bottom;
- sm.h = sm.left + sm.right;
- if (sm.top && this.scrollTop <= 0 && this.session)
- this.session.setScrollTop(-sm.top);
- this.updateFull();
- };
- this.getHScrollBarAlwaysVisible = function() {
- return this.$hScrollBarAlwaysVisible;
- };
- this.setHScrollBarAlwaysVisible = function(alwaysVisible) {
- this.setOption("hScrollBarAlwaysVisible", alwaysVisible);
- };
- this.getVScrollBarAlwaysVisible = function() {
- return this.$vScrollBarAlwaysVisible;
- };
- this.setVScrollBarAlwaysVisible = function(alwaysVisible) {
- this.setOption("vScrollBarAlwaysVisible", alwaysVisible);
- };
-
- this.$updateScrollBarV = function() {
- var scrollHeight = this.layerConfig.maxHeight;
- var scrollerHeight = this.$size.scrollerHeight;
- if (!this.$maxLines && this.$scrollPastEnd) {
- scrollHeight -= (scrollerHeight - this.lineHeight) * this.$scrollPastEnd;
- if (this.scrollTop > scrollHeight - scrollerHeight) {
- scrollHeight = this.scrollTop + scrollerHeight;
- this.scrollBarV.scrollTop = null;
- }
- }
- this.scrollBarV.setScrollHeight(scrollHeight + this.scrollMargin.v);
- this.scrollBarV.setScrollTop(this.scrollTop + this.scrollMargin.top);
- };
- this.$updateScrollBarH = function() {
- this.scrollBarH.setScrollWidth(this.layerConfig.width + 2 * this.$padding + this.scrollMargin.h);
- this.scrollBarH.setScrollLeft(this.scrollLeft + this.scrollMargin.left);
- };
-
- this.$frozen = false;
- this.freeze = function() {
- this.$frozen = true;
- };
-
- this.unfreeze = function() {
- this.$frozen = false;
- };
-
- this.$renderChanges = function(changes, force) {
- if (this.$changes) {
- changes |= this.$changes;
- this.$changes = 0;
- }
- if ((!this.session || !this.container.offsetWidth || this.$frozen) || (!changes && !force)) {
- this.$changes |= changes;
- return;
- }
- if (this.$size.$dirty) {
- this.$changes |= changes;
- return this.onResize(true);
- }
- if (!this.lineHeight) {
- this.$textLayer.checkForSizeChanges();
- }
-
- this._signal("beforeRender");
- var config = this.layerConfig;
- if (changes & this.CHANGE_FULL ||
- changes & this.CHANGE_SIZE ||
- changes & this.CHANGE_TEXT ||
- changes & this.CHANGE_LINES ||
- changes & this.CHANGE_SCROLL ||
- changes & this.CHANGE_H_SCROLL
- ) {
- changes |= this.$computeLayerConfig();
- if (config.firstRow != this.layerConfig.firstRow && config.firstRowScreen == this.layerConfig.firstRowScreen) {
- var st = this.scrollTop + (config.firstRow - this.layerConfig.firstRow) * this.lineHeight;
- if (st > 0) {
- this.scrollTop = st;
- changes = changes | this.CHANGE_SCROLL;
- changes |= this.$computeLayerConfig();
- }
- }
- config = this.layerConfig;
- this.$updateScrollBarV();
- if (changes & this.CHANGE_H_SCROLL)
- this.$updateScrollBarH();
- this.$gutterLayer.element.style.marginTop = (-config.offset) + "px";
- this.content.style.marginTop = (-config.offset) + "px";
- this.content.style.width = config.width + 2 * this.$padding + "px";
- this.content.style.height = config.minHeight + "px";
- }
- if (changes & this.CHANGE_H_SCROLL) {
- this.content.style.marginLeft = -this.scrollLeft + "px";
- this.scroller.className = this.scrollLeft <= 0 ? "ace_scroller" : "ace_scroller ace_scroll-left";
- }
- if (changes & this.CHANGE_FULL) {
- this.$textLayer.update(config);
- if (this.$showGutter)
- this.$gutterLayer.update(config);
- this.$markerBack.update(config);
- this.$markerFront.update(config);
- this.$cursorLayer.update(config);
- this.$moveTextAreaToCursor();
- this.$highlightGutterLine && this.$updateGutterLineHighlight();
- this._signal("afterRender");
- return;
- }
- if (changes & this.CHANGE_SCROLL) {
- if (changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES)
- this.$textLayer.update(config);
- else
- this.$textLayer.scrollLines(config);
-
- if (this.$showGutter)
- this.$gutterLayer.update(config);
- this.$markerBack.update(config);
- this.$markerFront.update(config);
- this.$cursorLayer.update(config);
- this.$highlightGutterLine && this.$updateGutterLineHighlight();
- this.$moveTextAreaToCursor();
- this._signal("afterRender");
- return;
- }
-
- if (changes & this.CHANGE_TEXT) {
- this.$textLayer.update(config);
- if (this.$showGutter)
- this.$gutterLayer.update(config);
- }
- else if (changes & this.CHANGE_LINES) {
- if (this.$updateLines() || (changes & this.CHANGE_GUTTER) && this.$showGutter)
- this.$gutterLayer.update(config);
- }
- else if (changes & this.CHANGE_TEXT || changes & this.CHANGE_GUTTER) {
- if (this.$showGutter)
- this.$gutterLayer.update(config);
- }
-
- if (changes & this.CHANGE_CURSOR) {
- this.$cursorLayer.update(config);
- this.$moveTextAreaToCursor();
- this.$highlightGutterLine && this.$updateGutterLineHighlight();
- }
-
- if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_FRONT)) {
- this.$markerFront.update(config);
- }
-
- if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_BACK)) {
- this.$markerBack.update(config);
- }
-
- this._signal("afterRender");
- };
-
-
- this.$autosize = function() {
- var height = this.session.getScreenLength() * this.lineHeight;
- var maxHeight = this.$maxLines * this.lineHeight;
- var desiredHeight = Math.max(
- (this.$minLines||1) * this.lineHeight,
- Math.min(maxHeight, height)
- ) + this.scrollMargin.v + (this.$extraHeight || 0);
- if (this.$horizScroll)
- desiredHeight += this.scrollBarH.getHeight();
- var vScroll = height > maxHeight;
-
- if (desiredHeight != this.desiredHeight ||
- this.$size.height != this.desiredHeight || vScroll != this.$vScroll) {
- if (vScroll != this.$vScroll) {
- this.$vScroll = vScroll;
- this.scrollBarV.setVisible(vScroll);
- }
-
- var w = this.container.clientWidth;
- this.container.style.height = desiredHeight + "px";
- this.$updateCachedSize(true, this.$gutterWidth, w, desiredHeight);
- this.desiredHeight = desiredHeight;
-
- this._signal("autosize");
- }
- };
-
- this.$computeLayerConfig = function() {
- var session = this.session;
- var size = this.$size;
-
- var hideScrollbars = size.height <= 2 * this.lineHeight;
- var screenLines = this.session.getScreenLength();
- var maxHeight = screenLines * this.lineHeight;
-
- var longestLine = this.$getLongestLine();
-
- var horizScroll = !hideScrollbars && (this.$hScrollBarAlwaysVisible ||
- size.scrollerWidth - longestLine - 2 * this.$padding < 0);
-
- var hScrollChanged = this.$horizScroll !== horizScroll;
- if (hScrollChanged) {
- this.$horizScroll = horizScroll;
- this.scrollBarH.setVisible(horizScroll);
- }
- var vScrollBefore = this.$vScroll; // autosize can change vscroll value in which case we need to update longestLine
- if (this.$maxLines && this.lineHeight > 1)
- this.$autosize();
-
- var offset = this.scrollTop % this.lineHeight;
- var minHeight = size.scrollerHeight + this.lineHeight;
-
- var scrollPastEnd = !this.$maxLines && this.$scrollPastEnd
- ? (size.scrollerHeight - this.lineHeight) * this.$scrollPastEnd
- : 0;
- maxHeight += scrollPastEnd;
-
- var sm = this.scrollMargin;
- this.session.setScrollTop(Math.max(-sm.top,
- Math.min(this.scrollTop, maxHeight - size.scrollerHeight + sm.bottom)));
-
- this.session.setScrollLeft(Math.max(-sm.left, Math.min(this.scrollLeft,
- longestLine + 2 * this.$padding - size.scrollerWidth + sm.right)));
-
- var vScroll = !hideScrollbars && (this.$vScrollBarAlwaysVisible ||
- size.scrollerHeight - maxHeight + scrollPastEnd < 0 || this.scrollTop > sm.top);
- var vScrollChanged = vScrollBefore !== vScroll;
- if (vScrollChanged) {
- this.$vScroll = vScroll;
- this.scrollBarV.setVisible(vScroll);
- }
-
- var lineCount = Math.ceil(minHeight / this.lineHeight) - 1;
- var firstRow = Math.max(0, Math.round((this.scrollTop - offset) / this.lineHeight));
- var lastRow = firstRow + lineCount;
- var firstRowScreen, firstRowHeight;
- var lineHeight = this.lineHeight;
- firstRow = session.screenToDocumentRow(firstRow, 0);
- var foldLine = session.getFoldLine(firstRow);
- if (foldLine) {
- firstRow = foldLine.start.row;
- }
-
- firstRowScreen = session.documentToScreenRow(firstRow, 0);
- firstRowHeight = session.getRowLength(firstRow) * lineHeight;
-
- lastRow = Math.min(session.screenToDocumentRow(lastRow, 0), session.getLength() - 1);
- minHeight = size.scrollerHeight + session.getRowLength(lastRow) * lineHeight +
- firstRowHeight;
-
- offset = this.scrollTop - firstRowScreen * lineHeight;
-
- var changes = 0;
- if (this.layerConfig.width != longestLine)
- changes = this.CHANGE_H_SCROLL;
- if (hScrollChanged || vScrollChanged) {
- changes = this.$updateCachedSize(true, this.gutterWidth, size.width, size.height);
- this._signal("scrollbarVisibilityChanged");
- if (vScrollChanged)
- longestLine = this.$getLongestLine();
- }
-
- this.layerConfig = {
- width : longestLine,
- padding : this.$padding,
- firstRow : firstRow,
- firstRowScreen: firstRowScreen,
- lastRow : lastRow,
- lineHeight : lineHeight,
- characterWidth : this.characterWidth,
- minHeight : minHeight,
- maxHeight : maxHeight,
- offset : offset,
- gutterOffset : Math.max(0, Math.ceil((offset + size.height - size.scrollerHeight) / lineHeight)),
- height : this.$size.scrollerHeight
- };
-
- return changes;
- };
-
- this.$updateLines = function() {
- var firstRow = this.$changedLines.firstRow;
- var lastRow = this.$changedLines.lastRow;
- this.$changedLines = null;
-
- var layerConfig = this.layerConfig;
-
- if (firstRow > layerConfig.lastRow + 1) { return; }
- if (lastRow < layerConfig.firstRow) { return; }
- if (lastRow === Infinity) {
- if (this.$showGutter)
- this.$gutterLayer.update(layerConfig);
- this.$textLayer.update(layerConfig);
- return;
- }
- this.$textLayer.updateLines(layerConfig, firstRow, lastRow);
- return true;
- };
-
- this.$getLongestLine = function() {
- var charCount = this.session.getScreenWidth();
- if (this.showInvisibles && !this.session.$useWrapMode)
- charCount += 1;
-
- return Math.max(this.$size.scrollerWidth - 2 * this.$padding, Math.round(charCount * this.characterWidth));
- };
- this.updateFrontMarkers = function() {
- this.$markerFront.setMarkers(this.session.getMarkers(true));
- this.$loop.schedule(this.CHANGE_MARKER_FRONT);
- };
- this.updateBackMarkers = function() {
- this.$markerBack.setMarkers(this.session.getMarkers());
- this.$loop.schedule(this.CHANGE_MARKER_BACK);
- };
- this.addGutterDecoration = function(row, className){
- this.$gutterLayer.addGutterDecoration(row, className);
- };
- this.removeGutterDecoration = function(row, className){
- this.$gutterLayer.removeGutterDecoration(row, className);
- };
- this.updateBreakpoints = function(rows) {
- this.$loop.schedule(this.CHANGE_GUTTER);
- };
- this.setAnnotations = function(annotations) {
- this.$gutterLayer.setAnnotations(annotations);
- this.$loop.schedule(this.CHANGE_GUTTER);
- };
- this.updateCursor = function() {
- this.$loop.schedule(this.CHANGE_CURSOR);
- };
- this.hideCursor = function() {
- this.$cursorLayer.hideCursor();
- };
- this.showCursor = function() {
- this.$cursorLayer.showCursor();
- };
-
- this.scrollSelectionIntoView = function(anchor, lead, offset) {
- this.scrollCursorIntoView(anchor, offset);
- this.scrollCursorIntoView(lead, offset);
- };
- this.scrollCursorIntoView = function(cursor, offset, $viewMargin) {
- if (this.$size.scrollerHeight === 0)
- return;
-
- var pos = this.$cursorLayer.getPixelPosition(cursor);
-
- var left = pos.left;
- var top = pos.top;
-
- var topMargin = $viewMargin && $viewMargin.top || 0;
- var bottomMargin = $viewMargin && $viewMargin.bottom || 0;
-
- var scrollTop = this.$scrollAnimation ? this.session.getScrollTop() : this.scrollTop;
-
- if (scrollTop + topMargin > top) {
- if (offset && scrollTop + topMargin > top + this.lineHeight)
- top -= offset * this.$size.scrollerHeight;
- if (top === 0)
- top = -this.scrollMargin.top;
- this.session.setScrollTop(top);
- } else if (scrollTop + this.$size.scrollerHeight - bottomMargin < top + this.lineHeight) {
- if (offset && scrollTop + this.$size.scrollerHeight - bottomMargin < top - this.lineHeight)
- top += offset * this.$size.scrollerHeight;
- this.session.setScrollTop(top + this.lineHeight - this.$size.scrollerHeight);
- }
-
- var scrollLeft = this.scrollLeft;
-
- if (scrollLeft > left) {
- if (left < this.$padding + 2 * this.layerConfig.characterWidth)
- left = -this.scrollMargin.left;
- this.session.setScrollLeft(left);
- } else if (scrollLeft + this.$size.scrollerWidth < left + this.characterWidth) {
- this.session.setScrollLeft(Math.round(left + this.characterWidth - this.$size.scrollerWidth));
- } else if (scrollLeft <= this.$padding && left - scrollLeft < this.characterWidth) {
- this.session.setScrollLeft(0);
- }
- };
- this.getScrollTop = function() {
- return this.session.getScrollTop();
- };
- this.getScrollLeft = function() {
- return this.session.getScrollLeft();
- };
- this.getScrollTopRow = function() {
- return this.scrollTop / this.lineHeight;
- };
- this.getScrollBottomRow = function() {
- return Math.max(0, Math.floor((this.scrollTop + this.$size.scrollerHeight) / this.lineHeight) - 1);
- };
- this.scrollToRow = function(row) {
- this.session.setScrollTop(row * this.lineHeight);
- };
-
- this.alignCursor = function(cursor, alignment) {
- if (typeof cursor == "number")
- cursor = {row: cursor, column: 0};
-
- var pos = this.$cursorLayer.getPixelPosition(cursor);
- var h = this.$size.scrollerHeight - this.lineHeight;
- var offset = pos.top - h * (alignment || 0);
-
- this.session.setScrollTop(offset);
- return offset;
- };
-
- this.STEPS = 8;
- this.$calcSteps = function(fromValue, toValue){
- var i = 0;
- var l = this.STEPS;
- var steps = [];
-
- var func = function(t, x_min, dx) {
- return dx * (Math.pow(t - 1, 3) + 1) + x_min;
- };
-
- for (i = 0; i < l; ++i)
- steps.push(func(i / this.STEPS, fromValue, toValue - fromValue));
-
- return steps;
- };
- this.scrollToLine = function(line, center, animate, callback) {
- var pos = this.$cursorLayer.getPixelPosition({row: line, column: 0});
- var offset = pos.top;
- if (center)
- offset -= this.$size.scrollerHeight / 2;
-
- var initialScroll = this.scrollTop;
- this.session.setScrollTop(offset);
- if (animate !== false)
- this.animateScrolling(initialScroll, callback);
- };
-
- this.animateScrolling = function(fromValue, callback) {
- var toValue = this.scrollTop;
- if (!this.$animatedScroll)
- return;
- var _self = this;
-
- if (fromValue == toValue)
- return;
-
- if (this.$scrollAnimation) {
- var oldSteps = this.$scrollAnimation.steps;
- if (oldSteps.length) {
- fromValue = oldSteps[0];
- if (fromValue == toValue)
- return;
- }
- }
-
- var steps = _self.$calcSteps(fromValue, toValue);
- this.$scrollAnimation = {from: fromValue, to: toValue, steps: steps};
-
- clearInterval(this.$timer);
-
- _self.session.setScrollTop(steps.shift());
- _self.session.$scrollTop = toValue;
- this.$timer = setInterval(function() {
- if (steps.length) {
- _self.session.setScrollTop(steps.shift());
- _self.session.$scrollTop = toValue;
- } else if (toValue != null) {
- _self.session.$scrollTop = -1;
- _self.session.setScrollTop(toValue);
- toValue = null;
- } else {
- _self.$timer = clearInterval(_self.$timer);
- _self.$scrollAnimation = null;
- callback && callback();
- }
- }, 10);
- };
- this.scrollToY = function(scrollTop) {
- if (this.scrollTop !== scrollTop) {
- this.$loop.schedule(this.CHANGE_SCROLL);
- this.scrollTop = scrollTop;
- }
- };
- this.scrollToX = function(scrollLeft) {
- if (this.scrollLeft !== scrollLeft)
- this.scrollLeft = scrollLeft;
- this.$loop.schedule(this.CHANGE_H_SCROLL);
- };
- this.scrollTo = function(x, y) {
- this.session.setScrollTop(y);
- this.session.setScrollLeft(y);
- };
- this.scrollBy = function(deltaX, deltaY) {
- deltaY && this.session.setScrollTop(this.session.getScrollTop() + deltaY);
- deltaX && this.session.setScrollLeft(this.session.getScrollLeft() + deltaX);
- };
- this.isScrollableBy = function(deltaX, deltaY) {
- if (deltaY < 0 && this.session.getScrollTop() >= 1 - this.scrollMargin.top)
- return true;
- if (deltaY > 0 && this.session.getScrollTop() + this.$size.scrollerHeight
- - this.layerConfig.maxHeight < -1 + this.scrollMargin.bottom)
- return true;
- if (deltaX < 0 && this.session.getScrollLeft() >= 1 - this.scrollMargin.left)
- return true;
- if (deltaX > 0 && this.session.getScrollLeft() + this.$size.scrollerWidth
- - this.layerConfig.width < -1 + this.scrollMargin.right)
- return true;
- };
-
- this.pixelToScreenCoordinates = function(x, y) {
- var canvasPos = this.scroller.getBoundingClientRect();
-
- var offset = (x + this.scrollLeft - canvasPos.left - this.$padding) / this.characterWidth;
- var row = Math.floor((y + this.scrollTop - canvasPos.top) / this.lineHeight);
- var col = Math.round(offset);
-
- return {row: row, column: col, side: offset - col > 0 ? 1 : -1};
- };
-
- this.screenToTextCoordinates = function(x, y) {
- var canvasPos = this.scroller.getBoundingClientRect();
-
- var col = Math.round(
- (x + this.scrollLeft - canvasPos.left - this.$padding) / this.characterWidth
- );
-
- var row = (y + this.scrollTop - canvasPos.top) / this.lineHeight;
-
- return this.session.screenToDocumentPosition(row, Math.max(col, 0));
- };
- this.textToScreenCoordinates = function(row, column) {
- var canvasPos = this.scroller.getBoundingClientRect();
- var pos = this.session.documentToScreenPosition(row, column);
-
- var x = this.$padding + Math.round(pos.column * this.characterWidth);
- var y = pos.row * this.lineHeight;
-
- return {
- pageX: canvasPos.left + x - this.scrollLeft,
- pageY: canvasPos.top + y - this.scrollTop
- };
- };
- this.visualizeFocus = function() {
- dom.addCssClass(this.container, "ace_focus");
- };
- this.visualizeBlur = function() {
- dom.removeCssClass(this.container, "ace_focus");
- };
- this.showComposition = function(position) {
- if (!this.$composition)
- this.$composition = {
- keepTextAreaAtCursor: this.$keepTextAreaAtCursor,
- cssText: this.textarea.style.cssText
- };
-
- this.$keepTextAreaAtCursor = true;
- dom.addCssClass(this.textarea, "ace_composition");
- this.textarea.style.cssText = "";
- this.$moveTextAreaToCursor();
- };
- this.setCompositionText = function(text) {
- this.$moveTextAreaToCursor();
- };
- this.hideComposition = function() {
- if (!this.$composition)
- return;
-
- dom.removeCssClass(this.textarea, "ace_composition");
- this.$keepTextAreaAtCursor = this.$composition.keepTextAreaAtCursor;
- this.textarea.style.cssText = this.$composition.cssText;
- this.$composition = null;
- };
- this.setTheme = function(theme, cb) {
- var _self = this;
- this.$themeId = theme;
- _self._dispatchEvent('themeChange',{theme:theme});
-
- if (!theme || typeof theme == "string") {
- var moduleName = theme || this.$options.theme.initialValue;
- config.loadModule(["theme", moduleName], afterLoad);
- } else {
- afterLoad(theme);
- }
-
- function afterLoad(module) {
- if (_self.$themeId != theme)
- return cb && cb();
- if (!module.cssClass)
- return;
- dom.importCssString(
- module.cssText,
- module.cssClass,
- _self.container.ownerDocument
- );
-
- if (_self.theme)
- dom.removeCssClass(_self.container, _self.theme.cssClass);
-
- var padding = "padding" in module ? module.padding
- : "padding" in (_self.theme || {}) ? 4 : _self.$padding;
- if (_self.$padding && padding != _self.$padding)
- _self.setPadding(padding);
- _self.$theme = module.cssClass;
-
- _self.theme = module;
- dom.addCssClass(_self.container, module.cssClass);
- dom.setCssClass(_self.container, "ace_dark", module.isDark);
- if (_self.$size) {
- _self.$size.width = 0;
- _self.$updateSizeAsync();
- }
-
- _self._dispatchEvent('themeLoaded', {theme:module});
- cb && cb();
- }
- };
- this.getTheme = function() {
- return this.$themeId;
- };
- this.setStyle = function(style, include) {
- dom.setCssClass(this.container, style, include !== false);
- };
- this.unsetStyle = function(style) {
- dom.removeCssClass(this.container, style);
- };
-
- this.setCursorStyle = function(style) {
- if (this.scroller.style.cursor != style)
- this.scroller.style.cursor = style;
- };
- this.setMouseCursor = function(cursorStyle) {
- this.scroller.style.cursor = cursorStyle;
- };
- this.destroy = function() {
- this.$textLayer.destroy();
- this.$cursorLayer.destroy();
- };
-
-}).call(VirtualRenderer.prototype);
-
-
-config.defineOptions(VirtualRenderer.prototype, "renderer", {
- animatedScroll: {initialValue: false},
- showInvisibles: {
- set: function(value) {
- if (this.$textLayer.setShowInvisibles(value))
- this.$loop.schedule(this.CHANGE_TEXT);
- },
- initialValue: false
- },
- showPrintMargin: {
- set: function() { this.$updatePrintMargin(); },
- initialValue: true
- },
- printMarginColumn: {
- set: function() { this.$updatePrintMargin(); },
- initialValue: 80
- },
- printMargin: {
- set: function(val) {
- if (typeof val == "number")
- this.$printMarginColumn = val;
- this.$showPrintMargin = !!val;
- this.$updatePrintMargin();
- },
- get: function() {
- return this.$showPrintMargin && this.$printMarginColumn;
- }
- },
- showGutter: {
- set: function(show){
- this.$gutter.style.display = show ? "block" : "none";
- this.$loop.schedule(this.CHANGE_FULL);
- this.onGutterResize();
- },
- initialValue: true
- },
- fadeFoldWidgets: {
- set: function(show) {
- dom.setCssClass(this.$gutter, "ace_fade-fold-widgets", show);
- },
- initialValue: false
- },
- showFoldWidgets: {
- set: function(show) {this.$gutterLayer.setShowFoldWidgets(show)},
- initialValue: true
- },
- showLineNumbers: {
- set: function(show) {
- this.$gutterLayer.setShowLineNumbers(show);
- this.$loop.schedule(this.CHANGE_GUTTER);
- },
- initialValue: true
- },
- displayIndentGuides: {
- set: function(show) {
- if (this.$textLayer.setDisplayIndentGuides(show))
- this.$loop.schedule(this.CHANGE_TEXT);
- },
- initialValue: true
- },
- highlightGutterLine: {
- set: function(shouldHighlight) {
- if (!this.$gutterLineHighlight) {
- this.$gutterLineHighlight = dom.createElement("div");
- this.$gutterLineHighlight.className = "ace_gutter-active-line";
- this.$gutter.appendChild(this.$gutterLineHighlight);
- return;
- }
-
- this.$gutterLineHighlight.style.display = shouldHighlight ? "" : "none";
- if (this.$cursorLayer.$pixelPos)
- this.$updateGutterLineHighlight();
- },
- initialValue: false,
- value: true
- },
- hScrollBarAlwaysVisible: {
- set: function(val) {
- if (!this.$hScrollBarAlwaysVisible || !this.$horizScroll)
- this.$loop.schedule(this.CHANGE_SCROLL);
- },
- initialValue: false
- },
- vScrollBarAlwaysVisible: {
- set: function(val) {
- if (!this.$vScrollBarAlwaysVisible || !this.$vScroll)
- this.$loop.schedule(this.CHANGE_SCROLL);
- },
- initialValue: false
- },
- fontSize: {
- set: function(size) {
- if (typeof size == "number")
- size = size + "px";
- this.container.style.fontSize = size;
- this.updateFontSize();
- },
- initialValue: 12
- },
- fontFamily: {
- set: function(name) {
- this.container.style.fontFamily = name;
- this.updateFontSize();
- }
- },
- maxLines: {
- set: function(val) {
- this.updateFull();
- }
- },
- minLines: {
- set: function(val) {
- this.updateFull();
- }
- },
- scrollPastEnd: {
- set: function(val) {
- val = +val || 0;
- if (this.$scrollPastEnd == val)
- return;
- this.$scrollPastEnd = val;
- this.$loop.schedule(this.CHANGE_SCROLL);
- },
- initialValue: 0,
- handlesSet: true
- },
- fixedWidthGutter: {
- set: function(val) {
- this.$gutterLayer.$fixedWidth = !!val;
- this.$loop.schedule(this.CHANGE_GUTTER);
- }
- },
- theme: {
- set: function(val) { this.setTheme(val) },
- get: function() { return this.$themeId || this.theme; },
- initialValue: "./theme/textmate",
- handlesSet: true
- }
-});
-
-exports.VirtualRenderer = VirtualRenderer;
-});
-
-ace.define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/net","ace/lib/event_emitter","ace/config"], function(require, exports, module) {
-"use strict";
-
-var oop = require("../lib/oop");
-var net = require("../lib/net");
-var EventEmitter = require("../lib/event_emitter").EventEmitter;
-var config = require("../config");
-
-var WorkerClient = function(topLevelNamespaces, mod, classname, workerUrl) {
- this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this);
- this.changeListener = this.changeListener.bind(this);
- this.onMessage = this.onMessage.bind(this);
- if (require.nameToUrl && !require.toUrl)
- require.toUrl = require.nameToUrl;
-
- if (config.get("packaged") || !require.toUrl) {
- workerUrl = workerUrl || config.moduleUrl(mod, "worker");
- } else {
- var normalizePath = this.$normalizePath;
- workerUrl = workerUrl || normalizePath(require.toUrl("ace/worker/worker.js", null, "_"));
-
- var tlns = {};
- topLevelNamespaces.forEach(function(ns) {
- tlns[ns] = normalizePath(require.toUrl(ns, null, "_").replace(/(\.js)?(\?.*)?$/, ""));
- });
- }
-
- try {
- this.$worker = new Worker(workerUrl);
- } catch(e) {
- if (e instanceof window.DOMException) {
- var blob = this.$workerBlob(workerUrl);
- var URL = window.URL || window.webkitURL;
- var blobURL = URL.createObjectURL(blob);
-
- this.$worker = new Worker(blobURL);
- URL.revokeObjectURL(blobURL);
- } else {
- throw e;
- }
- }
- this.$worker.postMessage({
- init : true,
- tlns : tlns,
- module : mod,
- classname : classname
- });
-
- this.callbackId = 1;
- this.callbacks = {};
-
- this.$worker.onmessage = this.onMessage;
-};
-
-(function(){
-
- oop.implement(this, EventEmitter);
-
- this.onMessage = function(e) {
- var msg = e.data;
- switch(msg.type) {
- case "event":
- this._signal(msg.name, {data: msg.data});
- break;
- case "call":
- var callback = this.callbacks[msg.id];
- if (callback) {
- callback(msg.data);
- delete this.callbacks[msg.id];
- }
- break;
- case "error":
- this.reportError(msg.data);
- break;
- case "log":
- window.console && console.log && console.log.apply(console, msg.data);
- break;
- }
- };
-
- this.reportError = function(err) {
- window.console && console.error && console.error(err);
- };
-
- this.$normalizePath = function(path) {
- return net.qualifyURL(path);
- };
-
- this.terminate = function() {
- this._signal("terminate", {});
- this.deltaQueue = null;
- this.$worker.terminate();
- this.$worker = null;
- if (this.$doc)
- this.$doc.off("change", this.changeListener);
- this.$doc = null;
- };
-
- this.send = function(cmd, args) {
- this.$worker.postMessage({command: cmd, args: args});
- };
-
- this.call = function(cmd, args, callback) {
- if (callback) {
- var id = this.callbackId++;
- this.callbacks[id] = callback;
- args.push(id);
- }
- this.send(cmd, args);
- };
-
- this.emit = function(event, data) {
- try {
- this.$worker.postMessage({event: event, data: {data: data.data}});
- }
- catch(ex) {
- console.error(ex.stack);
- }
- };
-
- this.attachToDocument = function(doc) {
- if(this.$doc)
- this.terminate();
-
- this.$doc = doc;
- this.call("setValue", [doc.getValue()]);
- doc.on("change", this.changeListener);
- };
-
- this.changeListener = function(delta) {
- if (!this.deltaQueue) {
- this.deltaQueue = [];
- setTimeout(this.$sendDeltaQueue, 0);
- }
- if (delta.action == "insert")
- this.deltaQueue.push(delta.start, delta.lines);
- else
- this.deltaQueue.push(delta.start, delta.end);
- };
-
- this.$sendDeltaQueue = function() {
- var q = this.deltaQueue;
- if (!q) return;
- this.deltaQueue = null;
- if (q.length > 50 && q.length > this.$doc.getLength() >> 1) {
- this.call("setValue", [this.$doc.getValue()]);
- } else
- this.emit("change", {data: q});
- };
-
- this.$workerBlob = function(workerUrl) {
- var script = "importScripts('" + net.qualifyURL(workerUrl) + "');";
- try {
- return new Blob([script], {"type": "application/javascript"});
- } catch (e) { // Backwards-compatibility
- var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
- var blobBuilder = new BlobBuilder();
- blobBuilder.append(script);
- return blobBuilder.getBlob("application/javascript");
- }
- };
-
-}).call(WorkerClient.prototype);
-
-
-var UIWorkerClient = function(topLevelNamespaces, mod, classname) {
- this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this);
- this.changeListener = this.changeListener.bind(this);
- this.callbackId = 1;
- this.callbacks = {};
- this.messageBuffer = [];
-
- var main = null;
- var emitSync = false;
- var sender = Object.create(EventEmitter);
- var _self = this;
-
- this.$worker = {};
- this.$worker.terminate = function() {};
- this.$worker.postMessage = function(e) {
- _self.messageBuffer.push(e);
- if (main) {
- if (emitSync)
- setTimeout(processNext);
- else
- processNext();
- }
- };
- this.setEmitSync = function(val) { emitSync = val };
-
- var processNext = function() {
- var msg = _self.messageBuffer.shift();
- if (msg.command)
- main[msg.command].apply(main, msg.args);
- else if (msg.event)
- sender._signal(msg.event, msg.data);
- };
-
- sender.postMessage = function(msg) {
- _self.onMessage({data: msg});
- };
- sender.callback = function(data, callbackId) {
- this.postMessage({type: "call", id: callbackId, data: data});
- };
- sender.emit = function(name, data) {
- this.postMessage({type: "event", name: name, data: data});
- };
-
- config.loadModule(["worker", mod], function(Main) {
- main = new Main[classname](sender);
- while (_self.messageBuffer.length)
- processNext();
- });
-};
-
-UIWorkerClient.prototype = WorkerClient.prototype;
-
-exports.UIWorkerClient = UIWorkerClient;
-exports.WorkerClient = WorkerClient;
-
-});
-
-ace.define("ace/placeholder",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/oop"], function(require, exports, module) {
-"use strict";
-
-var Range = require("./range").Range;
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-var oop = require("./lib/oop");
-
-var PlaceHolder = function(session, length, pos, others, mainClass, othersClass) {
- var _self = this;
- this.length = length;
- this.session = session;
- this.doc = session.getDocument();
- this.mainClass = mainClass;
- this.othersClass = othersClass;
- this.$onUpdate = this.onUpdate.bind(this);
- this.doc.on("change", this.$onUpdate);
- this.$others = others;
-
- this.$onCursorChange = function() {
- setTimeout(function() {
- _self.onCursorChange();
- });
- };
-
- this.$pos = pos;
- var undoStack = session.getUndoManager().$undoStack || session.getUndoManager().$undostack || {length: -1};
- this.$undoStackDepth = undoStack.length;
- this.setup();
-
- session.selection.on("changeCursor", this.$onCursorChange);
-};
-
-(function() {
-
- oop.implement(this, EventEmitter);
- this.setup = function() {
- var _self = this;
- var doc = this.doc;
- var session = this.session;
-
- this.selectionBefore = session.selection.toJSON();
- if (session.selection.inMultiSelectMode)
- session.selection.toSingleRange();
-
- this.pos = doc.createAnchor(this.$pos.row, this.$pos.column);
- var pos = this.pos;
- pos.$insertRight = true;
- pos.detach();
- pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column + this.length), this.mainClass, null, false);
- this.others = [];
- this.$others.forEach(function(other) {
- var anchor = doc.createAnchor(other.row, other.column);
- anchor.$insertRight = true;
- anchor.detach();
- _self.others.push(anchor);
- });
- session.setUndoSelect(false);
- };
- this.showOtherMarkers = function() {
- if (this.othersActive) return;
- var session = this.session;
- var _self = this;
- this.othersActive = true;
- this.others.forEach(function(anchor) {
- anchor.markerId = session.addMarker(new Range(anchor.row, anchor.column, anchor.row, anchor.column+_self.length), _self.othersClass, null, false);
- });
- };
- this.hideOtherMarkers = function() {
- if (!this.othersActive) return;
- this.othersActive = false;
- for (var i = 0; i < this.others.length; i++) {
- this.session.removeMarker(this.others[i].markerId);
- }
- };
- this.onUpdate = function(delta) {
- if (this.$updating)
- return this.updateAnchors(delta);
-
- var range = delta;
- if (range.start.row !== range.end.row) return;
- if (range.start.row !== this.pos.row) return;
- this.$updating = true;
- var lengthDiff = delta.action === "insert" ? range.end.column - range.start.column : range.start.column - range.end.column;
- var inMainRange = range.start.column >= this.pos.column && range.start.column <= this.pos.column + this.length + 1;
- var distanceFromStart = range.start.column - this.pos.column;
-
- this.updateAnchors(delta);
-
- if (inMainRange)
- this.length += lengthDiff;
-
- if (inMainRange && !this.session.$fromUndo) {
- if (delta.action === 'insert') {
- for (var i = this.others.length - 1; i >= 0; i--) {
- var otherPos = this.others[i];
- var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart};
- this.doc.insertMergedLines(newPos, delta.lines);
- }
- } else if (delta.action === 'remove') {
- for (var i = this.others.length - 1; i >= 0; i--) {
- var otherPos = this.others[i];
- var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart};
- this.doc.remove(new Range(newPos.row, newPos.column, newPos.row, newPos.column - lengthDiff));
- }
- }
- }
-
- this.$updating = false;
- this.updateMarkers();
- };
-
- this.updateAnchors = function(delta) {
- this.pos.onChange(delta);
- for (var i = this.others.length; i--;)
- this.others[i].onChange(delta);
- this.updateMarkers();
- };
-
- this.updateMarkers = function() {
- if (this.$updating)
- return;
- var _self = this;
- var session = this.session;
- var updateMarker = function(pos, className) {
- session.removeMarker(pos.markerId);
- pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column+_self.length), className, null, false);
- };
- updateMarker(this.pos, this.mainClass);
- for (var i = this.others.length; i--;)
- updateMarker(this.others[i], this.othersClass);
- };
-
- this.onCursorChange = function(event) {
- if (this.$updating || !this.session) return;
- var pos = this.session.selection.getCursor();
- if (pos.row === this.pos.row && pos.column >= this.pos.column && pos.column <= this.pos.column + this.length) {
- this.showOtherMarkers();
- this._emit("cursorEnter", event);
- } else {
- this.hideOtherMarkers();
- this._emit("cursorLeave", event);
- }
- };
- this.detach = function() {
- this.session.removeMarker(this.pos && this.pos.markerId);
- this.hideOtherMarkers();
- this.doc.removeEventListener("change", this.$onUpdate);
- this.session.selection.removeEventListener("changeCursor", this.$onCursorChange);
- this.session.setUndoSelect(true);
- this.session = null;
- };
- this.cancel = function() {
- if (this.$undoStackDepth === -1)
- return;
- var undoManager = this.session.getUndoManager();
- var undosRequired = (undoManager.$undoStack || undoManager.$undostack).length - this.$undoStackDepth;
- for (var i = 0; i < undosRequired; i++) {
- undoManager.undo(true);
- }
- if (this.selectionBefore)
- this.session.selection.fromJSON(this.selectionBefore);
- };
-}).call(PlaceHolder.prototype);
-
-
-exports.PlaceHolder = PlaceHolder;
-});
-
-ace.define("ace/mouse/multi_select_handler",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(require, exports, module) {
-
-var event = require("../lib/event");
-var useragent = require("../lib/useragent");
-function isSamePoint(p1, p2) {
- return p1.row == p2.row && p1.column == p2.column;
-}
-
-function onMouseDown(e) {
- var ev = e.domEvent;
- var alt = ev.altKey;
- var shift = ev.shiftKey;
- var ctrl = ev.ctrlKey;
- var accel = e.getAccelKey();
- var button = e.getButton();
-
- if (ctrl && useragent.isMac)
- button = ev.button;
-
- if (e.editor.inMultiSelectMode && button == 2) {
- e.editor.textInput.onContextMenu(e.domEvent);
- return;
- }
-
- if (!ctrl && !alt && !accel) {
- if (button === 0 && e.editor.inMultiSelectMode)
- e.editor.exitMultiSelectMode();
- return;
- }
-
- if (button !== 0)
- return;
-
- var editor = e.editor;
- var selection = editor.selection;
- var isMultiSelect = editor.inMultiSelectMode;
- var pos = e.getDocumentPosition();
- var cursor = selection.getCursor();
- var inSelection = e.inSelection() || (selection.isEmpty() && isSamePoint(pos, cursor));
-
- var mouseX = e.x, mouseY = e.y;
- var onMouseSelection = function(e) {
- mouseX = e.clientX;
- mouseY = e.clientY;
- };
-
- var session = editor.session;
- var screenAnchor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY);
- var screenCursor = screenAnchor;
-
- var selectionMode;
- if (editor.$mouseHandler.$enableJumpToDef) {
- if (ctrl && alt || accel && alt)
- selectionMode = shift ? "block" : "add";
- else if (alt && editor.$blockSelectEnabled)
- selectionMode = "block";
- } else {
- if (accel && !alt) {
- selectionMode = "add";
- if (!isMultiSelect && shift)
- return;
- } else if (alt && editor.$blockSelectEnabled) {
- selectionMode = "block";
- }
- }
-
- if (selectionMode && useragent.isMac && ev.ctrlKey) {
- editor.$mouseHandler.cancelContextMenu();
- }
-
- if (selectionMode == "add") {
- if (!isMultiSelect && inSelection)
- return; // dragging
-
- if (!isMultiSelect) {
- var range = selection.toOrientedRange();
- editor.addSelectionMarker(range);
- }
-
- var oldRange = selection.rangeList.rangeAtPoint(pos);
-
-
- editor.$blockScrolling++;
- editor.inVirtualSelectionMode = true;
-
- if (shift) {
- oldRange = null;
- range = selection.ranges[0] || range;
- editor.removeSelectionMarker(range);
- }
- editor.once("mouseup", function() {
- var tmpSel = selection.toOrientedRange();
-
- if (oldRange && tmpSel.isEmpty() && isSamePoint(oldRange.cursor, tmpSel.cursor))
- selection.substractPoint(tmpSel.cursor);
- else {
- if (shift) {
- selection.substractPoint(range.cursor);
- } else if (range) {
- editor.removeSelectionMarker(range);
- selection.addRange(range);
- }
- selection.addRange(tmpSel);
- }
- editor.$blockScrolling--;
- editor.inVirtualSelectionMode = false;
- });
-
- } else if (selectionMode == "block") {
- e.stop();
- editor.inVirtualSelectionMode = true;
- var initialRange;
- var rectSel = [];
- var blockSelect = function() {
- var newCursor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY);
- var cursor = session.screenToDocumentPosition(newCursor.row, newCursor.column);
-
- if (isSamePoint(screenCursor, newCursor) && isSamePoint(cursor, selection.lead))
- return;
- screenCursor = newCursor;
-
- editor.$blockScrolling++;
- editor.selection.moveToPosition(cursor);
- editor.renderer.scrollCursorIntoView();
-
- editor.removeSelectionMarkers(rectSel);
- rectSel = selection.rectangularRangeBlock(screenCursor, screenAnchor);
- if (editor.$mouseHandler.$clickSelection && rectSel.length == 1 && rectSel[0].isEmpty())
- rectSel[0] = editor.$mouseHandler.$clickSelection.clone();
- rectSel.forEach(editor.addSelectionMarker, editor);
- editor.updateSelectionMarkers();
- editor.$blockScrolling--;
- };
- editor.$blockScrolling++;
- if (isMultiSelect && !accel) {
- selection.toSingleRange();
- } else if (!isMultiSelect && accel) {
- initialRange = selection.toOrientedRange();
- editor.addSelectionMarker(initialRange);
- }
-
- if (shift)
- screenAnchor = session.documentToScreenPosition(selection.lead);
- else
- selection.moveToPosition(pos);
- editor.$blockScrolling--;
-
- screenCursor = {row: -1, column: -1};
-
- var onMouseSelectionEnd = function(e) {
- clearInterval(timerId);
- editor.removeSelectionMarkers(rectSel);
- if (!rectSel.length)
- rectSel = [selection.toOrientedRange()];
- editor.$blockScrolling++;
- if (initialRange) {
- editor.removeSelectionMarker(initialRange);
- selection.toSingleRange(initialRange);
- }
- for (var i = 0; i < rectSel.length; i++)
- selection.addRange(rectSel[i]);
- editor.inVirtualSelectionMode = false;
- editor.$mouseHandler.$clickSelection = null;
- editor.$blockScrolling--;
- };
-
- var onSelectionInterval = blockSelect;
-
- event.capture(editor.container, onMouseSelection, onMouseSelectionEnd);
- var timerId = setInterval(function() {onSelectionInterval();}, 20);
-
- return e.preventDefault();
- }
-}
-
-
-exports.onMouseDown = onMouseDown;
-
-});
-
-ace.define("ace/commands/multi_select_commands",["require","exports","module","ace/keyboard/hash_handler"], function(require, exports, module) {
-exports.defaultCommands = [{
- name: "addCursorAbove",
- exec: function(editor) { editor.selectMoreLines(-1); },
- bindKey: {win: "Ctrl-Alt-Up", mac: "Ctrl-Alt-Up"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "addCursorBelow",
- exec: function(editor) { editor.selectMoreLines(1); },
- bindKey: {win: "Ctrl-Alt-Down", mac: "Ctrl-Alt-Down"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "addCursorAboveSkipCurrent",
- exec: function(editor) { editor.selectMoreLines(-1, true); },
- bindKey: {win: "Ctrl-Alt-Shift-Up", mac: "Ctrl-Alt-Shift-Up"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "addCursorBelowSkipCurrent",
- exec: function(editor) { editor.selectMoreLines(1, true); },
- bindKey: {win: "Ctrl-Alt-Shift-Down", mac: "Ctrl-Alt-Shift-Down"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selectMoreBefore",
- exec: function(editor) { editor.selectMore(-1); },
- bindKey: {win: "Ctrl-Alt-Left", mac: "Ctrl-Alt-Left"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selectMoreAfter",
- exec: function(editor) { editor.selectMore(1); },
- bindKey: {win: "Ctrl-Alt-Right", mac: "Ctrl-Alt-Right"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selectNextBefore",
- exec: function(editor) { editor.selectMore(-1, true); },
- bindKey: {win: "Ctrl-Alt-Shift-Left", mac: "Ctrl-Alt-Shift-Left"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selectNextAfter",
- exec: function(editor) { editor.selectMore(1, true); },
- bindKey: {win: "Ctrl-Alt-Shift-Right", mac: "Ctrl-Alt-Shift-Right"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "splitIntoLines",
- exec: function(editor) { editor.multiSelect.splitIntoLines(); },
- bindKey: {win: "Ctrl-Alt-L", mac: "Ctrl-Alt-L"},
- readOnly: true
-}, {
- name: "alignCursors",
- exec: function(editor) { editor.alignCursors(); },
- bindKey: {win: "Ctrl-Alt-A", mac: "Ctrl-Alt-A"},
- scrollIntoView: "cursor"
-}, {
- name: "findAll",
- exec: function(editor) { editor.findAll(); },
- bindKey: {win: "Ctrl-Alt-K", mac: "Ctrl-Alt-G"},
- scrollIntoView: "cursor",
- readOnly: true
-}];
-exports.multiSelectCommands = [{
- name: "singleSelection",
- bindKey: "esc",
- exec: function(editor) { editor.exitMultiSelectMode(); },
- scrollIntoView: "cursor",
- readOnly: true,
- isAvailable: function(editor) {return editor && editor.inMultiSelectMode}
-}];
-
-var HashHandler = require("../keyboard/hash_handler").HashHandler;
-exports.keyboardHandler = new HashHandler(exports.multiSelectCommands);
-
-});
-
-ace.define("ace/multi_select",["require","exports","module","ace/range_list","ace/range","ace/selection","ace/mouse/multi_select_handler","ace/lib/event","ace/lib/lang","ace/commands/multi_select_commands","ace/search","ace/edit_session","ace/editor","ace/config"], function(require, exports, module) {
-
-var RangeList = require("./range_list").RangeList;
-var Range = require("./range").Range;
-var Selection = require("./selection").Selection;
-var onMouseDown = require("./mouse/multi_select_handler").onMouseDown;
-var event = require("./lib/event");
-var lang = require("./lib/lang");
-var commands = require("./commands/multi_select_commands");
-exports.commands = commands.defaultCommands.concat(commands.multiSelectCommands);
-var Search = require("./search").Search;
-var search = new Search();
-
-function find(session, needle, dir) {
- search.$options.wrap = true;
- search.$options.needle = needle;
- search.$options.backwards = dir == -1;
- return search.find(session);
-}
-var EditSession = require("./edit_session").EditSession;
-(function() {
- this.getSelectionMarkers = function() {
- return this.$selectionMarkers;
- };
-}).call(EditSession.prototype);
-(function() {
- this.ranges = null;
- this.rangeList = null;
- this.addRange = function(range, $blockChangeEvents) {
- if (!range)
- return;
-
- if (!this.inMultiSelectMode && this.rangeCount === 0) {
- var oldRange = this.toOrientedRange();
- this.rangeList.add(oldRange);
- this.rangeList.add(range);
- if (this.rangeList.ranges.length != 2) {
- this.rangeList.removeAll();
- return $blockChangeEvents || this.fromOrientedRange(range);
- }
- this.rangeList.removeAll();
- this.rangeList.add(oldRange);
- this.$onAddRange(oldRange);
- }
-
- if (!range.cursor)
- range.cursor = range.end;
-
- var removed = this.rangeList.add(range);
-
- this.$onAddRange(range);
-
- if (removed.length)
- this.$onRemoveRange(removed);
-
- if (this.rangeCount > 1 && !this.inMultiSelectMode) {
- this._signal("multiSelect");
- this.inMultiSelectMode = true;
- this.session.$undoSelect = false;
- this.rangeList.attach(this.session);
- }
-
- return $blockChangeEvents || this.fromOrientedRange(range);
- };
-
- this.toSingleRange = function(range) {
- range = range || this.ranges[0];
- var removed = this.rangeList.removeAll();
- if (removed.length)
- this.$onRemoveRange(removed);
-
- range && this.fromOrientedRange(range);
- };
- this.substractPoint = function(pos) {
- var removed = this.rangeList.substractPoint(pos);
- if (removed) {
- this.$onRemoveRange(removed);
- return removed[0];
- }
- };
- this.mergeOverlappingRanges = function() {
- var removed = this.rangeList.merge();
- if (removed.length)
- this.$onRemoveRange(removed);
- else if(this.ranges[0])
- this.fromOrientedRange(this.ranges[0]);
- };
-
- this.$onAddRange = function(range) {
- this.rangeCount = this.rangeList.ranges.length;
- this.ranges.unshift(range);
- this._signal("addRange", {range: range});
- };
-
- this.$onRemoveRange = function(removed) {
- this.rangeCount = this.rangeList.ranges.length;
- if (this.rangeCount == 1 && this.inMultiSelectMode) {
- var lastRange = this.rangeList.ranges.pop();
- removed.push(lastRange);
- this.rangeCount = 0;
- }
-
- for (var i = removed.length; i--; ) {
- var index = this.ranges.indexOf(removed[i]);
- this.ranges.splice(index, 1);
- }
-
- this._signal("removeRange", {ranges: removed});
-
- if (this.rangeCount === 0 && this.inMultiSelectMode) {
- this.inMultiSelectMode = false;
- this._signal("singleSelect");
- this.session.$undoSelect = true;
- this.rangeList.detach(this.session);
- }
-
- lastRange = lastRange || this.ranges[0];
- if (lastRange && !lastRange.isEqual(this.getRange()))
- this.fromOrientedRange(lastRange);
- };
- this.$initRangeList = function() {
- if (this.rangeList)
- return;
-
- this.rangeList = new RangeList();
- this.ranges = [];
- this.rangeCount = 0;
- };
- this.getAllRanges = function() {
- return this.rangeCount ? this.rangeList.ranges.concat() : [this.getRange()];
- };
-
- this.splitIntoLines = function () {
- if (this.rangeCount > 1) {
- var ranges = this.rangeList.ranges;
- var lastRange = ranges[ranges.length - 1];
- var range = Range.fromPoints(ranges[0].start, lastRange.end);
-
- this.toSingleRange();
- this.setSelectionRange(range, lastRange.cursor == lastRange.start);
- } else {
- var range = this.getRange();
- var isBackwards = this.isBackwards();
- var startRow = range.start.row;
- var endRow = range.end.row;
- if (startRow == endRow) {
- if (isBackwards)
- var start = range.end, end = range.start;
- else
- var start = range.start, end = range.end;
-
- this.addRange(Range.fromPoints(end, end));
- this.addRange(Range.fromPoints(start, start));
- return;
- }
-
- var rectSel = [];
- var r = this.getLineRange(startRow, true);
- r.start.column = range.start.column;
- rectSel.push(r);
-
- for (var i = startRow + 1; i < endRow; i++)
- rectSel.push(this.getLineRange(i, true));
-
- r = this.getLineRange(endRow, true);
- r.end.column = range.end.column;
- rectSel.push(r);
-
- rectSel.forEach(this.addRange, this);
- }
- };
- this.toggleBlockSelection = function () {
- if (this.rangeCount > 1) {
- var ranges = this.rangeList.ranges;
- var lastRange = ranges[ranges.length - 1];
- var range = Range.fromPoints(ranges[0].start, lastRange.end);
-
- this.toSingleRange();
- this.setSelectionRange(range, lastRange.cursor == lastRange.start);
- } else {
- var cursor = this.session.documentToScreenPosition(this.selectionLead);
- var anchor = this.session.documentToScreenPosition(this.selectionAnchor);
-
- var rectSel = this.rectangularRangeBlock(cursor, anchor);
- rectSel.forEach(this.addRange, this);
- }
- };
- this.rectangularRangeBlock = function(screenCursor, screenAnchor, includeEmptyLines) {
- var rectSel = [];
-
- var xBackwards = screenCursor.column < screenAnchor.column;
- if (xBackwards) {
- var startColumn = screenCursor.column;
- var endColumn = screenAnchor.column;
- } else {
- var startColumn = screenAnchor.column;
- var endColumn = screenCursor.column;
- }
-
- var yBackwards = screenCursor.row < screenAnchor.row;
- if (yBackwards) {
- var startRow = screenCursor.row;
- var endRow = screenAnchor.row;
- } else {
- var startRow = screenAnchor.row;
- var endRow = screenCursor.row;
- }
-
- if (startColumn < 0)
- startColumn = 0;
- if (startRow < 0)
- startRow = 0;
-
- if (startRow == endRow)
- includeEmptyLines = true;
-
- for (var row = startRow; row <= endRow; row++) {
- var range = Range.fromPoints(
- this.session.screenToDocumentPosition(row, startColumn),
- this.session.screenToDocumentPosition(row, endColumn)
- );
- if (range.isEmpty()) {
- if (docEnd && isSamePoint(range.end, docEnd))
- break;
- var docEnd = range.end;
- }
- range.cursor = xBackwards ? range.start : range.end;
- rectSel.push(range);
- }
-
- if (yBackwards)
- rectSel.reverse();
-
- if (!includeEmptyLines) {
- var end = rectSel.length - 1;
- while (rectSel[end].isEmpty() && end > 0)
- end--;
- if (end > 0) {
- var start = 0;
- while (rectSel[start].isEmpty())
- start++;
- }
- for (var i = end; i >= start; i--) {
- if (rectSel[i].isEmpty())
- rectSel.splice(i, 1);
- }
- }
-
- return rectSel;
- };
-}).call(Selection.prototype);
-var Editor = require("./editor").Editor;
-(function() {
- this.updateSelectionMarkers = function() {
- this.renderer.updateCursor();
- this.renderer.updateBackMarkers();
- };
- this.addSelectionMarker = function(orientedRange) {
- if (!orientedRange.cursor)
- orientedRange.cursor = orientedRange.end;
-
- var style = this.getSelectionStyle();
- orientedRange.marker = this.session.addMarker(orientedRange, "ace_selection", style);
-
- this.session.$selectionMarkers.push(orientedRange);
- this.session.selectionMarkerCount = this.session.$selectionMarkers.length;
- return orientedRange;
- };
- this.removeSelectionMarker = function(range) {
- if (!range.marker)
- return;
- this.session.removeMarker(range.marker);
- var index = this.session.$selectionMarkers.indexOf(range);
- if (index != -1)
- this.session.$selectionMarkers.splice(index, 1);
- this.session.selectionMarkerCount = this.session.$selectionMarkers.length;
- };
-
- this.removeSelectionMarkers = function(ranges) {
- var markerList = this.session.$selectionMarkers;
- for (var i = ranges.length; i--; ) {
- var range = ranges[i];
- if (!range.marker)
- continue;
- this.session.removeMarker(range.marker);
- var index = markerList.indexOf(range);
- if (index != -1)
- markerList.splice(index, 1);
- }
- this.session.selectionMarkerCount = markerList.length;
- };
-
- this.$onAddRange = function(e) {
- this.addSelectionMarker(e.range);
- this.renderer.updateCursor();
- this.renderer.updateBackMarkers();
- };
-
- this.$onRemoveRange = function(e) {
- this.removeSelectionMarkers(e.ranges);
- this.renderer.updateCursor();
- this.renderer.updateBackMarkers();
- };
-
- this.$onMultiSelect = function(e) {
- if (this.inMultiSelectMode)
- return;
- this.inMultiSelectMode = true;
-
- this.setStyle("ace_multiselect");
- this.keyBinding.addKeyboardHandler(commands.keyboardHandler);
- this.commands.setDefaultHandler("exec", this.$onMultiSelectExec);
-
- this.renderer.updateCursor();
- this.renderer.updateBackMarkers();
- };
-
- this.$onSingleSelect = function(e) {
- if (this.session.multiSelect.inVirtualMode)
- return;
- this.inMultiSelectMode = false;
-
- this.unsetStyle("ace_multiselect");
- this.keyBinding.removeKeyboardHandler(commands.keyboardHandler);
-
- this.commands.removeDefaultHandler("exec", this.$onMultiSelectExec);
- this.renderer.updateCursor();
- this.renderer.updateBackMarkers();
- this._emit("changeSelection");
- };
-
- this.$onMultiSelectExec = function(e) {
- var command = e.command;
- var editor = e.editor;
- if (!editor.multiSelect)
- return;
- if (!command.multiSelectAction) {
- var result = command.exec(editor, e.args || {});
- editor.multiSelect.addRange(editor.multiSelect.toOrientedRange());
- editor.multiSelect.mergeOverlappingRanges();
- } else if (command.multiSelectAction == "forEach") {
- result = editor.forEachSelection(command, e.args);
- } else if (command.multiSelectAction == "forEachLine") {
- result = editor.forEachSelection(command, e.args, true);
- } else if (command.multiSelectAction == "single") {
- editor.exitMultiSelectMode();
- result = command.exec(editor, e.args || {});
- } else {
- result = command.multiSelectAction(editor, e.args || {});
- }
- return result;
- };
- this.forEachSelection = function(cmd, args, options) {
- if (this.inVirtualSelectionMode)
- return;
- var keepOrder = options && options.keepOrder;
- var $byLines = options == true || options && options.$byLines
- var session = this.session;
- var selection = this.selection;
- var rangeList = selection.rangeList;
- var ranges = (keepOrder ? selection : rangeList).ranges;
- var result;
-
- if (!ranges.length)
- return cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {});
-
- var reg = selection._eventRegistry;
- selection._eventRegistry = {};
-
- var tmpSel = new Selection(session);
- this.inVirtualSelectionMode = true;
- for (var i = ranges.length; i--;) {
- if ($byLines) {
- while (i > 0 && ranges[i].start.row == ranges[i - 1].end.row)
- i--;
- }
- tmpSel.fromOrientedRange(ranges[i]);
- tmpSel.index = i;
- this.selection = session.selection = tmpSel;
- var cmdResult = cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {});
- if (!result && cmdResult !== undefined)
- result = cmdResult;
- tmpSel.toOrientedRange(ranges[i]);
- }
- tmpSel.detach();
-
- this.selection = session.selection = selection;
- this.inVirtualSelectionMode = false;
- selection._eventRegistry = reg;
- selection.mergeOverlappingRanges();
-
- var anim = this.renderer.$scrollAnimation;
- this.onCursorChange();
- this.onSelectionChange();
- if (anim && anim.from == anim.to)
- this.renderer.animateScrolling(anim.from);
-
- return result;
- };
- this.exitMultiSelectMode = function() {
- if (!this.inMultiSelectMode || this.inVirtualSelectionMode)
- return;
- this.multiSelect.toSingleRange();
- };
-
- this.getSelectedText = function() {
- var text = "";
- if (this.inMultiSelectMode && !this.inVirtualSelectionMode) {
- var ranges = this.multiSelect.rangeList.ranges;
- var buf = [];
- for (var i = 0; i < ranges.length; i++) {
- buf.push(this.session.getTextRange(ranges[i]));
- }
- var nl = this.session.getDocument().getNewLineCharacter();
- text = buf.join(nl);
- if (text.length == (buf.length - 1) * nl.length)
- text = "";
- } else if (!this.selection.isEmpty()) {
- text = this.session.getTextRange(this.getSelectionRange());
- }
- return text;
- };
-
- this.$checkMultiselectChange = function(e, anchor) {
- if (this.inMultiSelectMode && !this.inVirtualSelectionMode) {
- var range = this.multiSelect.ranges[0];
- if (this.multiSelect.isEmpty() && anchor == this.multiSelect.anchor)
- return;
- var pos = anchor == this.multiSelect.anchor
- ? range.cursor == range.start ? range.end : range.start
- : range.cursor;
- if (pos.row != anchor.row
- || this.session.$clipPositionToDocument(pos.row, pos.column).column != anchor.column)
- this.multiSelect.toSingleRange(this.multiSelect.toOrientedRange());
- }
- };
- this.findAll = function(needle, options, additive) {
- options = options || {};
- options.needle = needle || options.needle;
- if (options.needle == undefined) {
- var range = this.selection.isEmpty()
- ? this.selection.getWordRange()
- : this.selection.getRange();
- options.needle = this.session.getTextRange(range);
- }
- this.$search.set(options);
-
- var ranges = this.$search.findAll(this.session);
- if (!ranges.length)
- return 0;
-
- this.$blockScrolling += 1;
- var selection = this.multiSelect;
-
- if (!additive)
- selection.toSingleRange(ranges[0]);
-
- for (var i = ranges.length; i--; )
- selection.addRange(ranges[i], true);
- if (range && selection.rangeList.rangeAtPoint(range.start))
- selection.addRange(range, true);
-
- this.$blockScrolling -= 1;
-
- return ranges.length;
- };
- this.selectMoreLines = function(dir, skip) {
- var range = this.selection.toOrientedRange();
- var isBackwards = range.cursor == range.end;
-
- var screenLead = this.session.documentToScreenPosition(range.cursor);
- if (this.selection.$desiredColumn)
- screenLead.column = this.selection.$desiredColumn;
-
- var lead = this.session.screenToDocumentPosition(screenLead.row + dir, screenLead.column);
-
- if (!range.isEmpty()) {
- var screenAnchor = this.session.documentToScreenPosition(isBackwards ? range.end : range.start);
- var anchor = this.session.screenToDocumentPosition(screenAnchor.row + dir, screenAnchor.column);
- } else {
- var anchor = lead;
- }
-
- if (isBackwards) {
- var newRange = Range.fromPoints(lead, anchor);
- newRange.cursor = newRange.start;
- } else {
- var newRange = Range.fromPoints(anchor, lead);
- newRange.cursor = newRange.end;
- }
-
- newRange.desiredColumn = screenLead.column;
- if (!this.selection.inMultiSelectMode) {
- this.selection.addRange(range);
- } else {
- if (skip)
- var toRemove = range.cursor;
- }
-
- this.selection.addRange(newRange);
- if (toRemove)
- this.selection.substractPoint(toRemove);
- };
- this.transposeSelections = function(dir) {
- var session = this.session;
- var sel = session.multiSelect;
- var all = sel.ranges;
-
- for (var i = all.length; i--; ) {
- var range = all[i];
- if (range.isEmpty()) {
- var tmp = session.getWordRange(range.start.row, range.start.column);
- range.start.row = tmp.start.row;
- range.start.column = tmp.start.column;
- range.end.row = tmp.end.row;
- range.end.column = tmp.end.column;
- }
- }
- sel.mergeOverlappingRanges();
-
- var words = [];
- for (var i = all.length; i--; ) {
- var range = all[i];
- words.unshift(session.getTextRange(range));
- }
-
- if (dir < 0)
- words.unshift(words.pop());
- else
- words.push(words.shift());
-
- for (var i = all.length; i--; ) {
- var range = all[i];
- var tmp = range.clone();
- session.replace(range, words[i]);
- range.start.row = tmp.start.row;
- range.start.column = tmp.start.column;
- }
- };
- this.selectMore = function(dir, skip, stopAtFirst) {
- var session = this.session;
- var sel = session.multiSelect;
-
- var range = sel.toOrientedRange();
- if (range.isEmpty()) {
- range = session.getWordRange(range.start.row, range.start.column);
- range.cursor = dir == -1 ? range.start : range.end;
- this.multiSelect.addRange(range);
- if (stopAtFirst)
- return;
- }
- var needle = session.getTextRange(range);
-
- var newRange = find(session, needle, dir);
- if (newRange) {
- newRange.cursor = dir == -1 ? newRange.start : newRange.end;
- this.$blockScrolling += 1;
- this.session.unfold(newRange);
- this.multiSelect.addRange(newRange);
- this.$blockScrolling -= 1;
- this.renderer.scrollCursorIntoView(null, 0.5);
- }
- if (skip)
- this.multiSelect.substractPoint(range.cursor);
- };
- this.alignCursors = function() {
- var session = this.session;
- var sel = session.multiSelect;
- var ranges = sel.ranges;
- var row = -1;
- var sameRowRanges = ranges.filter(function(r) {
- if (r.cursor.row == row)
- return true;
- row = r.cursor.row;
- });
-
- if (!ranges.length || sameRowRanges.length == ranges.length - 1) {
- var range = this.selection.getRange();
- var fr = range.start.row, lr = range.end.row;
- var guessRange = fr == lr;
- if (guessRange) {
- var max = this.session.getLength();
- var line;
- do {
- line = this.session.getLine(lr);
- } while (/[=:]/.test(line) && ++lr < max);
- do {
- line = this.session.getLine(fr);
- } while (/[=:]/.test(line) && --fr > 0);
-
- if (fr < 0) fr = 0;
- if (lr >= max) lr = max - 1;
- }
- var lines = this.session.removeFullLines(fr, lr);
- lines = this.$reAlignText(lines, guessRange);
- this.session.insert({row: fr, column: 0}, lines.join("\n") + "\n");
- if (!guessRange) {
- range.start.column = 0;
- range.end.column = lines[lines.length - 1].length;
- }
- this.selection.setRange(range);
- } else {
- sameRowRanges.forEach(function(r) {
- sel.substractPoint(r.cursor);
- });
-
- var maxCol = 0;
- var minSpace = Infinity;
- var spaceOffsets = ranges.map(function(r) {
- var p = r.cursor;
- var line = session.getLine(p.row);
- var spaceOffset = line.substr(p.column).search(/\S/g);
- if (spaceOffset == -1)
- spaceOffset = 0;
-
- if (p.column > maxCol)
- maxCol = p.column;
- if (spaceOffset < minSpace)
- minSpace = spaceOffset;
- return spaceOffset;
- });
- ranges.forEach(function(r, i) {
- var p = r.cursor;
- var l = maxCol - p.column;
- var d = spaceOffsets[i] - minSpace;
- if (l > d)
- session.insert(p, lang.stringRepeat(" ", l - d));
- else
- session.remove(new Range(p.row, p.column, p.row, p.column - l + d));
-
- r.start.column = r.end.column = maxCol;
- r.start.row = r.end.row = p.row;
- r.cursor = r.end;
- });
- sel.fromOrientedRange(ranges[0]);
- this.renderer.updateCursor();
- this.renderer.updateBackMarkers();
- }
- };
-
- this.$reAlignText = function(lines, forceLeft) {
- var isLeftAligned = true, isRightAligned = true;
- var startW, textW, endW;
-
- return lines.map(function(line) {
- var m = line.match(/(\s*)(.*?)(\s*)([=:].*)/);
- if (!m)
- return [line];
-
- if (startW == null) {
- startW = m[1].length;
- textW = m[2].length;
- endW = m[3].length;
- return m;
- }
-
- if (startW + textW + endW != m[1].length + m[2].length + m[3].length)
- isRightAligned = false;
- if (startW != m[1].length)
- isLeftAligned = false;
-
- if (startW > m[1].length)
- startW = m[1].length;
- if (textW < m[2].length)
- textW = m[2].length;
- if (endW > m[3].length)
- endW = m[3].length;
-
- return m;
- }).map(forceLeft ? alignLeft :
- isLeftAligned ? isRightAligned ? alignRight : alignLeft : unAlign);
-
- function spaces(n) {
- return lang.stringRepeat(" ", n);
- }
-
- function alignLeft(m) {
- return !m[2] ? m[0] : spaces(startW) + m[2]
- + spaces(textW - m[2].length + endW)
- + m[4].replace(/^([=:])\s+/, "$1 ");
- }
- function alignRight(m) {
- return !m[2] ? m[0] : spaces(startW + textW - m[2].length) + m[2]
- + spaces(endW, " ")
- + m[4].replace(/^([=:])\s+/, "$1 ");
- }
- function unAlign(m) {
- return !m[2] ? m[0] : spaces(startW) + m[2]
- + spaces(endW)
- + m[4].replace(/^([=:])\s+/, "$1 ");
- }
- };
-}).call(Editor.prototype);
-
-
-function isSamePoint(p1, p2) {
- return p1.row == p2.row && p1.column == p2.column;
-}
-exports.onSessionChange = function(e) {
- var session = e.session;
- if (session && !session.multiSelect) {
- session.$selectionMarkers = [];
- session.selection.$initRangeList();
- session.multiSelect = session.selection;
- }
- this.multiSelect = session && session.multiSelect;
-
- var oldSession = e.oldSession;
- if (oldSession) {
- oldSession.multiSelect.off("addRange", this.$onAddRange);
- oldSession.multiSelect.off("removeRange", this.$onRemoveRange);
- oldSession.multiSelect.off("multiSelect", this.$onMultiSelect);
- oldSession.multiSelect.off("singleSelect", this.$onSingleSelect);
- oldSession.multiSelect.lead.off("change", this.$checkMultiselectChange);
- oldSession.multiSelect.anchor.off("change", this.$checkMultiselectChange);
- }
-
- if (session) {
- session.multiSelect.on("addRange", this.$onAddRange);
- session.multiSelect.on("removeRange", this.$onRemoveRange);
- session.multiSelect.on("multiSelect", this.$onMultiSelect);
- session.multiSelect.on("singleSelect", this.$onSingleSelect);
- session.multiSelect.lead.on("change", this.$checkMultiselectChange);
- session.multiSelect.anchor.on("change", this.$checkMultiselectChange);
- }
-
- if (session && this.inMultiSelectMode != session.selection.inMultiSelectMode) {
- if (session.selection.inMultiSelectMode)
- this.$onMultiSelect();
- else
- this.$onSingleSelect();
- }
-};
-function MultiSelect(editor) {
- if (editor.$multiselectOnSessionChange)
- return;
- editor.$onAddRange = editor.$onAddRange.bind(editor);
- editor.$onRemoveRange = editor.$onRemoveRange.bind(editor);
- editor.$onMultiSelect = editor.$onMultiSelect.bind(editor);
- editor.$onSingleSelect = editor.$onSingleSelect.bind(editor);
- editor.$multiselectOnSessionChange = exports.onSessionChange.bind(editor);
- editor.$checkMultiselectChange = editor.$checkMultiselectChange.bind(editor);
-
- editor.$multiselectOnSessionChange(editor);
- editor.on("changeSession", editor.$multiselectOnSessionChange);
-
- editor.on("mousedown", onMouseDown);
- editor.commands.addCommands(commands.defaultCommands);
-
- addAltCursorListeners(editor);
-}
-
-function addAltCursorListeners(editor){
- var el = editor.textInput.getElement();
- var altCursor = false;
- event.addListener(el, "keydown", function(e) {
- var altDown = e.keyCode == 18 && !(e.ctrlKey || e.shiftKey || e.metaKey);
- if (editor.$blockSelectEnabled && altDown) {
- if (!altCursor) {
- editor.renderer.setMouseCursor("crosshair");
- altCursor = true;
- }
- } else if (altCursor) {
- reset();
- }
- });
-
- event.addListener(el, "keyup", reset);
- event.addListener(el, "blur", reset);
- function reset(e) {
- if (altCursor) {
- editor.renderer.setMouseCursor("");
- altCursor = false;
- }
- }
-}
-
-exports.MultiSelect = MultiSelect;
-
-
-require("./config").defineOptions(Editor.prototype, "editor", {
- enableMultiselect: {
- set: function(val) {
- MultiSelect(this);
- if (val) {
- this.on("changeSession", this.$multiselectOnSessionChange);
- this.on("mousedown", onMouseDown);
- } else {
- this.off("changeSession", this.$multiselectOnSessionChange);
- this.off("mousedown", onMouseDown);
- }
- },
- value: true
- },
- enableBlockSelect: {
- set: function(val) {
- this.$blockSelectEnabled = val;
- },
- value: true
- }
-});
-
-
-
-});
-
-ace.define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"], function(require, exports, module) {
-"use strict";
-
-var Range = require("../../range").Range;
-
-var FoldMode = exports.FoldMode = function() {};
-
-(function() {
-
- this.foldingStartMarker = null;
- this.foldingStopMarker = null;
- this.getFoldWidget = function(session, foldStyle, row) {
- var line = session.getLine(row);
- if (this.foldingStartMarker.test(line))
- return "start";
- if (foldStyle == "markbeginend"
- && this.foldingStopMarker
- && this.foldingStopMarker.test(line))
- return "end";
- return "";
- };
-
- this.getFoldWidgetRange = function(session, foldStyle, row) {
- return null;
- };
-
- this.indentationBlock = function(session, row, column) {
- var re = /\S/;
- var line = session.getLine(row);
- var startLevel = line.search(re);
- if (startLevel == -1)
- return;
-
- var startColumn = column || line.length;
- var maxRow = session.getLength();
- var startRow = row;
- var endRow = row;
-
- while (++row < maxRow) {
- var level = session.getLine(row).search(re);
-
- if (level == -1)
- continue;
-
- if (level <= startLevel)
- break;
-
- endRow = row;
- }
-
- if (endRow > startRow) {
- var endColumn = session.getLine(endRow).length;
- return new Range(startRow, startColumn, endRow, endColumn);
- }
- };
-
- this.openingBracketBlock = function(session, bracket, row, column, typeRe) {
- var start = {row: row, column: column + 1};
- var end = session.$findClosingBracket(bracket, start, typeRe);
- if (!end)
- return;
-
- var fw = session.foldWidgets[end.row];
- if (fw == null)
- fw = session.getFoldWidget(end.row);
-
- if (fw == "start" && end.row > start.row) {
- end.row --;
- end.column = session.getLine(end.row).length;
- }
- return Range.fromPoints(start, end);
- };
-
- this.closingBracketBlock = function(session, bracket, row, column, typeRe) {
- var end = {row: row, column: column};
- var start = session.$findOpeningBracket(bracket, end);
-
- if (!start)
- return;
-
- start.column++;
- end.column--;
-
- return Range.fromPoints(start, end);
- };
-}).call(FoldMode.prototype);
-
-});
-
-ace.define("ace/theme/textmate",["require","exports","module","ace/lib/dom"], function(require, exports, module) {
-"use strict";
-
-exports.isDark = false;
-exports.cssClass = "ace-tm";
-exports.cssText = ".ace-tm .ace_gutter {\
-background: #f0f0f0;\
-color: #333;\
-}\
-.ace-tm .ace_print-margin {\
-width: 1px;\
-background: #e8e8e8;\
-}\
-.ace-tm .ace_fold {\
-background-color: #6B72E6;\
-}\
-.ace-tm {\
-background-color: #FFFFFF;\
-color: black;\
-}\
-.ace-tm .ace_cursor {\
-color: black;\
-}\
-.ace-tm .ace_invisible {\
-color: rgb(191, 191, 191);\
-}\
-.ace-tm .ace_storage,\
-.ace-tm .ace_keyword {\
-color: blue;\
-}\
-.ace-tm .ace_constant {\
-color: rgb(197, 6, 11);\
-}\
-.ace-tm .ace_constant.ace_buildin {\
-color: rgb(88, 72, 246);\
-}\
-.ace-tm .ace_constant.ace_language {\
-color: rgb(88, 92, 246);\
-}\
-.ace-tm .ace_constant.ace_library {\
-color: rgb(6, 150, 14);\
-}\
-.ace-tm .ace_invalid {\
-background-color: rgba(255, 0, 0, 0.1);\
-color: red;\
-}\
-.ace-tm .ace_support.ace_function {\
-color: rgb(60, 76, 114);\
-}\
-.ace-tm .ace_support.ace_constant {\
-color: rgb(6, 150, 14);\
-}\
-.ace-tm .ace_support.ace_type,\
-.ace-tm .ace_support.ace_class {\
-color: rgb(109, 121, 222);\
-}\
-.ace-tm .ace_keyword.ace_operator {\
-color: rgb(104, 118, 135);\
-}\
-.ace-tm .ace_string {\
-color: rgb(3, 106, 7);\
-}\
-.ace-tm .ace_comment {\
-color: rgb(76, 136, 107);\
-}\
-.ace-tm .ace_comment.ace_doc {\
-color: rgb(0, 102, 255);\
-}\
-.ace-tm .ace_comment.ace_doc.ace_tag {\
-color: rgb(128, 159, 191);\
-}\
-.ace-tm .ace_constant.ace_numeric {\
-color: rgb(0, 0, 205);\
-}\
-.ace-tm .ace_variable {\
-color: rgb(49, 132, 149);\
-}\
-.ace-tm .ace_xml-pe {\
-color: rgb(104, 104, 91);\
-}\
-.ace-tm .ace_entity.ace_name.ace_function {\
-color: #0000A2;\
-}\
-.ace-tm .ace_heading {\
-color: rgb(12, 7, 255);\
-}\
-.ace-tm .ace_list {\
-color:rgb(185, 6, 144);\
-}\
-.ace-tm .ace_meta.ace_tag {\
-color:rgb(0, 22, 142);\
-}\
-.ace-tm .ace_string.ace_regex {\
-color: rgb(255, 0, 0)\
-}\
-.ace-tm .ace_marker-layer .ace_selection {\
-background: rgb(181, 213, 255);\
-}\
-.ace-tm.ace_multiselect .ace_selection.ace_start {\
-box-shadow: 0 0 3px 0px white;\
-}\
-.ace-tm .ace_marker-layer .ace_step {\
-background: rgb(252, 255, 0);\
-}\
-.ace-tm .ace_marker-layer .ace_stack {\
-background: rgb(164, 229, 101);\
-}\
-.ace-tm .ace_marker-layer .ace_bracket {\
-margin: -1px 0 0 -1px;\
-border: 1px solid rgb(192, 192, 192);\
-}\
-.ace-tm .ace_marker-layer .ace_active-line {\
-background: rgba(0, 0, 0, 0.07);\
-}\
-.ace-tm .ace_gutter-active-line {\
-background-color : #dcdcdc;\
-}\
-.ace-tm .ace_marker-layer .ace_selected-word {\
-background: rgb(250, 250, 255);\
-border: 1px solid rgb(200, 200, 250);\
-}\
-.ace-tm .ace_indent-guide {\
-background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\
-}\
-";
-
-var dom = require("../lib/dom");
-dom.importCssString(exports.cssText, exports.cssClass);
-});
-
-ace.define("ace/line_widgets",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/range"], function(require, exports, module) {
-"use strict";
-
-var oop = require("./lib/oop");
-var dom = require("./lib/dom");
-var Range = require("./range").Range;
-
-
-function LineWidgets(session) {
- this.session = session;
- this.session.widgetManager = this;
- this.session.getRowLength = this.getRowLength;
- this.session.$getWidgetScreenLength = this.$getWidgetScreenLength;
- this.updateOnChange = this.updateOnChange.bind(this);
- this.renderWidgets = this.renderWidgets.bind(this);
- this.measureWidgets = this.measureWidgets.bind(this);
- this.session._changedWidgets = [];
- this.$onChangeEditor = this.$onChangeEditor.bind(this);
-
- this.session.on("change", this.updateOnChange);
- this.session.on("changeFold", this.updateOnFold);
- this.session.on("changeEditor", this.$onChangeEditor);
-}
-
-(function() {
- this.getRowLength = function(row) {
- var h;
- if (this.lineWidgets)
- h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0;
- else
- h = 0;
- if (!this.$useWrapMode || !this.$wrapData[row]) {
- return 1 + h;
- } else {
- return this.$wrapData[row].length + 1 + h;
- }
- };
-
- this.$getWidgetScreenLength = function() {
- var screenRows = 0;
- this.lineWidgets.forEach(function(w){
- if (w && w.rowCount && !w.hidden)
- screenRows += w.rowCount;
- });
- return screenRows;
- };
-
- this.$onChangeEditor = function(e) {
- this.attach(e.editor);
- };
-
- this.attach = function(editor) {
- if (editor && editor.widgetManager && editor.widgetManager != this)
- editor.widgetManager.detach();
-
- if (this.editor == editor)
- return;
-
- this.detach();
- this.editor = editor;
-
- if (editor) {
- editor.widgetManager = this;
- editor.renderer.on("beforeRender", this.measureWidgets);
- editor.renderer.on("afterRender", this.renderWidgets);
- }
- };
- this.detach = function(e) {
- var editor = this.editor;
- if (!editor)
- return;
-
- this.editor = null;
- editor.widgetManager = null;
-
- editor.renderer.off("beforeRender", this.measureWidgets);
- editor.renderer.off("afterRender", this.renderWidgets);
- var lineWidgets = this.session.lineWidgets;
- lineWidgets && lineWidgets.forEach(function(w) {
- if (w && w.el && w.el.parentNode) {
- w._inDocument = false;
- w.el.parentNode.removeChild(w.el);
- }
- });
- };
-
- this.updateOnFold = function(e, session) {
- var lineWidgets = session.lineWidgets;
- if (!lineWidgets || !e.action)
- return;
- var fold = e.data;
- var start = fold.start.row;
- var end = fold.end.row;
- var hide = e.action == "add";
- for (var i = start + 1; i < end; i++) {
- if (lineWidgets[i])
- lineWidgets[i].hidden = hide;
- }
- if (lineWidgets[end]) {
- if (hide) {
- if (!lineWidgets[start])
- lineWidgets[start] = lineWidgets[end];
- else
- lineWidgets[end].hidden = hide;
- } else {
- if (lineWidgets[start] == lineWidgets[end])
- lineWidgets[start] = undefined;
- lineWidgets[end].hidden = hide;
- }
- }
- };
-
- this.updateOnChange = function(delta) {
- var lineWidgets = this.session.lineWidgets;
- if (!lineWidgets) return;
-
- var startRow = delta.start.row;
- var len = delta.end.row - startRow;
-
- if (len === 0) {
- } else if (delta.action == 'remove') {
- var removed = lineWidgets.splice(startRow + 1, len);
- removed.forEach(function(w) {
- w && this.removeLineWidget(w);
- }, this);
- this.$updateRows();
- } else {
- var args = new Array(len);
- args.unshift(startRow, 0);
- lineWidgets.splice.apply(lineWidgets, args);
- this.$updateRows();
- }
- };
-
- this.$updateRows = function() {
- var lineWidgets = this.session.lineWidgets;
- if (!lineWidgets) return;
- var noWidgets = true;
- lineWidgets.forEach(function(w, i) {
- if (w) {
- noWidgets = false;
- w.row = i;
- while (w.$oldWidget) {
- w.$oldWidget.row = i;
- w = w.$oldWidget;
- }
- }
- });
- if (noWidgets)
- this.session.lineWidgets = null;
- };
-
- this.addLineWidget = function(w) {
- if (!this.session.lineWidgets)
- this.session.lineWidgets = new Array(this.session.getLength());
-
- var old = this.session.lineWidgets[w.row];
- if (old) {
- w.$oldWidget = old;
- if (old.el && old.el.parentNode) {
- old.el.parentNode.removeChild(old.el);
- old._inDocument = false;
- }
- }
-
- this.session.lineWidgets[w.row] = w;
-
- w.session = this.session;
-
- var renderer = this.editor.renderer;
- if (w.html && !w.el) {
- w.el = dom.createElement("div");
- w.el.innerHTML = w.html;
- }
- if (w.el) {
- dom.addCssClass(w.el, "ace_lineWidgetContainer");
- w.el.style.position = "absolute";
- w.el.style.zIndex = 5;
- renderer.container.appendChild(w.el);
- w._inDocument = true;
- }
-
- if (!w.coverGutter) {
- w.el.style.zIndex = 3;
- }
- if (!w.pixelHeight) {
- w.pixelHeight = w.el.offsetHeight;
- }
- if (w.rowCount == null) {
- w.rowCount = w.pixelHeight / renderer.layerConfig.lineHeight;
- }
-
- var fold = this.session.getFoldAt(w.row, 0);
- w.$fold = fold;
- if (fold) {
- var lineWidgets = this.session.lineWidgets;
- if (w.row == fold.end.row && !lineWidgets[fold.start.row])
- lineWidgets[fold.start.row] = w;
- else
- w.hidden = true;
- }
-
- this.session._emit("changeFold", {data:{start:{row: w.row}}});
-
- this.$updateRows();
- this.renderWidgets(null, renderer);
- this.onWidgetChanged(w);
- return w;
- };
-
- this.removeLineWidget = function(w) {
- w._inDocument = false;
- w.session = null;
- if (w.el && w.el.parentNode)
- w.el.parentNode.removeChild(w.el);
- if (w.editor && w.editor.destroy) try {
- w.editor.destroy();
- } catch(e){}
- if (this.session.lineWidgets) {
- var w1 = this.session.lineWidgets[w.row]
- if (w1 == w) {
- this.session.lineWidgets[w.row] = w.$oldWidget;
- if (w.$oldWidget)
- this.onWidgetChanged(w.$oldWidget);
- } else {
- while (w1) {
- if (w1.$oldWidget == w) {
- w1.$oldWidget = w.$oldWidget;
- break;
- }
- w1 = w1.$oldWidget;
- }
- }
- }
- this.session._emit("changeFold", {data:{start:{row: w.row}}});
- this.$updateRows();
- };
-
- this.getWidgetsAtRow = function(row) {
- var lineWidgets = this.session.lineWidgets;
- var w = lineWidgets && lineWidgets[row];
- var list = [];
- while (w) {
- list.push(w);
- w = w.$oldWidget;
- }
- return list;
- };
-
- this.onWidgetChanged = function(w) {
- this.session._changedWidgets.push(w);
- this.editor && this.editor.renderer.updateFull();
- };
-
- this.measureWidgets = function(e, renderer) {
- var changedWidgets = this.session._changedWidgets;
- var config = renderer.layerConfig;
-
- if (!changedWidgets || !changedWidgets.length) return;
- var min = Infinity;
- for (var i = 0; i < changedWidgets.length; i++) {
- var w = changedWidgets[i];
- if (!w || !w.el) continue;
- if (w.session != this.session) continue;
- if (!w._inDocument) {
- if (this.session.lineWidgets[w.row] != w)
- continue;
- w._inDocument = true;
- renderer.container.appendChild(w.el);
- }
-
- w.h = w.el.offsetHeight;
-
- if (!w.fixedWidth) {
- w.w = w.el.offsetWidth;
- w.screenWidth = Math.ceil(w.w / config.characterWidth);
- }
-
- var rowCount = w.h / config.lineHeight;
- if (w.coverLine) {
- rowCount -= this.session.getRowLineCount(w.row);
- if (rowCount < 0)
- rowCount = 0;
- }
- if (w.rowCount != rowCount) {
- w.rowCount = rowCount;
- if (w.row < min)
- min = w.row;
- }
- }
- if (min != Infinity) {
- this.session._emit("changeFold", {data:{start:{row: min}}});
- this.session.lineWidgetWidth = null;
- }
- this.session._changedWidgets = [];
- };
-
- this.renderWidgets = function(e, renderer) {
- var config = renderer.layerConfig;
- var lineWidgets = this.session.lineWidgets;
- if (!lineWidgets)
- return;
- var first = Math.min(this.firstRow, config.firstRow);
- var last = Math.max(this.lastRow, config.lastRow, lineWidgets.length);
-
- while (first > 0 && !lineWidgets[first])
- first--;
-
- this.firstRow = config.firstRow;
- this.lastRow = config.lastRow;
-
- renderer.$cursorLayer.config = config;
- for (var i = first; i <= last; i++) {
- var w = lineWidgets[i];
- if (!w || !w.el) continue;
- if (w.hidden) {
- w.el.style.top = -100 - (w.pixelHeight || 0) + "px";
- continue;
- }
- if (!w._inDocument) {
- w._inDocument = true;
- renderer.container.appendChild(w.el);
- }
- var top = renderer.$cursorLayer.getPixelPosition({row: i, column:0}, true).top;
- if (!w.coverLine)
- top += config.lineHeight * this.session.getRowLineCount(w.row);
- w.el.style.top = top - config.offset + "px";
-
- var left = w.coverGutter ? 0 : renderer.gutterWidth;
- if (!w.fixedWidth)
- left -= renderer.scrollLeft;
- w.el.style.left = left + "px";
-
- if (w.fullWidth && w.screenWidth) {
- w.el.style.minWidth = config.width + 2 * config.padding + "px";
- }
-
- if (w.fixedWidth) {
- w.el.style.right = renderer.scrollBar.getWidth() + "px";
- } else {
- w.el.style.right = "";
- }
- }
- };
-
-}).call(LineWidgets.prototype);
-
-
-exports.LineWidgets = LineWidgets;
-
-});
-
-ace.define("ace/ext/error_marker",["require","exports","module","ace/line_widgets","ace/lib/dom","ace/range"], function(require, exports, module) {
-"use strict";
-var LineWidgets = require("../line_widgets").LineWidgets;
-var dom = require("../lib/dom");
-var Range = require("../range").Range;
-
-function binarySearch(array, needle, comparator) {
- var first = 0;
- var last = array.length - 1;
-
- while (first <= last) {
- var mid = (first + last) >> 1;
- var c = comparator(needle, array[mid]);
- if (c > 0)
- first = mid + 1;
- else if (c < 0)
- last = mid - 1;
- else
- return mid;
- }
- return -(first + 1);
-}
-
-function findAnnotations(session, row, dir) {
- var annotations = session.getAnnotations().sort(Range.comparePoints);
- if (!annotations.length)
- return;
-
- var i = binarySearch(annotations, {row: row, column: -1}, Range.comparePoints);
- if (i < 0)
- i = -i - 1;
-
- if (i >= annotations.length)
- i = dir > 0 ? 0 : annotations.length - 1;
- else if (i === 0 && dir < 0)
- i = annotations.length - 1;
-
- var annotation = annotations[i];
- if (!annotation || !dir)
- return;
-
- if (annotation.row === row) {
- do {
- annotation = annotations[i += dir];
- } while (annotation && annotation.row === row);
- if (!annotation)
- return annotations.slice();
- }
-
-
- var matched = [];
- row = annotation.row;
- do {
- matched[dir < 0 ? "unshift" : "push"](annotation);
- annotation = annotations[i += dir];
- } while (annotation && annotation.row == row);
- return matched.length && matched;
-}
-
-exports.showErrorMarker = function(editor, dir) {
- var session = editor.session;
- if (!session.widgetManager) {
- session.widgetManager = new LineWidgets(session);
- session.widgetManager.attach(editor);
- }
-
- var pos = editor.getCursorPosition();
- var row = pos.row;
- var oldWidget = session.widgetManager.getWidgetsAtRow(row).filter(function(w) {
- return w.type == "errorMarker";
- })[0];
- if (oldWidget) {
- oldWidget.destroy();
- } else {
- row -= dir;
- }
- var annotations = findAnnotations(session, row, dir);
- var gutterAnno;
- if (annotations) {
- var annotation = annotations[0];
- pos.column = (annotation.pos && typeof annotation.column != "number"
- ? annotation.pos.sc
- : annotation.column) || 0;
- pos.row = annotation.row;
- gutterAnno = editor.renderer.$gutterLayer.$annotations[pos.row];
- } else if (oldWidget) {
- return;
- } else {
- gutterAnno = {
- text: ["Looks good!"],
- className: "ace_ok"
- };
- }
- editor.session.unfold(pos.row);
- editor.selection.moveToPosition(pos);
-
- var w = {
- row: pos.row,
- fixedWidth: true,
- coverGutter: true,
- el: dom.createElement("div"),
- type: "errorMarker"
- };
- var el = w.el.appendChild(dom.createElement("div"));
- var arrow = w.el.appendChild(dom.createElement("div"));
- arrow.className = "error_widget_arrow " + gutterAnno.className;
-
- var left = editor.renderer.$cursorLayer
- .getPixelPosition(pos).left;
- arrow.style.left = left + editor.renderer.gutterWidth - 5 + "px";
-
- w.el.className = "error_widget_wrapper";
- el.className = "error_widget " + gutterAnno.className;
- el.innerHTML = gutterAnno.text.join("
");
-
- el.appendChild(dom.createElement("div"));
-
- var kb = function(_, hashId, keyString) {
- if (hashId === 0 && (keyString === "esc" || keyString === "return")) {
- w.destroy();
- return {command: "null"};
- }
- };
-
- w.destroy = function() {
- if (editor.$mouseHandler.isMousePressed)
- return;
- editor.keyBinding.removeKeyboardHandler(kb);
- session.widgetManager.removeLineWidget(w);
- editor.off("changeSelection", w.destroy);
- editor.off("changeSession", w.destroy);
- editor.off("mouseup", w.destroy);
- editor.off("change", w.destroy);
- };
-
- editor.keyBinding.addKeyboardHandler(kb);
- editor.on("changeSelection", w.destroy);
- editor.on("changeSession", w.destroy);
- editor.on("mouseup", w.destroy);
- editor.on("change", w.destroy);
-
- editor.session.widgetManager.addLineWidget(w);
-
- w.el.onmousedown = editor.focus.bind(editor);
-
- editor.renderer.scrollCursorIntoView(null, 0.5, {bottom: w.el.offsetHeight});
-};
-
-
-dom.importCssString("\
- .error_widget_wrapper {\
- background: inherit;\
- color: inherit;\
- border:none\
- }\
- .error_widget {\
- border-top: solid 2px;\
- border-bottom: solid 2px;\
- margin: 5px 0;\
- padding: 10px 40px;\
- white-space: pre-wrap;\
- }\
- .error_widget.ace_error, .error_widget_arrow.ace_error{\
- border-color: #ff5a5a\
- }\
- .error_widget.ace_warning, .error_widget_arrow.ace_warning{\
- border-color: #F1D817\
- }\
- .error_widget.ace_info, .error_widget_arrow.ace_info{\
- border-color: #5a5a5a\
- }\
- .error_widget.ace_ok, .error_widget_arrow.ace_ok{\
- border-color: #5aaa5a\
- }\
- .error_widget_arrow {\
- position: absolute;\
- border: solid 5px;\
- border-top-color: transparent!important;\
- border-right-color: transparent!important;\
- border-left-color: transparent!important;\
- top: -5px;\
- }\
-", "");
-
-});
-
-ace.define("ace/ace",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/dom","ace/lib/event","ace/editor","ace/edit_session","ace/undomanager","ace/virtual_renderer","ace/worker/worker_client","ace/keyboard/hash_handler","ace/placeholder","ace/multi_select","ace/mode/folding/fold_mode","ace/theme/textmate","ace/ext/error_marker","ace/config"], function(require, exports, module) {
-"use strict";
-
-require("./lib/fixoldbrowsers");
-
-var dom = require("./lib/dom");
-var event = require("./lib/event");
-
-var Editor = require("./editor").Editor;
-var EditSession = require("./edit_session").EditSession;
-var UndoManager = require("./undomanager").UndoManager;
-var Renderer = require("./virtual_renderer").VirtualRenderer;
-require("./worker/worker_client");
-require("./keyboard/hash_handler");
-require("./placeholder");
-require("./multi_select");
-require("./mode/folding/fold_mode");
-require("./theme/textmate");
-require("./ext/error_marker");
-
-exports.config = require("./config");
-exports.require = require;
-exports.edit = function(el) {
- if (typeof el == "string") {
- var _id = el;
- el = document.getElementById(_id);
- if (!el)
- throw new Error("ace.edit can't find div #" + _id);
- }
-
- if (el && el.env && el.env.editor instanceof Editor)
- return el.env.editor;
-
- var value = "";
- if (el && /input|textarea/i.test(el.tagName)) {
- var oldNode = el;
- value = oldNode.value;
- el = dom.createElement("pre");
- oldNode.parentNode.replaceChild(el, oldNode);
- } else if (el) {
- value = dom.getInnerText(el);
- el.innerHTML = "";
- }
-
- var doc = exports.createEditSession(value);
-
- var editor = new Editor(new Renderer(el));
- editor.setSession(doc);
-
- var env = {
- document: doc,
- editor: editor,
- onResize: editor.resize.bind(editor, null)
- };
- if (oldNode) env.textarea = oldNode;
- event.addListener(window, "resize", env.onResize);
- editor.on("destroy", function() {
- event.removeListener(window, "resize", env.onResize);
- env.editor.container.env = null; // prevent memory leak on old ie
- });
- editor.container.env = editor.env = env;
- return editor;
-};
-exports.createEditSession = function(text, mode) {
- var doc = new EditSession(text, mode);
- doc.setUndoManager(new UndoManager());
- return doc;
-}
-exports.EditSession = EditSession;
-exports.UndoManager = UndoManager;
-exports.version = "1.2.3";
-});
- (function() {
- ace.require(["ace/ace"], function(a) {
- a && a.config.init(true);
- if (!window.ace)
- window.ace = a;
- for (var key in a) if (a.hasOwnProperty(key))
- window.ace[key] = a[key];
- });
- })();
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-beautify.js b/icestudio/lib/ace-builds/src-noconflict/ext-beautify.js
deleted file mode 100644
index ba499b776..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-beautify.js
+++ /dev/null
@@ -1,334 +0,0 @@
-ace.define("ace/ext/beautify/php_rules",["require","exports","module","ace/token_iterator"], function(require, exports, module) {
-"use strict";
-var TokenIterator = require("ace/token_iterator").TokenIterator;
-exports.newLines = [{
- type: 'support.php_tag',
- value: ''
-}, {
- type: 'paren.lparen',
- value: '{',
- indent: true
-}, {
- type: 'paren.rparen',
- breakBefore: true,
- value: '}',
- indent: false
-}, {
- type: 'paren.rparen',
- breakBefore: true,
- value: '})',
- indent: false,
- dontBreak: true
-}, {
- type: 'comment'
-}, {
- type: 'text',
- value: ';'
-}, {
- type: 'text',
- value: ':',
- context: 'php'
-}, {
- type: 'keyword',
- value: 'case',
- indent: true,
- dontBreak: true
-}, {
- type: 'keyword',
- value: 'default',
- indent: true,
- dontBreak: true
-}, {
- type: 'keyword',
- value: 'break',
- indent: false,
- dontBreak: true
-}, {
- type: 'punctuation.doctype.end',
- value: '>'
-}, {
- type: 'meta.tag.punctuation.end',
- value: '>'
-}, {
- type: 'meta.tag.punctuation.begin',
- value: '<',
- blockTag: true,
- indent: true,
- dontBreak: true
-}, {
- type: 'meta.tag.punctuation.begin',
- value: '',
- indent: false,
- breakBefore: true,
- dontBreak: true
-}, {
- type: 'punctuation.operator',
- value: ';'
-}];
-
-exports.spaces = [{
- type: 'xml-pe',
- prepend: true
-},{
- type: 'entity.other.attribute-name',
- prepend: true
-}, {
- type: 'storage.type',
- value: 'var',
- append: true
-}, {
- type: 'storage.type',
- value: 'function',
- append: true
-}, {
- type: 'keyword.operator',
- value: '='
-}, {
- type: 'keyword',
- value: 'as',
- prepend: true,
- append: true
-}, {
- type: 'keyword',
- value: 'function',
- append: true
-}, {
- type: 'support.function',
- next: /[^\(]/,
- append: true
-}, {
- type: 'keyword',
- value: 'or',
- append: true,
- prepend: true
-}, {
- type: 'keyword',
- value: 'and',
- append: true,
- prepend: true
-}, {
- type: 'keyword',
- value: 'case',
- append: true
-}, {
- type: 'keyword.operator',
- value: '||',
- append: true,
- prepend: true
-}, {
- type: 'keyword.operator',
- value: '&&',
- append: true,
- prepend: true
-}];
-exports.singleTags = ['!doctype','area','base','br','hr','input','img','link','meta'];
-
-exports.transform = function(iterator, maxPos, context) {
- var token = iterator.getCurrentToken();
-
- var newLines = exports.newLines;
- var spaces = exports.spaces;
- var singleTags = exports.singleTags;
-
- var code = '';
-
- var indentation = 0;
- var dontBreak = false;
- var tag;
- var lastTag;
- var lastToken = {};
- var nextTag;
- var nextToken = {};
- var breakAdded = false;
- var value = '';
-
- while (token!==null) {
- console.log(token);
-
- if( !token ){
- token = iterator.stepForward();
- continue;
- }
- if( token.type == 'support.php_tag' && token.value != '?>' ){
- context = 'php';
- }
- else if( token.type == 'support.php_tag' && token.value == '?>' ){
- context = 'html';
- }
- else if( token.type == 'meta.tag.name.style' && context != 'css' ){
- context = 'css';
- }
- else if( token.type == 'meta.tag.name.style' && context == 'css' ){
- context = 'html';
- }
- else if( token.type == 'meta.tag.name.script' && context != 'js' ){
- context = 'js';
- }
- else if( token.type == 'meta.tag.name.script' && context == 'js' ){
- context = 'html';
- }
-
- nextToken = iterator.stepForward();
- if (nextToken && nextToken.type.indexOf('meta.tag.name') == 0) {
- nextTag = nextToken.value;
- }
- if ( lastToken.type == 'support.php_tag' && lastToken.value == '=') {
- dontBreak = true;
- }
- if (token.type == 'meta.tag.name') {
- token.value = token.value.toLowerCase();
- }
- if (token.type == 'text') {
- token.value = token.value.trim();
- }
- if (!token.value) {
- token = nextToken;
- continue;
- }
- value = token.value;
- for (var i in spaces) {
- if (
- token.type == spaces[i].type &&
- (!spaces[i].value || token.value == spaces[i].value) &&
- (
- nextToken &&
- (!spaces[i].next || spaces[i].next.test(nextToken.value))
- )
- ) {
- if (spaces[i].prepend) {
- value = ' ' + token.value;
- }
-
- if (spaces[i].append) {
- value += ' ';
- }
- }
- }
- if (token.type.indexOf('meta.tag.name') == 0) {
- tag = token.value;
- }
- breakAdded = false;
- for (i in newLines) {
- if (
- token.type == newLines[i].type &&
- (
- !newLines[i].value ||
- token.value == newLines[i].value
- ) &&
- (
- !newLines[i].blockTag ||
- singleTags.indexOf(nextTag) === -1
- ) &&
- (
- !newLines[i].context ||
- newLines[i].context === context
- )
- ) {
- if (newLines[i].indent === false) {
- indentation--;
- }
-
- if (
- newLines[i].breakBefore &&
- ( !newLines[i].prev || newLines[i].prev.test(lastToken.value) )
- ) {
- code += "\n";
- breakAdded = true;
- for (i = 0; i < indentation; i++) {
- code += "\t";
- }
- }
-
- break;
- }
- }
-
- if (dontBreak===false) {
- for (i in newLines) {
- if (
- lastToken.type == newLines[i].type &&
- (
- !newLines[i].value || lastToken.value == newLines[i].value
- ) &&
- (
- !newLines[i].blockTag ||
- singleTags.indexOf(tag) === -1
- ) &&
- (
- !newLines[i].context ||
- newLines[i].context === context
- )
- ) {
- if (newLines[i].indent === true) {
- indentation++;
- }
-
- if (!newLines[i].dontBreak && !breakAdded) {
- code += "\n";
- for (i = 0; i < indentation; i++) {
- code += "\t";
- }
- }
-
- break;
- }
- }
- }
-
- code += value;
- if ( lastToken.type == 'support.php_tag' && lastToken.value == '?>' ) {
- dontBreak = false;
- }
- lastTag = tag;
-
- lastToken = token;
-
- token = nextToken;
-
- if (token===null) {
- break;
- }
- }
-
- return code;
-};
-
-
-
-});
-
-ace.define("ace/ext/beautify",["require","exports","module","ace/token_iterator","ace/ext/beautify/php_rules"], function(require, exports, module) {
-"use strict";
-var TokenIterator = require("ace/token_iterator").TokenIterator;
-
-var phpTransform = require("./beautify/php_rules").transform;
-
-exports.beautify = function(session) {
- var iterator = new TokenIterator(session, 0, 0);
- var token = iterator.getCurrentToken();
-
- var context = session.$modeId.split("/").pop();
-
- var code = phpTransform(iterator, context);
- session.doc.setValue(code);
-};
-
-exports.commands = [{
- name: "beautify",
- exec: function(editor) {
- exports.beautify(editor.session);
- },
- bindKey: "Ctrl-Shift-B"
-}]
-
-});
- (function() {
- ace.require(["ace/ext/beautify"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-chromevox.js b/icestudio/lib/ace-builds/src-noconflict/ext-chromevox.js
deleted file mode 100644
index a321335c6..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-chromevox.js
+++ /dev/null
@@ -1,540 +0,0 @@
-ace.define("ace/ext/chromevox",["require","exports","module","ace/editor","ace/config"], function(require, exports, module) {
-var cvoxAce = {};
-cvoxAce.SpeechProperty;
-cvoxAce.Cursor;
-cvoxAce.Token;
-cvoxAce.Annotation;
-var CONSTANT_PROP = {
- 'rate': 0.8,
- 'pitch': 0.4,
- 'volume': 0.9
-};
-var DEFAULT_PROP = {
- 'rate': 1,
- 'pitch': 0.5,
- 'volume': 0.9
-};
-var ENTITY_PROP = {
- 'rate': 0.8,
- 'pitch': 0.8,
- 'volume': 0.9
-};
-var KEYWORD_PROP = {
- 'rate': 0.8,
- 'pitch': 0.3,
- 'volume': 0.9
-};
-var STORAGE_PROP = {
- 'rate': 0.8,
- 'pitch': 0.7,
- 'volume': 0.9
-};
-var VARIABLE_PROP = {
- 'rate': 0.8,
- 'pitch': 0.8,
- 'volume': 0.9
-};
-var DELETED_PROP = {
- 'punctuationEcho': 'none',
- 'relativePitch': -0.6
-};
-var ERROR_EARCON = 'ALERT_NONMODAL';
-var MODE_SWITCH_EARCON = 'ALERT_MODAL';
-var NO_MATCH_EARCON = 'INVALID_KEYPRESS';
-var INSERT_MODE_STATE = 'insertMode';
-var COMMAND_MODE_STATE = 'start';
-
-var REPLACE_LIST = [
- {
- substr: ';',
- newSubstr: ' semicolon '
- },
- {
- substr: ':',
- newSubstr: ' colon '
- }
-];
-var Command = {
- SPEAK_ANNOT: 'annots',
- SPEAK_ALL_ANNOTS: 'all_annots',
- TOGGLE_LOCATION: 'toggle_location',
- SPEAK_MODE: 'mode',
- SPEAK_ROW_COL: 'row_col',
- TOGGLE_DISPLACEMENT: 'toggle_displacement',
- FOCUS_TEXT: 'focus_text'
-};
-var KEY_PREFIX = 'CONTROL + SHIFT ';
-cvoxAce.editor = null;
-var lastCursor = null;
-var annotTable = {};
-var shouldSpeakRowLocation = false;
-var shouldSpeakDisplacement = false;
-var changed = false;
-var vimState = null;
-var keyCodeToShortcutMap = {};
-var cmdToShortcutMap = {};
-var getKeyShortcutString = function(keyCode) {
- return KEY_PREFIX + String.fromCharCode(keyCode);
-};
-var isVimMode = function() {
- var keyboardHandler = cvoxAce.editor.keyBinding.getKeyboardHandler();
- return keyboardHandler.$id === 'ace/keyboard/vim';
-};
-var getCurrentToken = function(cursor) {
- return cvoxAce.editor.getSession().getTokenAt(cursor.row, cursor.column + 1);
-};
-var getCurrentLine = function(cursor) {
- return cvoxAce.editor.getSession().getLine(cursor.row);
-};
-var onRowChange = function(currCursor) {
- if (annotTable[currCursor.row]) {
- cvox.Api.playEarcon(ERROR_EARCON);
- }
- if (shouldSpeakRowLocation) {
- cvox.Api.stop();
- speakChar(currCursor);
- speakTokenQueue(getCurrentToken(currCursor));
- speakLine(currCursor.row, 1);
- } else {
- speakLine(currCursor.row, 0);
- }
-};
-var isWord = function(cursor) {
- var line = getCurrentLine(cursor);
- var lineSuffix = line.substr(cursor.column - 1);
- if (cursor.column === 0) {
- lineSuffix = ' ' + line;
- }
- var firstWordRegExp = /^\W(\w+)/;
- var words = firstWordRegExp.exec(lineSuffix);
- return words !== null;
-};
-var rules = {
- 'constant': {
- prop: CONSTANT_PROP
- },
- 'entity': {
- prop: ENTITY_PROP
- },
- 'keyword': {
- prop: KEYWORD_PROP
- },
- 'storage': {
- prop: STORAGE_PROP
- },
- 'variable': {
- prop: VARIABLE_PROP
- },
- 'meta': {
- prop: DEFAULT_PROP,
- replace: [
- {
- substr: '',
- newSubstr: ' closing tag '
- },
- {
- substr: '/>',
- newSubstr: ' close tag '
- },
- {
- substr: '<',
- newSubstr: ' tag start '
- },
- {
- substr: '>',
- newSubstr: ' tag end '
- }
- ]
- }
-};
-var DEFAULT_RULE = {
- prop: DEFAULT_RULE
-};
-var expand = function(value, replaceRules) {
- var newValue = value;
- for (var i = 0; i < replaceRules.length; i++) {
- var replaceRule = replaceRules[i];
- var regexp = new RegExp(replaceRule.substr, 'g');
- newValue = newValue.replace(regexp, replaceRule.newSubstr);
- }
- return newValue;
-};
-var mergeTokens = function(tokens, start, end) {
- var newToken = {};
- newToken.value = '';
- newToken.type = tokens[start].type;
- for (var j = start; j < end; j++) {
- newToken.value += tokens[j].value;
- }
- return newToken;
-};
-var mergeLikeTokens = function(tokens) {
- if (tokens.length <= 1) {
- return tokens;
- }
- var newTokens = [];
- var lastLikeIndex = 0;
- for (var i = 1; i < tokens.length; i++) {
- var lastLikeToken = tokens[lastLikeIndex];
- var currToken = tokens[i];
- if (getTokenRule(lastLikeToken) !== getTokenRule(currToken)) {
- newTokens.push(mergeTokens(tokens, lastLikeIndex, i));
- lastLikeIndex = i;
- }
- }
- newTokens.push(mergeTokens(tokens, lastLikeIndex, tokens.length));
- return newTokens;
-};
-var isRowWhiteSpace = function(row) {
- var line = cvoxAce.editor.getSession().getLine(row);
- var whiteSpaceRegexp = /^\s*$/;
- return whiteSpaceRegexp.exec(line) !== null;
-};
-var speakLine = function(row, queue) {
- var tokens = cvoxAce.editor.getSession().getTokens(row);
- if (tokens.length === 0 || isRowWhiteSpace(row)) {
- cvox.Api.playEarcon('EDITABLE_TEXT');
- return;
- }
- tokens = mergeLikeTokens(tokens);
- var firstToken = tokens[0];
- tokens = tokens.filter(function(token) {
- return token !== firstToken;
- });
- speakToken_(firstToken, queue);
- tokens.forEach(speakTokenQueue);
-};
-var speakTokenFlush = function(token) {
- speakToken_(token, 0);
-};
-var speakTokenQueue = function(token) {
- speakToken_(token, 1);
-};
-var getTokenRule = function(token) {
- if (!token || !token.type) {
- return;
- }
- var split = token.type.split('.');
- if (split.length === 0) {
- return;
- }
- var type = split[0];
- var rule = rules[type];
- if (!rule) {
- return DEFAULT_RULE;
- }
- return rule;
-};
-var speakToken_ = function(token, queue) {
- var rule = getTokenRule(token);
- var value = expand(token.value, REPLACE_LIST);
- if (rule.replace) {
- value = expand(value, rule.replace);
- }
- cvox.Api.speak(value, queue, rule.prop);
-};
-var speakChar = function(cursor) {
- var line = getCurrentLine(cursor);
- cvox.Api.speak(line[cursor.column], 1);
-};
-var speakDisplacement = function(lastCursor, currCursor) {
- var line = getCurrentLine(currCursor);
- var displace = line.substring(lastCursor.column, currCursor.column);
- displace = displace.replace(/ /g, ' space ');
- cvox.Api.speak(displace);
-};
-var speakCharOrWordOrLine = function(lastCursor, currCursor) {
- if (Math.abs(lastCursor.column - currCursor.column) !== 1) {
- var currLineLength = getCurrentLine(currCursor).length;
- if (currCursor.column === 0 || currCursor.column === currLineLength) {
- speakLine(currCursor.row, 0);
- return;
- }
- if (isWord(currCursor)) {
- cvox.Api.stop();
- speakTokenQueue(getCurrentToken(currCursor));
- return;
- }
- }
- speakChar(currCursor);
-};
-var onColumnChange = function(lastCursor, currCursor) {
- if (!cvoxAce.editor.selection.isEmpty()) {
- speakDisplacement(lastCursor, currCursor);
- cvox.Api.speak('selected', 1);
- }
- else if (shouldSpeakDisplacement) {
- speakDisplacement(lastCursor, currCursor);
- } else {
- speakCharOrWordOrLine(lastCursor, currCursor);
- }
-};
-var onCursorChange = function(evt) {
- if (changed) {
- changed = false;
- return;
- }
- var currCursor = cvoxAce.editor.selection.getCursor();
- if (currCursor.row !== lastCursor.row) {
- onRowChange(currCursor);
- } else {
- onColumnChange(lastCursor, currCursor);
- }
- lastCursor = currCursor;
-};
-var onSelectionChange = function(evt) {
- if (cvoxAce.editor.selection.isEmpty()) {
- cvox.Api.speak('unselected');
- }
-};
-var onChange = function(delta) {
- switch (delta.action) {
- case 'remove':
- cvox.Api.speak(delta.text, 0, DELETED_PROP);
- changed = true;
- break;
- case 'insert':
- cvox.Api.speak(delta.text, 0);
- changed = true;
- break;
- }
-};
-var isNewAnnotation = function(annot) {
- var row = annot.row;
- var col = annot.column;
- return !annotTable[row] || !annotTable[row][col];
-};
-var populateAnnotations = function(annotations) {
- annotTable = {};
- for (var i = 0; i < annotations.length; i++) {
- var annotation = annotations[i];
- var row = annotation.row;
- var col = annotation.column;
- if (!annotTable[row]) {
- annotTable[row] = {};
- }
- annotTable[row][col] = annotation;
- }
-};
-var onAnnotationChange = function(evt) {
- var annotations = cvoxAce.editor.getSession().getAnnotations();
- var newAnnotations = annotations.filter(isNewAnnotation);
- if (newAnnotations.length > 0) {
- cvox.Api.playEarcon(ERROR_EARCON);
- }
- populateAnnotations(annotations);
-};
-var speakAnnot = function(annot) {
- var annotText = annot.type + ' ' + annot.text + ' on ' +
- rowColToString(annot.row, annot.column);
- annotText = annotText.replace(';', 'semicolon');
- cvox.Api.speak(annotText, 1);
-};
-var speakAnnotsByRow = function(row) {
- var annots = annotTable[row];
- for (var col in annots) {
- speakAnnot(annots[col]);
- }
-};
-var rowColToString = function(row, col) {
- return 'row ' + (row + 1) + ' column ' + (col + 1);
-};
-var speakCurrRowAndCol = function() {
- cvox.Api.speak(rowColToString(lastCursor.row, lastCursor.column));
-};
-var speakAllAnnots = function() {
- for (var row in annotTable) {
- speakAnnotsByRow(row);
- }
-};
-var speakMode = function() {
- if (!isVimMode()) {
- return;
- }
- switch (cvoxAce.editor.keyBinding.$data.state) {
- case INSERT_MODE_STATE:
- cvox.Api.speak('Insert mode');
- break;
- case COMMAND_MODE_STATE:
- cvox.Api.speak('Command mode');
- break;
- }
-};
-var toggleSpeakRowLocation = function() {
- shouldSpeakRowLocation = !shouldSpeakRowLocation;
- if (shouldSpeakRowLocation) {
- cvox.Api.speak('Speak location on row change enabled.');
- } else {
- cvox.Api.speak('Speak location on row change disabled.');
- }
-};
-var toggleSpeakDisplacement = function() {
- shouldSpeakDisplacement = !shouldSpeakDisplacement;
- if (shouldSpeakDisplacement) {
- cvox.Api.speak('Speak displacement on column changes.');
- } else {
- cvox.Api.speak('Speak current character or word on column changes.');
- }
-};
-var onKeyDown = function(evt) {
- if (evt.ctrlKey && evt.shiftKey) {
- var shortcut = keyCodeToShortcutMap[evt.keyCode];
- if (shortcut) {
- shortcut.func();
- }
- }
-};
-var onChangeStatus = function(evt, editor) {
- if (!isVimMode()) {
- return;
- }
- var state = editor.keyBinding.$data.state;
- if (state === vimState) {
- return;
- }
- switch (state) {
- case INSERT_MODE_STATE:
- cvox.Api.playEarcon(MODE_SWITCH_EARCON);
- cvox.Api.setKeyEcho(true);
- break;
- case COMMAND_MODE_STATE:
- cvox.Api.playEarcon(MODE_SWITCH_EARCON);
- cvox.Api.setKeyEcho(false);
- break;
- }
- vimState = state;
-};
-var contextMenuHandler = function(evt) {
- var cmd = evt.detail['customCommand'];
- var shortcut = cmdToShortcutMap[cmd];
- if (shortcut) {
- shortcut.func();
- cvoxAce.editor.focus();
- }
-};
-var initContextMenu = function() {
- var ACTIONS = SHORTCUTS.map(function(shortcut) {
- return {
- desc: shortcut.desc + getKeyShortcutString(shortcut.keyCode),
- cmd: shortcut.cmd
- };
- });
- var body = document.querySelector('body');
- body.setAttribute('contextMenuActions', JSON.stringify(ACTIONS));
- body.addEventListener('ATCustomEvent', contextMenuHandler, true);
-};
-var onFindSearchbox = function(evt) {
- if (evt.match) {
- speakLine(lastCursor.row, 0);
- } else {
- cvox.Api.playEarcon(NO_MATCH_EARCON);
- }
-};
-var focus = function() {
- cvoxAce.editor.focus();
-};
-var SHORTCUTS = [
- {
- keyCode: 49,
- func: function() {
- speakAnnotsByRow(lastCursor.row);
- },
- cmd: Command.SPEAK_ANNOT,
- desc: 'Speak annotations on line'
- },
- {
- keyCode: 50,
- func: speakAllAnnots,
- cmd: Command.SPEAK_ALL_ANNOTS,
- desc: 'Speak all annotations'
- },
- {
- keyCode: 51,
- func: speakMode,
- cmd: Command.SPEAK_MODE,
- desc: 'Speak Vim mode'
- },
- {
- keyCode: 52,
- func: toggleSpeakRowLocation,
- cmd: Command.TOGGLE_LOCATION,
- desc: 'Toggle speak row location'
- },
- {
- keyCode: 53,
- func: speakCurrRowAndCol,
- cmd: Command.SPEAK_ROW_COL,
- desc: 'Speak row and column'
- },
- {
- keyCode: 54,
- func: toggleSpeakDisplacement,
- cmd: Command.TOGGLE_DISPLACEMENT,
- desc: 'Toggle speak displacement'
- },
- {
- keyCode: 55,
- func: focus,
- cmd: Command.FOCUS_TEXT,
- desc: 'Focus text'
- }
-];
-var onFocus = function(_, editor) {
- cvoxAce.editor = editor;
- editor.getSession().selection.on('changeCursor', onCursorChange);
- editor.getSession().selection.on('changeSelection', onSelectionChange);
- editor.getSession().on('change', onChange);
- editor.getSession().on('changeAnnotation', onAnnotationChange);
- editor.on('changeStatus', onChangeStatus);
- editor.on('findSearchBox', onFindSearchbox);
- editor.container.addEventListener('keydown', onKeyDown);
-
- lastCursor = editor.selection.getCursor();
-};
-var init = function(editor) {
- onFocus(null, editor);
- SHORTCUTS.forEach(function(shortcut) {
- keyCodeToShortcutMap[shortcut.keyCode] = shortcut;
- cmdToShortcutMap[shortcut.cmd] = shortcut;
- });
-
- editor.on('focus', onFocus);
- if (isVimMode()) {
- cvox.Api.setKeyEcho(false);
- }
- initContextMenu();
-};
-function cvoxApiExists() {
- return (typeof(cvox) !== 'undefined') && cvox && cvox.Api;
-}
-var tries = 0;
-var MAX_TRIES = 15;
-function watchForCvoxLoad(editor) {
- if (cvoxApiExists()) {
- init(editor);
- } else {
- tries++;
- if (tries >= MAX_TRIES) {
- return;
- }
- window.setTimeout(watchForCvoxLoad, 500, editor);
- }
-}
-
-var Editor = require('../editor').Editor;
-require('../config').defineOptions(Editor.prototype, 'editor', {
- enableChromevoxEnhancements: {
- set: function(val) {
- if (val) {
- watchForCvoxLoad(this);
- }
- },
- value: true // turn it on by default or check for window.cvox
- }
-});
-
-});
- (function() {
- ace.require(["ace/ext/chromevox"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-elastic_tabstops_lite.js b/icestudio/lib/ace-builds/src-noconflict/ext-elastic_tabstops_lite.js
deleted file mode 100644
index 14e8855f1..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-elastic_tabstops_lite.js
+++ /dev/null
@@ -1,274 +0,0 @@
-ace.define("ace/ext/elastic_tabstops_lite",["require","exports","module","ace/editor","ace/config"], function(require, exports, module) {
-"use strict";
-
-var ElasticTabstopsLite = function(editor) {
- this.$editor = editor;
- var self = this;
- var changedRows = [];
- var recordChanges = false;
- this.onAfterExec = function() {
- recordChanges = false;
- self.processRows(changedRows);
- changedRows = [];
- };
- this.onExec = function() {
- recordChanges = true;
- };
- this.onChange = function(delta) {
- if (recordChanges) {
- if (changedRows.indexOf(delta.start.row) == -1)
- changedRows.push(delta.start.row);
- if (delta.end.row != delta.start.row)
- changedRows.push(delta.end.row);
- }
- };
-};
-
-(function() {
- this.processRows = function(rows) {
- this.$inChange = true;
- var checkedRows = [];
-
- for (var r = 0, rowCount = rows.length; r < rowCount; r++) {
- var row = rows[r];
-
- if (checkedRows.indexOf(row) > -1)
- continue;
-
- var cellWidthObj = this.$findCellWidthsForBlock(row);
- var cellWidths = this.$setBlockCellWidthsToMax(cellWidthObj.cellWidths);
- var rowIndex = cellWidthObj.firstRow;
-
- for (var w = 0, l = cellWidths.length; w < l; w++) {
- var widths = cellWidths[w];
- checkedRows.push(rowIndex);
- this.$adjustRow(rowIndex, widths);
- rowIndex++;
- }
- }
- this.$inChange = false;
- };
-
- this.$findCellWidthsForBlock = function(row) {
- var cellWidths = [], widths;
- var rowIter = row;
- while (rowIter >= 0) {
- widths = this.$cellWidthsForRow(rowIter);
- if (widths.length == 0)
- break;
-
- cellWidths.unshift(widths);
- rowIter--;
- }
- var firstRow = rowIter + 1;
- rowIter = row;
- var numRows = this.$editor.session.getLength();
-
- while (rowIter < numRows - 1) {
- rowIter++;
-
- widths = this.$cellWidthsForRow(rowIter);
- if (widths.length == 0)
- break;
-
- cellWidths.push(widths);
- }
-
- return { cellWidths: cellWidths, firstRow: firstRow };
- };
-
- this.$cellWidthsForRow = function(row) {
- var selectionColumns = this.$selectionColumnsForRow(row);
-
- var tabs = [-1].concat(this.$tabsForRow(row));
- var widths = tabs.map(function(el) { return 0; } ).slice(1);
- var line = this.$editor.session.getLine(row);
-
- for (var i = 0, len = tabs.length - 1; i < len; i++) {
- var leftEdge = tabs[i]+1;
- var rightEdge = tabs[i+1];
-
- var rightmostSelection = this.$rightmostSelectionInCell(selectionColumns, rightEdge);
- var cell = line.substring(leftEdge, rightEdge);
- widths[i] = Math.max(cell.replace(/\s+$/g,'').length, rightmostSelection - leftEdge);
- }
-
- return widths;
- };
-
- this.$selectionColumnsForRow = function(row) {
- var selections = [], cursor = this.$editor.getCursorPosition();
- if (this.$editor.session.getSelection().isEmpty()) {
- if (row == cursor.row)
- selections.push(cursor.column);
- }
-
- return selections;
- };
-
- this.$setBlockCellWidthsToMax = function(cellWidths) {
- var startingNewBlock = true, blockStartRow, blockEndRow, maxWidth;
- var columnInfo = this.$izip_longest(cellWidths);
-
- for (var c = 0, l = columnInfo.length; c < l; c++) {
- var column = columnInfo[c];
- if (!column.push) {
- console.error(column);
- continue;
- }
- column.push(NaN);
-
- for (var r = 0, s = column.length; r < s; r++) {
- var width = column[r];
- if (startingNewBlock) {
- blockStartRow = r;
- maxWidth = 0;
- startingNewBlock = false;
- }
- if (isNaN(width)) {
- blockEndRow = r;
-
- for (var j = blockStartRow; j < blockEndRow; j++) {
- cellWidths[j][c] = maxWidth;
- }
- startingNewBlock = true;
- }
-
- maxWidth = Math.max(maxWidth, width);
- }
- }
-
- return cellWidths;
- };
-
- this.$rightmostSelectionInCell = function(selectionColumns, cellRightEdge) {
- var rightmost = 0;
-
- if (selectionColumns.length) {
- var lengths = [];
- for (var s = 0, length = selectionColumns.length; s < length; s++) {
- if (selectionColumns[s] <= cellRightEdge)
- lengths.push(s);
- else
- lengths.push(0);
- }
- rightmost = Math.max.apply(Math, lengths);
- }
-
- return rightmost;
- };
-
- this.$tabsForRow = function(row) {
- var rowTabs = [], line = this.$editor.session.getLine(row),
- re = /\t/g, match;
-
- while ((match = re.exec(line)) != null) {
- rowTabs.push(match.index);
- }
-
- return rowTabs;
- };
-
- this.$adjustRow = function(row, widths) {
- var rowTabs = this.$tabsForRow(row);
-
- if (rowTabs.length == 0)
- return;
-
- var bias = 0, location = -1;
- var expandedSet = this.$izip(widths, rowTabs);
-
- for (var i = 0, l = expandedSet.length; i < l; i++) {
- var w = expandedSet[i][0], it = expandedSet[i][1];
- location += 1 + w;
- it += bias;
- var difference = location - it;
-
- if (difference == 0)
- continue;
-
- var partialLine = this.$editor.session.getLine(row).substr(0, it );
- var strippedPartialLine = partialLine.replace(/\s*$/g, "");
- var ispaces = partialLine.length - strippedPartialLine.length;
-
- if (difference > 0) {
- this.$editor.session.getDocument().insertInLine({row: row, column: it + 1}, Array(difference + 1).join(" ") + "\t");
- this.$editor.session.getDocument().removeInLine(row, it, it + 1);
-
- bias += difference;
- }
-
- if (difference < 0 && ispaces >= -difference) {
- this.$editor.session.getDocument().removeInLine(row, it + difference, it);
- bias += difference;
- }
- }
- };
- this.$izip_longest = function(iterables) {
- if (!iterables[0])
- return [];
- var longest = iterables[0].length;
- var iterablesLength = iterables.length;
-
- for (var i = 1; i < iterablesLength; i++) {
- var iLength = iterables[i].length;
- if (iLength > longest)
- longest = iLength;
- }
-
- var expandedSet = [];
-
- for (var l = 0; l < longest; l++) {
- var set = [];
- for (var i = 0; i < iterablesLength; i++) {
- if (iterables[i][l] === "")
- set.push(NaN);
- else
- set.push(iterables[i][l]);
- }
-
- expandedSet.push(set);
- }
-
-
- return expandedSet;
- };
- this.$izip = function(widths, tabs) {
- var size = widths.length >= tabs.length ? tabs.length : widths.length;
-
- var expandedSet = [];
- for (var i = 0; i < size; i++) {
- var set = [ widths[i], tabs[i] ];
- expandedSet.push(set);
- }
- return expandedSet;
- };
-
-}).call(ElasticTabstopsLite.prototype);
-
-exports.ElasticTabstopsLite = ElasticTabstopsLite;
-
-var Editor = require("../editor").Editor;
-require("../config").defineOptions(Editor.prototype, "editor", {
- useElasticTabstops: {
- set: function(val) {
- if (val) {
- if (!this.elasticTabstops)
- this.elasticTabstops = new ElasticTabstopsLite(this);
- this.commands.on("afterExec", this.elasticTabstops.onAfterExec);
- this.commands.on("exec", this.elasticTabstops.onExec);
- this.on("change", this.elasticTabstops.onChange);
- } else if (this.elasticTabstops) {
- this.commands.removeListener("afterExec", this.elasticTabstops.onAfterExec);
- this.commands.removeListener("exec", this.elasticTabstops.onExec);
- this.removeListener("change", this.elasticTabstops.onChange);
- }
- }
- }
-});
-
-});
- (function() {
- ace.require(["ace/ext/elastic_tabstops_lite"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-emmet.js b/icestudio/lib/ace-builds/src-noconflict/ext-emmet.js
deleted file mode 100644
index 2eeabe216..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-emmet.js
+++ /dev/null
@@ -1,1218 +0,0 @@
-ace.define("ace/snippets",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/anchor","ace/keyboard/hash_handler","ace/tokenizer","ace/lib/dom","ace/editor"], function(require, exports, module) {
-"use strict";
-var oop = require("./lib/oop");
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-var lang = require("./lib/lang");
-var Range = require("./range").Range;
-var Anchor = require("./anchor").Anchor;
-var HashHandler = require("./keyboard/hash_handler").HashHandler;
-var Tokenizer = require("./tokenizer").Tokenizer;
-var comparePoints = Range.comparePoints;
-
-var SnippetManager = function() {
- this.snippetMap = {};
- this.snippetNameMap = {};
-};
-
-(function() {
- oop.implement(this, EventEmitter);
-
- this.getTokenizer = function() {
- function TabstopToken(str, _, stack) {
- str = str.substr(1);
- if (/^\d+$/.test(str) && !stack.inFormatString)
- return [{tabstopId: parseInt(str, 10)}];
- return [{text: str}];
- }
- function escape(ch) {
- return "(?:[^\\\\" + ch + "]|\\\\.)";
- }
- SnippetManager.$tokenizer = new Tokenizer({
- start: [
- {regex: /:/, onMatch: function(val, state, stack) {
- if (stack.length && stack[0].expectIf) {
- stack[0].expectIf = false;
- stack[0].elseBranch = stack[0];
- return [stack[0]];
- }
- return ":";
- }},
- {regex: /\\./, onMatch: function(val, state, stack) {
- var ch = val[1];
- if (ch == "}" && stack.length) {
- val = ch;
- }else if ("`$\\".indexOf(ch) != -1) {
- val = ch;
- } else if (stack.inFormatString) {
- if (ch == "n")
- val = "\n";
- else if (ch == "t")
- val = "\n";
- else if ("ulULE".indexOf(ch) != -1) {
- val = {changeCase: ch, local: ch > "a"};
- }
- }
-
- return [val];
- }},
- {regex: /}/, onMatch: function(val, state, stack) {
- return [stack.length ? stack.shift() : val];
- }},
- {regex: /\$(?:\d+|\w+)/, onMatch: TabstopToken},
- {regex: /\$\{[\dA-Z_a-z]+/, onMatch: function(str, state, stack) {
- var t = TabstopToken(str.substr(1), state, stack);
- stack.unshift(t[0]);
- return t;
- }, next: "snippetVar"},
- {regex: /\n/, token: "newline", merge: false}
- ],
- snippetVar: [
- {regex: "\\|" + escape("\\|") + "*\\|", onMatch: function(val, state, stack) {
- stack[0].choices = val.slice(1, -1).split(",");
- }, next: "start"},
- {regex: "/(" + escape("/") + "+)/(?:(" + escape("/") + "*)/)(\\w*):?",
- onMatch: function(val, state, stack) {
- var ts = stack[0];
- ts.fmtString = val;
-
- val = this.splitRegex.exec(val);
- ts.guard = val[1];
- ts.fmt = val[2];
- ts.flag = val[3];
- return "";
- }, next: "start"},
- {regex: "`" + escape("`") + "*`", onMatch: function(val, state, stack) {
- stack[0].code = val.splice(1, -1);
- return "";
- }, next: "start"},
- {regex: "\\?", onMatch: function(val, state, stack) {
- if (stack[0])
- stack[0].expectIf = true;
- }, next: "start"},
- {regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "start"}
- ],
- formatString: [
- {regex: "/(" + escape("/") + "+)/", token: "regex"},
- {regex: "", onMatch: function(val, state, stack) {
- stack.inFormatString = true;
- }, next: "start"}
- ]
- });
- SnippetManager.prototype.getTokenizer = function() {
- return SnippetManager.$tokenizer;
- };
- return SnippetManager.$tokenizer;
- };
-
- this.tokenizeTmSnippet = function(str, startState) {
- return this.getTokenizer().getLineTokens(str, startState).tokens.map(function(x) {
- return x.value || x;
- });
- };
-
- this.$getDefaultValue = function(editor, name) {
- if (/^[A-Z]\d+$/.test(name)) {
- var i = name.substr(1);
- return (this.variables[name[0] + "__"] || {})[i];
- }
- if (/^\d+$/.test(name)) {
- return (this.variables.__ || {})[name];
- }
- name = name.replace(/^TM_/, "");
-
- if (!editor)
- return;
- var s = editor.session;
- switch(name) {
- case "CURRENT_WORD":
- var r = s.getWordRange();
- case "SELECTION":
- case "SELECTED_TEXT":
- return s.getTextRange(r);
- case "CURRENT_LINE":
- return s.getLine(editor.getCursorPosition().row);
- case "PREV_LINE": // not possible in textmate
- return s.getLine(editor.getCursorPosition().row - 1);
- case "LINE_INDEX":
- return editor.getCursorPosition().column;
- case "LINE_NUMBER":
- return editor.getCursorPosition().row + 1;
- case "SOFT_TABS":
- return s.getUseSoftTabs() ? "YES" : "NO";
- case "TAB_SIZE":
- return s.getTabSize();
- case "FILENAME":
- case "FILEPATH":
- return "";
- case "FULLNAME":
- return "Ace";
- }
- };
- this.variables = {};
- this.getVariableValue = function(editor, varName) {
- if (this.variables.hasOwnProperty(varName))
- return this.variables[varName](editor, varName) || "";
- return this.$getDefaultValue(editor, varName) || "";
- };
- this.tmStrFormat = function(str, ch, editor) {
- var flag = ch.flag || "";
- var re = ch.guard;
- re = new RegExp(re, flag.replace(/[^gi]/, ""));
- var fmtTokens = this.tokenizeTmSnippet(ch.fmt, "formatString");
- var _self = this;
- var formatted = str.replace(re, function() {
- _self.variables.__ = arguments;
- var fmtParts = _self.resolveVariables(fmtTokens, editor);
- var gChangeCase = "E";
- for (var i = 0; i < fmtParts.length; i++) {
- var ch = fmtParts[i];
- if (typeof ch == "object") {
- fmtParts[i] = "";
- if (ch.changeCase && ch.local) {
- var next = fmtParts[i + 1];
- if (next && typeof next == "string") {
- if (ch.changeCase == "u")
- fmtParts[i] = next[0].toUpperCase();
- else
- fmtParts[i] = next[0].toLowerCase();
- fmtParts[i + 1] = next.substr(1);
- }
- } else if (ch.changeCase) {
- gChangeCase = ch.changeCase;
- }
- } else if (gChangeCase == "U") {
- fmtParts[i] = ch.toUpperCase();
- } else if (gChangeCase == "L") {
- fmtParts[i] = ch.toLowerCase();
- }
- }
- return fmtParts.join("");
- });
- this.variables.__ = null;
- return formatted;
- };
-
- this.resolveVariables = function(snippet, editor) {
- var result = [];
- for (var i = 0; i < snippet.length; i++) {
- var ch = snippet[i];
- if (typeof ch == "string") {
- result.push(ch);
- } else if (typeof ch != "object") {
- continue;
- } else if (ch.skip) {
- gotoNext(ch);
- } else if (ch.processed < i) {
- continue;
- } else if (ch.text) {
- var value = this.getVariableValue(editor, ch.text);
- if (value && ch.fmtString)
- value = this.tmStrFormat(value, ch);
- ch.processed = i;
- if (ch.expectIf == null) {
- if (value) {
- result.push(value);
- gotoNext(ch);
- }
- } else {
- if (value) {
- ch.skip = ch.elseBranch;
- } else
- gotoNext(ch);
- }
- } else if (ch.tabstopId != null) {
- result.push(ch);
- } else if (ch.changeCase != null) {
- result.push(ch);
- }
- }
- function gotoNext(ch) {
- var i1 = snippet.indexOf(ch, i + 1);
- if (i1 != -1)
- i = i1;
- }
- return result;
- };
-
- this.insertSnippetForSelection = function(editor, snippetText) {
- var cursor = editor.getCursorPosition();
- var line = editor.session.getLine(cursor.row);
- var tabString = editor.session.getTabString();
- var indentString = line.match(/^\s*/)[0];
-
- if (cursor.column < indentString.length)
- indentString = indentString.slice(0, cursor.column);
-
- var tokens = this.tokenizeTmSnippet(snippetText);
- tokens = this.resolveVariables(tokens, editor);
- tokens = tokens.map(function(x) {
- if (x == "\n")
- return x + indentString;
- if (typeof x == "string")
- return x.replace(/\t/g, tabString);
- return x;
- });
- var tabstops = [];
- tokens.forEach(function(p, i) {
- if (typeof p != "object")
- return;
- var id = p.tabstopId;
- var ts = tabstops[id];
- if (!ts) {
- ts = tabstops[id] = [];
- ts.index = id;
- ts.value = "";
- }
- if (ts.indexOf(p) !== -1)
- return;
- ts.push(p);
- var i1 = tokens.indexOf(p, i + 1);
- if (i1 === -1)
- return;
-
- var value = tokens.slice(i + 1, i1);
- var isNested = value.some(function(t) {return typeof t === "object"});
- if (isNested && !ts.value) {
- ts.value = value;
- } else if (value.length && (!ts.value || typeof ts.value !== "string")) {
- ts.value = value.join("");
- }
- });
- tabstops.forEach(function(ts) {ts.length = 0});
- var expanding = {};
- function copyValue(val) {
- var copy = [];
- for (var i = 0; i < val.length; i++) {
- var p = val[i];
- if (typeof p == "object") {
- if (expanding[p.tabstopId])
- continue;
- var j = val.lastIndexOf(p, i - 1);
- p = copy[j] || {tabstopId: p.tabstopId};
- }
- copy[i] = p;
- }
- return copy;
- }
- for (var i = 0; i < tokens.length; i++) {
- var p = tokens[i];
- if (typeof p != "object")
- continue;
- var id = p.tabstopId;
- var i1 = tokens.indexOf(p, i + 1);
- if (expanding[id]) {
- if (expanding[id] === p)
- expanding[id] = null;
- continue;
- }
-
- var ts = tabstops[id];
- var arg = typeof ts.value == "string" ? [ts.value] : copyValue(ts.value);
- arg.unshift(i + 1, Math.max(0, i1 - i));
- arg.push(p);
- expanding[id] = p;
- tokens.splice.apply(tokens, arg);
-
- if (ts.indexOf(p) === -1)
- ts.push(p);
- }
- var row = 0, column = 0;
- var text = "";
- tokens.forEach(function(t) {
- if (typeof t === "string") {
- if (t[0] === "\n"){
- column = t.length - 1;
- row ++;
- } else
- column += t.length;
- text += t;
- } else {
- if (!t.start)
- t.start = {row: row, column: column};
- else
- t.end = {row: row, column: column};
- }
- });
- var range = editor.getSelectionRange();
- var end = editor.session.replace(range, text);
-
- var tabstopManager = new TabstopManager(editor);
- var selectionId = editor.inVirtualSelectionMode && editor.selection.index;
- tabstopManager.addTabstops(tabstops, range.start, end, selectionId);
- };
-
- this.insertSnippet = function(editor, snippetText) {
- var self = this;
- if (editor.inVirtualSelectionMode)
- return self.insertSnippetForSelection(editor, snippetText);
-
- editor.forEachSelection(function() {
- self.insertSnippetForSelection(editor, snippetText);
- }, null, {keepOrder: true});
-
- if (editor.tabstopManager)
- editor.tabstopManager.tabNext();
- };
-
- this.$getScope = function(editor) {
- var scope = editor.session.$mode.$id || "";
- scope = scope.split("/").pop();
- if (scope === "html" || scope === "php") {
- if (scope === "php" && !editor.session.$mode.inlinePhp)
- scope = "html";
- var c = editor.getCursorPosition();
- var state = editor.session.getState(c.row);
- if (typeof state === "object") {
- state = state[0];
- }
- if (state.substring) {
- if (state.substring(0, 3) == "js-")
- scope = "javascript";
- else if (state.substring(0, 4) == "css-")
- scope = "css";
- else if (state.substring(0, 4) == "php-")
- scope = "php";
- }
- }
-
- return scope;
- };
-
- this.getActiveScopes = function(editor) {
- var scope = this.$getScope(editor);
- var scopes = [scope];
- var snippetMap = this.snippetMap;
- if (snippetMap[scope] && snippetMap[scope].includeScopes) {
- scopes.push.apply(scopes, snippetMap[scope].includeScopes);
- }
- scopes.push("_");
- return scopes;
- };
-
- this.expandWithTab = function(editor, options) {
- var self = this;
- var result = editor.forEachSelection(function() {
- return self.expandSnippetForSelection(editor, options);
- }, null, {keepOrder: true});
- if (result && editor.tabstopManager)
- editor.tabstopManager.tabNext();
- return result;
- };
-
- this.expandSnippetForSelection = function(editor, options) {
- var cursor = editor.getCursorPosition();
- var line = editor.session.getLine(cursor.row);
- var before = line.substring(0, cursor.column);
- var after = line.substr(cursor.column);
-
- var snippetMap = this.snippetMap;
- var snippet;
- this.getActiveScopes(editor).some(function(scope) {
- var snippets = snippetMap[scope];
- if (snippets)
- snippet = this.findMatchingSnippet(snippets, before, after);
- return !!snippet;
- }, this);
- if (!snippet)
- return false;
- if (options && options.dryRun)
- return true;
- editor.session.doc.removeInLine(cursor.row,
- cursor.column - snippet.replaceBefore.length,
- cursor.column + snippet.replaceAfter.length
- );
-
- this.variables.M__ = snippet.matchBefore;
- this.variables.T__ = snippet.matchAfter;
- this.insertSnippetForSelection(editor, snippet.content);
-
- this.variables.M__ = this.variables.T__ = null;
- return true;
- };
-
- this.findMatchingSnippet = function(snippetList, before, after) {
- for (var i = snippetList.length; i--;) {
- var s = snippetList[i];
- if (s.startRe && !s.startRe.test(before))
- continue;
- if (s.endRe && !s.endRe.test(after))
- continue;
- if (!s.startRe && !s.endRe)
- continue;
-
- s.matchBefore = s.startRe ? s.startRe.exec(before) : [""];
- s.matchAfter = s.endRe ? s.endRe.exec(after) : [""];
- s.replaceBefore = s.triggerRe ? s.triggerRe.exec(before)[0] : "";
- s.replaceAfter = s.endTriggerRe ? s.endTriggerRe.exec(after)[0] : "";
- return s;
- }
- };
-
- this.snippetMap = {};
- this.snippetNameMap = {};
- this.register = function(snippets, scope) {
- var snippetMap = this.snippetMap;
- var snippetNameMap = this.snippetNameMap;
- var self = this;
-
- if (!snippets)
- snippets = [];
-
- function wrapRegexp(src) {
- if (src && !/^\^?\(.*\)\$?$|^\\b$/.test(src))
- src = "(?:" + src + ")";
-
- return src || "";
- }
- function guardedRegexp(re, guard, opening) {
- re = wrapRegexp(re);
- guard = wrapRegexp(guard);
- if (opening) {
- re = guard + re;
- if (re && re[re.length - 1] != "$")
- re = re + "$";
- } else {
- re = re + guard;
- if (re && re[0] != "^")
- re = "^" + re;
- }
- return new RegExp(re);
- }
-
- function addSnippet(s) {
- if (!s.scope)
- s.scope = scope || "_";
- scope = s.scope;
- if (!snippetMap[scope]) {
- snippetMap[scope] = [];
- snippetNameMap[scope] = {};
- }
-
- var map = snippetNameMap[scope];
- if (s.name) {
- var old = map[s.name];
- if (old)
- self.unregister(old);
- map[s.name] = s;
- }
- snippetMap[scope].push(s);
-
- if (s.tabTrigger && !s.trigger) {
- if (!s.guard && /^\w/.test(s.tabTrigger))
- s.guard = "\\b";
- s.trigger = lang.escapeRegExp(s.tabTrigger);
- }
-
- if (!s.trigger && !s.guard && !s.endTrigger && !s.endGuard)
- return;
-
- s.startRe = guardedRegexp(s.trigger, s.guard, true);
- s.triggerRe = new RegExp(s.trigger, "", true);
-
- s.endRe = guardedRegexp(s.endTrigger, s.endGuard, true);
- s.endTriggerRe = new RegExp(s.endTrigger, "", true);
- }
-
- if (snippets && snippets.content)
- addSnippet(snippets);
- else if (Array.isArray(snippets))
- snippets.forEach(addSnippet);
-
- this._signal("registerSnippets", {scope: scope});
- };
- this.unregister = function(snippets, scope) {
- var snippetMap = this.snippetMap;
- var snippetNameMap = this.snippetNameMap;
-
- function removeSnippet(s) {
- var nameMap = snippetNameMap[s.scope||scope];
- if (nameMap && nameMap[s.name]) {
- delete nameMap[s.name];
- var map = snippetMap[s.scope||scope];
- var i = map && map.indexOf(s);
- if (i >= 0)
- map.splice(i, 1);
- }
- }
- if (snippets.content)
- removeSnippet(snippets);
- else if (Array.isArray(snippets))
- snippets.forEach(removeSnippet);
- };
- this.parseSnippetFile = function(str) {
- str = str.replace(/\r/g, "");
- var list = [], snippet = {};
- var re = /^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;
- var m;
- while (m = re.exec(str)) {
- if (m[1]) {
- try {
- snippet = JSON.parse(m[1]);
- list.push(snippet);
- } catch (e) {}
- } if (m[4]) {
- snippet.content = m[4].replace(/^\t/gm, "");
- list.push(snippet);
- snippet = {};
- } else {
- var key = m[2], val = m[3];
- if (key == "regex") {
- var guardRe = /\/((?:[^\/\\]|\\.)*)|$/g;
- snippet.guard = guardRe.exec(val)[1];
- snippet.trigger = guardRe.exec(val)[1];
- snippet.endTrigger = guardRe.exec(val)[1];
- snippet.endGuard = guardRe.exec(val)[1];
- } else if (key == "snippet") {
- snippet.tabTrigger = val.match(/^\S*/)[0];
- if (!snippet.name)
- snippet.name = val;
- } else {
- snippet[key] = val;
- }
- }
- }
- return list;
- };
- this.getSnippetByName = function(name, editor) {
- var snippetMap = this.snippetNameMap;
- var snippet;
- this.getActiveScopes(editor).some(function(scope) {
- var snippets = snippetMap[scope];
- if (snippets)
- snippet = snippets[name];
- return !!snippet;
- }, this);
- return snippet;
- };
-
-}).call(SnippetManager.prototype);
-
-
-var TabstopManager = function(editor) {
- if (editor.tabstopManager)
- return editor.tabstopManager;
- editor.tabstopManager = this;
- this.$onChange = this.onChange.bind(this);
- this.$onChangeSelection = lang.delayedCall(this.onChangeSelection.bind(this)).schedule;
- this.$onChangeSession = this.onChangeSession.bind(this);
- this.$onAfterExec = this.onAfterExec.bind(this);
- this.attach(editor);
-};
-(function() {
- this.attach = function(editor) {
- this.index = 0;
- this.ranges = [];
- this.tabstops = [];
- this.$openTabstops = null;
- this.selectedTabstop = null;
-
- this.editor = editor;
- this.editor.on("change", this.$onChange);
- this.editor.on("changeSelection", this.$onChangeSelection);
- this.editor.on("changeSession", this.$onChangeSession);
- this.editor.commands.on("afterExec", this.$onAfterExec);
- this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
- };
- this.detach = function() {
- this.tabstops.forEach(this.removeTabstopMarkers, this);
- this.ranges = null;
- this.tabstops = null;
- this.selectedTabstop = null;
- this.editor.removeListener("change", this.$onChange);
- this.editor.removeListener("changeSelection", this.$onChangeSelection);
- this.editor.removeListener("changeSession", this.$onChangeSession);
- this.editor.commands.removeListener("afterExec", this.$onAfterExec);
- this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
- this.editor.tabstopManager = null;
- this.editor = null;
- };
-
- this.onChange = function(delta) {
- var changeRange = delta;
- var isRemove = delta.action[0] == "r";
- var start = delta.start;
- var end = delta.end;
- var startRow = start.row;
- var endRow = end.row;
- var lineDif = endRow - startRow;
- var colDiff = end.column - start.column;
-
- if (isRemove) {
- lineDif = -lineDif;
- colDiff = -colDiff;
- }
- if (!this.$inChange && isRemove) {
- var ts = this.selectedTabstop;
- var changedOutside = ts && !ts.some(function(r) {
- return comparePoints(r.start, start) <= 0 && comparePoints(r.end, end) >= 0;
- });
- if (changedOutside)
- return this.detach();
- }
- var ranges = this.ranges;
- for (var i = 0; i < ranges.length; i++) {
- var r = ranges[i];
- if (r.end.row < start.row)
- continue;
-
- if (isRemove && comparePoints(start, r.start) < 0 && comparePoints(end, r.end) > 0) {
- this.removeRange(r);
- i--;
- continue;
- }
-
- if (r.start.row == startRow && r.start.column > start.column)
- r.start.column += colDiff;
- if (r.end.row == startRow && r.end.column >= start.column)
- r.end.column += colDiff;
- if (r.start.row >= startRow)
- r.start.row += lineDif;
- if (r.end.row >= startRow)
- r.end.row += lineDif;
-
- if (comparePoints(r.start, r.end) > 0)
- this.removeRange(r);
- }
- if (!ranges.length)
- this.detach();
- };
- this.updateLinkedFields = function() {
- var ts = this.selectedTabstop;
- if (!ts || !ts.hasLinkedRanges)
- return;
- this.$inChange = true;
- var session = this.editor.session;
- var text = session.getTextRange(ts.firstNonLinked);
- for (var i = ts.length; i--;) {
- var range = ts[i];
- if (!range.linked)
- continue;
- var fmt = exports.snippetManager.tmStrFormat(text, range.original);
- session.replace(range, fmt);
- }
- this.$inChange = false;
- };
- this.onAfterExec = function(e) {
- if (e.command && !e.command.readOnly)
- this.updateLinkedFields();
- };
- this.onChangeSelection = function() {
- if (!this.editor)
- return;
- var lead = this.editor.selection.lead;
- var anchor = this.editor.selection.anchor;
- var isEmpty = this.editor.selection.isEmpty();
- for (var i = this.ranges.length; i--;) {
- if (this.ranges[i].linked)
- continue;
- var containsLead = this.ranges[i].contains(lead.row, lead.column);
- var containsAnchor = isEmpty || this.ranges[i].contains(anchor.row, anchor.column);
- if (containsLead && containsAnchor)
- return;
- }
- this.detach();
- };
- this.onChangeSession = function() {
- this.detach();
- };
- this.tabNext = function(dir) {
- var max = this.tabstops.length;
- var index = this.index + (dir || 1);
- index = Math.min(Math.max(index, 1), max);
- if (index == max)
- index = 0;
- this.selectTabstop(index);
- if (index === 0)
- this.detach();
- };
- this.selectTabstop = function(index) {
- this.$openTabstops = null;
- var ts = this.tabstops[this.index];
- if (ts)
- this.addTabstopMarkers(ts);
- this.index = index;
- ts = this.tabstops[this.index];
- if (!ts || !ts.length)
- return;
-
- this.selectedTabstop = ts;
- if (!this.editor.inVirtualSelectionMode) {
- var sel = this.editor.multiSelect;
- sel.toSingleRange(ts.firstNonLinked.clone());
- for (var i = ts.length; i--;) {
- if (ts.hasLinkedRanges && ts[i].linked)
- continue;
- sel.addRange(ts[i].clone(), true);
- }
- if (sel.ranges[0])
- sel.addRange(sel.ranges[0].clone());
- } else {
- this.editor.selection.setRange(ts.firstNonLinked);
- }
-
- this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
- };
- this.addTabstops = function(tabstops, start, end) {
- if (!this.$openTabstops)
- this.$openTabstops = [];
- if (!tabstops[0]) {
- var p = Range.fromPoints(end, end);
- moveRelative(p.start, start);
- moveRelative(p.end, start);
- tabstops[0] = [p];
- tabstops[0].index = 0;
- }
-
- var i = this.index;
- var arg = [i + 1, 0];
- var ranges = this.ranges;
- tabstops.forEach(function(ts, index) {
- var dest = this.$openTabstops[index] || ts;
-
- for (var i = ts.length; i--;) {
- var p = ts[i];
- var range = Range.fromPoints(p.start, p.end || p.start);
- movePoint(range.start, start);
- movePoint(range.end, start);
- range.original = p;
- range.tabstop = dest;
- ranges.push(range);
- if (dest != ts)
- dest.unshift(range);
- else
- dest[i] = range;
- if (p.fmtString) {
- range.linked = true;
- dest.hasLinkedRanges = true;
- } else if (!dest.firstNonLinked)
- dest.firstNonLinked = range;
- }
- if (!dest.firstNonLinked)
- dest.hasLinkedRanges = false;
- if (dest === ts) {
- arg.push(dest);
- this.$openTabstops[index] = dest;
- }
- this.addTabstopMarkers(dest);
- }, this);
-
- if (arg.length > 2) {
- if (this.tabstops.length)
- arg.push(arg.splice(2, 1)[0]);
- this.tabstops.splice.apply(this.tabstops, arg);
- }
- };
-
- this.addTabstopMarkers = function(ts) {
- var session = this.editor.session;
- ts.forEach(function(range) {
- if (!range.markerId)
- range.markerId = session.addMarker(range, "ace_snippet-marker", "text");
- });
- };
- this.removeTabstopMarkers = function(ts) {
- var session = this.editor.session;
- ts.forEach(function(range) {
- session.removeMarker(range.markerId);
- range.markerId = null;
- });
- };
- this.removeRange = function(range) {
- var i = range.tabstop.indexOf(range);
- range.tabstop.splice(i, 1);
- i = this.ranges.indexOf(range);
- this.ranges.splice(i, 1);
- this.editor.session.removeMarker(range.markerId);
- if (!range.tabstop.length) {
- i = this.tabstops.indexOf(range.tabstop);
- if (i != -1)
- this.tabstops.splice(i, 1);
- if (!this.tabstops.length)
- this.detach();
- }
- };
-
- this.keyboardHandler = new HashHandler();
- this.keyboardHandler.bindKeys({
- "Tab": function(ed) {
- if (exports.snippetManager && exports.snippetManager.expandWithTab(ed)) {
- return;
- }
-
- ed.tabstopManager.tabNext(1);
- },
- "Shift-Tab": function(ed) {
- ed.tabstopManager.tabNext(-1);
- },
- "Esc": function(ed) {
- ed.tabstopManager.detach();
- },
- "Return": function(ed) {
- return false;
- }
- });
-}).call(TabstopManager.prototype);
-
-
-
-var changeTracker = {};
-changeTracker.onChange = Anchor.prototype.onChange;
-changeTracker.setPosition = function(row, column) {
- this.pos.row = row;
- this.pos.column = column;
-};
-changeTracker.update = function(pos, delta, $insertRight) {
- this.$insertRight = $insertRight;
- this.pos = pos;
- this.onChange(delta);
-};
-
-var movePoint = function(point, diff) {
- if (point.row == 0)
- point.column += diff.column;
- point.row += diff.row;
-};
-
-var moveRelative = function(point, start) {
- if (point.row == start.row)
- point.column -= start.column;
- point.row -= start.row;
-};
-
-
-require("./lib/dom").importCssString("\
-.ace_snippet-marker {\
- -moz-box-sizing: border-box;\
- box-sizing: border-box;\
- background: rgba(194, 193, 208, 0.09);\
- border: 1px dotted rgba(211, 208, 235, 0.62);\
- position: absolute;\
-}");
-
-exports.snippetManager = new SnippetManager();
-
-
-var Editor = require("./editor").Editor;
-(function() {
- this.insertSnippet = function(content, options) {
- return exports.snippetManager.insertSnippet(this, content, options);
- };
- this.expandSnippet = function(options) {
- return exports.snippetManager.expandWithTab(this, options);
- };
-}).call(Editor.prototype);
-
-});
-
-ace.define("ace/ext/emmet",["require","exports","module","ace/keyboard/hash_handler","ace/editor","ace/snippets","ace/range","resources","resources","range","tabStops","resources","utils","actions","ace/config","ace/config"], function(require, exports, module) {
-"use strict";
-var HashHandler = require("ace/keyboard/hash_handler").HashHandler;
-var Editor = require("ace/editor").Editor;
-var snippetManager = require("ace/snippets").snippetManager;
-var Range = require("ace/range").Range;
-var emmet, emmetPath;
-function AceEmmetEditor() {}
-
-AceEmmetEditor.prototype = {
- setupContext: function(editor) {
- this.ace = editor;
- this.indentation = editor.session.getTabString();
- if (!emmet)
- emmet = window.emmet;
- emmet.require("resources").setVariable("indentation", this.indentation);
- this.$syntax = null;
- this.$syntax = this.getSyntax();
- },
- getSelectionRange: function() {
- var range = this.ace.getSelectionRange();
- var doc = this.ace.session.doc;
- return {
- start: doc.positionToIndex(range.start),
- end: doc.positionToIndex(range.end)
- };
- },
- createSelection: function(start, end) {
- var doc = this.ace.session.doc;
- this.ace.selection.setRange({
- start: doc.indexToPosition(start),
- end: doc.indexToPosition(end)
- });
- },
- getCurrentLineRange: function() {
- var ace = this.ace;
- var row = ace.getCursorPosition().row;
- var lineLength = ace.session.getLine(row).length;
- var index = ace.session.doc.positionToIndex({row: row, column: 0});
- return {
- start: index,
- end: index + lineLength
- };
- },
- getCaretPos: function(){
- var pos = this.ace.getCursorPosition();
- return this.ace.session.doc.positionToIndex(pos);
- },
- setCaretPos: function(index){
- var pos = this.ace.session.doc.indexToPosition(index);
- this.ace.selection.moveToPosition(pos);
- },
- getCurrentLine: function() {
- var row = this.ace.getCursorPosition().row;
- return this.ace.session.getLine(row);
- },
- replaceContent: function(value, start, end, noIndent) {
- if (end == null)
- end = start == null ? this.getContent().length : start;
- if (start == null)
- start = 0;
-
- var editor = this.ace;
- var doc = editor.session.doc;
- var range = Range.fromPoints(doc.indexToPosition(start), doc.indexToPosition(end));
- editor.session.remove(range);
-
- range.end = range.start;
-
- value = this.$updateTabstops(value);
- snippetManager.insertSnippet(editor, value);
- },
- getContent: function(){
- return this.ace.getValue();
- },
- getSyntax: function() {
- if (this.$syntax)
- return this.$syntax;
- var syntax = this.ace.session.$modeId.split("/").pop();
- if (syntax == "html" || syntax == "php") {
- var cursor = this.ace.getCursorPosition();
- var state = this.ace.session.getState(cursor.row);
- if (typeof state != "string")
- state = state[0];
- if (state) {
- state = state.split("-");
- if (state.length > 1)
- syntax = state[0];
- else if (syntax == "php")
- syntax = "html";
- }
- }
- return syntax;
- },
- getProfileName: function() {
- switch (this.getSyntax()) {
- case "css": return "css";
- case "xml":
- case "xsl":
- return "xml";
- case "html":
- var profile = emmet.require("resources").getVariable("profile");
- if (!profile)
- profile = this.ace.session.getLines(0,2).join("").search(/]+XHTML/i) != -1 ? "xhtml": "html";
- return profile;
- default:
- var mode = this.ace.session.$mode;
- return mode.emmetConfig && mode.emmetConfig.profile || "xhtml";
- }
- },
- prompt: function(title) {
- return prompt(title);
- },
- getSelection: function() {
- return this.ace.session.getTextRange();
- },
- getFilePath: function() {
- return "";
- },
- $updateTabstops: function(value) {
- var base = 1000;
- var zeroBase = 0;
- var lastZero = null;
- var range = emmet.require('range');
- var ts = emmet.require('tabStops');
- var settings = emmet.require('resources').getVocabulary("user");
- var tabstopOptions = {
- tabstop: function(data) {
- var group = parseInt(data.group, 10);
- var isZero = group === 0;
- if (isZero)
- group = ++zeroBase;
- else
- group += base;
-
- var placeholder = data.placeholder;
- if (placeholder) {
- placeholder = ts.processText(placeholder, tabstopOptions);
- }
-
- var result = '${' + group + (placeholder ? ':' + placeholder : '') + '}';
-
- if (isZero) {
- lastZero = range.create(data.start, result);
- }
-
- return result;
- },
- escape: function(ch) {
- if (ch == '$') return '\\$';
- if (ch == '\\') return '\\\\';
- return ch;
- }
- };
-
- value = ts.processText(value, tabstopOptions);
-
- if (settings.variables['insert_final_tabstop'] && !/\$\{0\}$/.test(value)) {
- value += '${0}';
- } else if (lastZero) {
- value = emmet.require('utils').replaceSubstring(value, '${0}', lastZero);
- }
-
- return value;
- }
-};
-
-
-var keymap = {
- expand_abbreviation: {"mac": "ctrl+alt+e", "win": "alt+e"},
- match_pair_outward: {"mac": "ctrl+d", "win": "ctrl+,"},
- match_pair_inward: {"mac": "ctrl+j", "win": "ctrl+shift+0"},
- matching_pair: {"mac": "ctrl+alt+j", "win": "alt+j"},
- next_edit_point: "alt+right",
- prev_edit_point: "alt+left",
- toggle_comment: {"mac": "command+/", "win": "ctrl+/"},
- split_join_tag: {"mac": "shift+command+'", "win": "shift+ctrl+`"},
- remove_tag: {"mac": "command+'", "win": "shift+ctrl+;"},
- evaluate_math_expression: {"mac": "shift+command+y", "win": "shift+ctrl+y"},
- increment_number_by_1: "ctrl+up",
- decrement_number_by_1: "ctrl+down",
- increment_number_by_01: "alt+up",
- decrement_number_by_01: "alt+down",
- increment_number_by_10: {"mac": "alt+command+up", "win": "shift+alt+up"},
- decrement_number_by_10: {"mac": "alt+command+down", "win": "shift+alt+down"},
- select_next_item: {"mac": "shift+command+.", "win": "shift+ctrl+."},
- select_previous_item: {"mac": "shift+command+,", "win": "shift+ctrl+,"},
- reflect_css_value: {"mac": "shift+command+r", "win": "shift+ctrl+r"},
-
- encode_decode_data_url: {"mac": "shift+ctrl+d", "win": "ctrl+'"},
- expand_abbreviation_with_tab: "Tab",
- wrap_with_abbreviation: {"mac": "shift+ctrl+a", "win": "shift+ctrl+a"}
-};
-
-var editorProxy = new AceEmmetEditor();
-exports.commands = new HashHandler();
-exports.runEmmetCommand = function runEmmetCommand(editor) {
- try {
- editorProxy.setupContext(editor);
- var actions = emmet.require("actions");
-
- if (this.action == "expand_abbreviation_with_tab") {
- if (!editor.selection.isEmpty())
- return false;
- var pos = editor.selection.lead;
- var token = editor.session.getTokenAt(pos.row, pos.column);
- if (token && /\btag\b/.test(token.type))
- return false;
- }
-
- if (this.action == "wrap_with_abbreviation") {
- return setTimeout(function() {
- actions.run("wrap_with_abbreviation", editorProxy);
- }, 0);
- }
-
- var result = actions.run(this.action, editorProxy);
- } catch(e) {
- if (!emmet) {
- load(runEmmetCommand.bind(this, editor));
- return true;
- }
- editor._signal("changeStatus", typeof e == "string" ? e : e.message);
- console.log(e);
- result = false;
- }
- return result;
-};
-
-for (var command in keymap) {
- exports.commands.addCommand({
- name: "emmet:" + command,
- action: command,
- bindKey: keymap[command],
- exec: exports.runEmmetCommand,
- multiSelectAction: "forEach"
- });
-}
-
-exports.updateCommands = function(editor, enabled) {
- if (enabled) {
- editor.keyBinding.addKeyboardHandler(exports.commands);
- } else {
- editor.keyBinding.removeKeyboardHandler(exports.commands);
- }
-};
-
-exports.isSupportedMode = function(mode) {
- if (!mode) return false;
- if (mode.emmetConfig) return true;
- var id = mode.$id || mode;
- return /css|less|scss|sass|stylus|html|php|twig|ejs|handlebars/.test(id);
-};
-
-exports.isAvailable = function(editor, command) {
- if (/(evaluate_math_expression|expand_abbreviation)$/.test(command))
- return true;
- var mode = editor.session.$mode;
- var isSupported = exports.isSupportedMode(mode);
- if (isSupported && mode.$modes) {
- try {
- editorProxy.setupContext(editor);
- if (/js|php/.test(editorProxy.getSyntax()))
- isSupported = false;
- } catch(e) {}
- }
- return isSupported;
-}
-
-var onChangeMode = function(e, target) {
- var editor = target;
- if (!editor)
- return;
- var enabled = exports.isSupportedMode(editor.session.$mode);
- if (e.enableEmmet === false)
- enabled = false;
- if (enabled)
- load();
- exports.updateCommands(editor, enabled);
-};
-
-var load = function(cb) {
- if (typeof emmetPath == "string") {
- require("ace/config").loadModule(emmetPath, function() {
- emmetPath = null;
- cb && cb();
- });
- }
-};
-
-exports.AceEmmetEditor = AceEmmetEditor;
-require("ace/config").defineOptions(Editor.prototype, "editor", {
- enableEmmet: {
- set: function(val) {
- this[val ? "on" : "removeListener"]("changeMode", onChangeMode);
- onChangeMode({enableEmmet: !!val}, this);
- },
- value: true
- }
-});
-
-exports.setCore = function(e) {
- if (typeof e == "string")
- emmetPath = e;
- else
- emmet = e;
-};
-});
- (function() {
- ace.require(["ace/ext/emmet"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-error_marker.js b/icestudio/lib/ace-builds/src-noconflict/ext-error_marker.js
deleted file mode 100644
index d4c9eb913..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-error_marker.js
+++ /dev/null
@@ -1,6 +0,0 @@
-
-;
- (function() {
- ace.require(["ace/ext/error_marker"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-keybinding_menu.js b/icestudio/lib/ace-builds/src-noconflict/ext-keybinding_menu.js
deleted file mode 100644
index ede7d8dbe..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-keybinding_menu.js
+++ /dev/null
@@ -1,170 +0,0 @@
-ace.define("ace/ext/menu_tools/overlay_page",["require","exports","module","ace/lib/dom"], function(require, exports, module) {
-'use strict';
-var dom = require("../../lib/dom");
-var cssText = "#ace_settingsmenu, #kbshortcutmenu {\
-background-color: #F7F7F7;\
-color: black;\
-box-shadow: -5px 4px 5px rgba(126, 126, 126, 0.55);\
-padding: 1em 0.5em 2em 1em;\
-overflow: auto;\
-position: absolute;\
-margin: 0;\
-bottom: 0;\
-right: 0;\
-top: 0;\
-z-index: 9991;\
-cursor: default;\
-}\
-.ace_dark #ace_settingsmenu, .ace_dark #kbshortcutmenu {\
-box-shadow: -20px 10px 25px rgba(126, 126, 126, 0.25);\
-background-color: rgba(255, 255, 255, 0.6);\
-color: black;\
-}\
-.ace_optionsMenuEntry:hover {\
-background-color: rgba(100, 100, 100, 0.1);\
--webkit-transition: all 0.5s;\
-transition: all 0.3s\
-}\
-.ace_closeButton {\
-background: rgba(245, 146, 146, 0.5);\
-border: 1px solid #F48A8A;\
-border-radius: 50%;\
-padding: 7px;\
-position: absolute;\
-right: -8px;\
-top: -8px;\
-z-index: 1000;\
-}\
-.ace_closeButton{\
-background: rgba(245, 146, 146, 0.9);\
-}\
-.ace_optionsMenuKey {\
-color: darkslateblue;\
-font-weight: bold;\
-}\
-.ace_optionsMenuCommand {\
-color: darkcyan;\
-font-weight: normal;\
-}";
-dom.importCssString(cssText);
-module.exports.overlayPage = function overlayPage(editor, contentElement, top, right, bottom, left) {
- top = top ? 'top: ' + top + ';' : '';
- bottom = bottom ? 'bottom: ' + bottom + ';' : '';
- right = right ? 'right: ' + right + ';' : '';
- left = left ? 'left: ' + left + ';' : '';
-
- var closer = document.createElement('div');
- var contentContainer = document.createElement('div');
-
- function documentEscListener(e) {
- if (e.keyCode === 27) {
- closer.click();
- }
- }
-
- closer.style.cssText = 'margin: 0; padding: 0; ' +
- 'position: fixed; top:0; bottom:0; left:0; right:0;' +
- 'z-index: 9990; ' +
- 'background-color: rgba(0, 0, 0, 0.3);';
- closer.addEventListener('click', function() {
- document.removeEventListener('keydown', documentEscListener);
- closer.parentNode.removeChild(closer);
- editor.focus();
- closer = null;
- });
- document.addEventListener('keydown', documentEscListener);
-
- contentContainer.style.cssText = top + right + bottom + left;
- contentContainer.addEventListener('click', function(e) {
- e.stopPropagation();
- });
-
- var wrapper = dom.createElement("div");
- wrapper.style.position = "relative";
-
- var closeButton = dom.createElement("div");
- closeButton.className = "ace_closeButton";
- closeButton.addEventListener('click', function() {
- closer.click();
- });
-
- wrapper.appendChild(closeButton);
- contentContainer.appendChild(wrapper);
-
- contentContainer.appendChild(contentElement);
- closer.appendChild(contentContainer);
- document.body.appendChild(closer);
- editor.blur();
-};
-
-});
-
-ace.define("ace/ext/menu_tools/get_editor_keyboard_shortcuts",["require","exports","module","ace/lib/keys"], function(require, exports, module) {
-"use strict";
-var keys = require("../../lib/keys");
-module.exports.getEditorKeybordShortcuts = function(editor) {
- var KEY_MODS = keys.KEY_MODS;
- var keybindings = [];
- var commandMap = {};
- editor.keyBinding.$handlers.forEach(function(handler) {
- var ckb = handler.commandKeyBinding;
- for (var i in ckb) {
- var key = i.replace(/(^|-)\w/g, function(x) { return x.toUpperCase(); });
- var commands = ckb[i];
- if (!Array.isArray(commands))
- commands = [commands];
- commands.forEach(function(command) {
- if (typeof command != "string")
- command = command.name
- if (commandMap[command]) {
- commandMap[command].key += "|" + key;
- } else {
- commandMap[command] = {key: key, command: command};
- keybindings.push(commandMap[command]);
- }
- });
- }
- });
- return keybindings;
-};
-
-});
-
-ace.define("ace/ext/keybinding_menu",["require","exports","module","ace/editor","ace/ext/menu_tools/overlay_page","ace/ext/menu_tools/get_editor_keyboard_shortcuts"], function(require, exports, module) {
- "use strict";
- var Editor = require("ace/editor").Editor;
- function showKeyboardShortcuts (editor) {
- if(!document.getElementById('kbshortcutmenu')) {
- var overlayPage = require('./menu_tools/overlay_page').overlayPage;
- var getEditorKeybordShortcuts = require('./menu_tools/get_editor_keyboard_shortcuts').getEditorKeybordShortcuts;
- var kb = getEditorKeybordShortcuts(editor);
- var el = document.createElement('div');
- var commands = kb.reduce(function(previous, current) {
- return previous + '';
- }, '');
-
- el.id = 'kbshortcutmenu';
- el.innerHTML = '
Keyboard Shortcuts
' + commands + '
';
- overlayPage(editor, el, '0', '0', '0', null);
- }
- }
- module.exports.init = function(editor) {
- Editor.prototype.showKeyboardShortcuts = function() {
- showKeyboardShortcuts(this);
- };
- editor.commands.addCommands([{
- name: "showKeyboardShortcuts",
- bindKey: {win: "Ctrl-Alt-h", mac: "Command-Alt-h"},
- exec: function(editor, line) {
- editor.showKeyboardShortcuts();
- }
- }]);
- };
-
-});
- (function() {
- ace.require(["ace/ext/keybinding_menu"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-language_tools.js b/icestudio/lib/ace-builds/src-noconflict/ext-language_tools.js
deleted file mode 100644
index ac86ae9cc..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-language_tools.js
+++ /dev/null
@@ -1,1938 +0,0 @@
-ace.define("ace/snippets",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/anchor","ace/keyboard/hash_handler","ace/tokenizer","ace/lib/dom","ace/editor"], function(require, exports, module) {
-"use strict";
-var oop = require("./lib/oop");
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-var lang = require("./lib/lang");
-var Range = require("./range").Range;
-var Anchor = require("./anchor").Anchor;
-var HashHandler = require("./keyboard/hash_handler").HashHandler;
-var Tokenizer = require("./tokenizer").Tokenizer;
-var comparePoints = Range.comparePoints;
-
-var SnippetManager = function() {
- this.snippetMap = {};
- this.snippetNameMap = {};
-};
-
-(function() {
- oop.implement(this, EventEmitter);
-
- this.getTokenizer = function() {
- function TabstopToken(str, _, stack) {
- str = str.substr(1);
- if (/^\d+$/.test(str) && !stack.inFormatString)
- return [{tabstopId: parseInt(str, 10)}];
- return [{text: str}];
- }
- function escape(ch) {
- return "(?:[^\\\\" + ch + "]|\\\\.)";
- }
- SnippetManager.$tokenizer = new Tokenizer({
- start: [
- {regex: /:/, onMatch: function(val, state, stack) {
- if (stack.length && stack[0].expectIf) {
- stack[0].expectIf = false;
- stack[0].elseBranch = stack[0];
- return [stack[0]];
- }
- return ":";
- }},
- {regex: /\\./, onMatch: function(val, state, stack) {
- var ch = val[1];
- if (ch == "}" && stack.length) {
- val = ch;
- }else if ("`$\\".indexOf(ch) != -1) {
- val = ch;
- } else if (stack.inFormatString) {
- if (ch == "n")
- val = "\n";
- else if (ch == "t")
- val = "\n";
- else if ("ulULE".indexOf(ch) != -1) {
- val = {changeCase: ch, local: ch > "a"};
- }
- }
-
- return [val];
- }},
- {regex: /}/, onMatch: function(val, state, stack) {
- return [stack.length ? stack.shift() : val];
- }},
- {regex: /\$(?:\d+|\w+)/, onMatch: TabstopToken},
- {regex: /\$\{[\dA-Z_a-z]+/, onMatch: function(str, state, stack) {
- var t = TabstopToken(str.substr(1), state, stack);
- stack.unshift(t[0]);
- return t;
- }, next: "snippetVar"},
- {regex: /\n/, token: "newline", merge: false}
- ],
- snippetVar: [
- {regex: "\\|" + escape("\\|") + "*\\|", onMatch: function(val, state, stack) {
- stack[0].choices = val.slice(1, -1).split(",");
- }, next: "start"},
- {regex: "/(" + escape("/") + "+)/(?:(" + escape("/") + "*)/)(\\w*):?",
- onMatch: function(val, state, stack) {
- var ts = stack[0];
- ts.fmtString = val;
-
- val = this.splitRegex.exec(val);
- ts.guard = val[1];
- ts.fmt = val[2];
- ts.flag = val[3];
- return "";
- }, next: "start"},
- {regex: "`" + escape("`") + "*`", onMatch: function(val, state, stack) {
- stack[0].code = val.splice(1, -1);
- return "";
- }, next: "start"},
- {regex: "\\?", onMatch: function(val, state, stack) {
- if (stack[0])
- stack[0].expectIf = true;
- }, next: "start"},
- {regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "start"}
- ],
- formatString: [
- {regex: "/(" + escape("/") + "+)/", token: "regex"},
- {regex: "", onMatch: function(val, state, stack) {
- stack.inFormatString = true;
- }, next: "start"}
- ]
- });
- SnippetManager.prototype.getTokenizer = function() {
- return SnippetManager.$tokenizer;
- };
- return SnippetManager.$tokenizer;
- };
-
- this.tokenizeTmSnippet = function(str, startState) {
- return this.getTokenizer().getLineTokens(str, startState).tokens.map(function(x) {
- return x.value || x;
- });
- };
-
- this.$getDefaultValue = function(editor, name) {
- if (/^[A-Z]\d+$/.test(name)) {
- var i = name.substr(1);
- return (this.variables[name[0] + "__"] || {})[i];
- }
- if (/^\d+$/.test(name)) {
- return (this.variables.__ || {})[name];
- }
- name = name.replace(/^TM_/, "");
-
- if (!editor)
- return;
- var s = editor.session;
- switch(name) {
- case "CURRENT_WORD":
- var r = s.getWordRange();
- case "SELECTION":
- case "SELECTED_TEXT":
- return s.getTextRange(r);
- case "CURRENT_LINE":
- return s.getLine(editor.getCursorPosition().row);
- case "PREV_LINE": // not possible in textmate
- return s.getLine(editor.getCursorPosition().row - 1);
- case "LINE_INDEX":
- return editor.getCursorPosition().column;
- case "LINE_NUMBER":
- return editor.getCursorPosition().row + 1;
- case "SOFT_TABS":
- return s.getUseSoftTabs() ? "YES" : "NO";
- case "TAB_SIZE":
- return s.getTabSize();
- case "FILENAME":
- case "FILEPATH":
- return "";
- case "FULLNAME":
- return "Ace";
- }
- };
- this.variables = {};
- this.getVariableValue = function(editor, varName) {
- if (this.variables.hasOwnProperty(varName))
- return this.variables[varName](editor, varName) || "";
- return this.$getDefaultValue(editor, varName) || "";
- };
- this.tmStrFormat = function(str, ch, editor) {
- var flag = ch.flag || "";
- var re = ch.guard;
- re = new RegExp(re, flag.replace(/[^gi]/, ""));
- var fmtTokens = this.tokenizeTmSnippet(ch.fmt, "formatString");
- var _self = this;
- var formatted = str.replace(re, function() {
- _self.variables.__ = arguments;
- var fmtParts = _self.resolveVariables(fmtTokens, editor);
- var gChangeCase = "E";
- for (var i = 0; i < fmtParts.length; i++) {
- var ch = fmtParts[i];
- if (typeof ch == "object") {
- fmtParts[i] = "";
- if (ch.changeCase && ch.local) {
- var next = fmtParts[i + 1];
- if (next && typeof next == "string") {
- if (ch.changeCase == "u")
- fmtParts[i] = next[0].toUpperCase();
- else
- fmtParts[i] = next[0].toLowerCase();
- fmtParts[i + 1] = next.substr(1);
- }
- } else if (ch.changeCase) {
- gChangeCase = ch.changeCase;
- }
- } else if (gChangeCase == "U") {
- fmtParts[i] = ch.toUpperCase();
- } else if (gChangeCase == "L") {
- fmtParts[i] = ch.toLowerCase();
- }
- }
- return fmtParts.join("");
- });
- this.variables.__ = null;
- return formatted;
- };
-
- this.resolveVariables = function(snippet, editor) {
- var result = [];
- for (var i = 0; i < snippet.length; i++) {
- var ch = snippet[i];
- if (typeof ch == "string") {
- result.push(ch);
- } else if (typeof ch != "object") {
- continue;
- } else if (ch.skip) {
- gotoNext(ch);
- } else if (ch.processed < i) {
- continue;
- } else if (ch.text) {
- var value = this.getVariableValue(editor, ch.text);
- if (value && ch.fmtString)
- value = this.tmStrFormat(value, ch);
- ch.processed = i;
- if (ch.expectIf == null) {
- if (value) {
- result.push(value);
- gotoNext(ch);
- }
- } else {
- if (value) {
- ch.skip = ch.elseBranch;
- } else
- gotoNext(ch);
- }
- } else if (ch.tabstopId != null) {
- result.push(ch);
- } else if (ch.changeCase != null) {
- result.push(ch);
- }
- }
- function gotoNext(ch) {
- var i1 = snippet.indexOf(ch, i + 1);
- if (i1 != -1)
- i = i1;
- }
- return result;
- };
-
- this.insertSnippetForSelection = function(editor, snippetText) {
- var cursor = editor.getCursorPosition();
- var line = editor.session.getLine(cursor.row);
- var tabString = editor.session.getTabString();
- var indentString = line.match(/^\s*/)[0];
-
- if (cursor.column < indentString.length)
- indentString = indentString.slice(0, cursor.column);
-
- var tokens = this.tokenizeTmSnippet(snippetText);
- tokens = this.resolveVariables(tokens, editor);
- tokens = tokens.map(function(x) {
- if (x == "\n")
- return x + indentString;
- if (typeof x == "string")
- return x.replace(/\t/g, tabString);
- return x;
- });
- var tabstops = [];
- tokens.forEach(function(p, i) {
- if (typeof p != "object")
- return;
- var id = p.tabstopId;
- var ts = tabstops[id];
- if (!ts) {
- ts = tabstops[id] = [];
- ts.index = id;
- ts.value = "";
- }
- if (ts.indexOf(p) !== -1)
- return;
- ts.push(p);
- var i1 = tokens.indexOf(p, i + 1);
- if (i1 === -1)
- return;
-
- var value = tokens.slice(i + 1, i1);
- var isNested = value.some(function(t) {return typeof t === "object"});
- if (isNested && !ts.value) {
- ts.value = value;
- } else if (value.length && (!ts.value || typeof ts.value !== "string")) {
- ts.value = value.join("");
- }
- });
- tabstops.forEach(function(ts) {ts.length = 0});
- var expanding = {};
- function copyValue(val) {
- var copy = [];
- for (var i = 0; i < val.length; i++) {
- var p = val[i];
- if (typeof p == "object") {
- if (expanding[p.tabstopId])
- continue;
- var j = val.lastIndexOf(p, i - 1);
- p = copy[j] || {tabstopId: p.tabstopId};
- }
- copy[i] = p;
- }
- return copy;
- }
- for (var i = 0; i < tokens.length; i++) {
- var p = tokens[i];
- if (typeof p != "object")
- continue;
- var id = p.tabstopId;
- var i1 = tokens.indexOf(p, i + 1);
- if (expanding[id]) {
- if (expanding[id] === p)
- expanding[id] = null;
- continue;
- }
-
- var ts = tabstops[id];
- var arg = typeof ts.value == "string" ? [ts.value] : copyValue(ts.value);
- arg.unshift(i + 1, Math.max(0, i1 - i));
- arg.push(p);
- expanding[id] = p;
- tokens.splice.apply(tokens, arg);
-
- if (ts.indexOf(p) === -1)
- ts.push(p);
- }
- var row = 0, column = 0;
- var text = "";
- tokens.forEach(function(t) {
- if (typeof t === "string") {
- if (t[0] === "\n"){
- column = t.length - 1;
- row ++;
- } else
- column += t.length;
- text += t;
- } else {
- if (!t.start)
- t.start = {row: row, column: column};
- else
- t.end = {row: row, column: column};
- }
- });
- var range = editor.getSelectionRange();
- var end = editor.session.replace(range, text);
-
- var tabstopManager = new TabstopManager(editor);
- var selectionId = editor.inVirtualSelectionMode && editor.selection.index;
- tabstopManager.addTabstops(tabstops, range.start, end, selectionId);
- };
-
- this.insertSnippet = function(editor, snippetText) {
- var self = this;
- if (editor.inVirtualSelectionMode)
- return self.insertSnippetForSelection(editor, snippetText);
-
- editor.forEachSelection(function() {
- self.insertSnippetForSelection(editor, snippetText);
- }, null, {keepOrder: true});
-
- if (editor.tabstopManager)
- editor.tabstopManager.tabNext();
- };
-
- this.$getScope = function(editor) {
- var scope = editor.session.$mode.$id || "";
- scope = scope.split("/").pop();
- if (scope === "html" || scope === "php") {
- if (scope === "php" && !editor.session.$mode.inlinePhp)
- scope = "html";
- var c = editor.getCursorPosition();
- var state = editor.session.getState(c.row);
- if (typeof state === "object") {
- state = state[0];
- }
- if (state.substring) {
- if (state.substring(0, 3) == "js-")
- scope = "javascript";
- else if (state.substring(0, 4) == "css-")
- scope = "css";
- else if (state.substring(0, 4) == "php-")
- scope = "php";
- }
- }
-
- return scope;
- };
-
- this.getActiveScopes = function(editor) {
- var scope = this.$getScope(editor);
- var scopes = [scope];
- var snippetMap = this.snippetMap;
- if (snippetMap[scope] && snippetMap[scope].includeScopes) {
- scopes.push.apply(scopes, snippetMap[scope].includeScopes);
- }
- scopes.push("_");
- return scopes;
- };
-
- this.expandWithTab = function(editor, options) {
- var self = this;
- var result = editor.forEachSelection(function() {
- return self.expandSnippetForSelection(editor, options);
- }, null, {keepOrder: true});
- if (result && editor.tabstopManager)
- editor.tabstopManager.tabNext();
- return result;
- };
-
- this.expandSnippetForSelection = function(editor, options) {
- var cursor = editor.getCursorPosition();
- var line = editor.session.getLine(cursor.row);
- var before = line.substring(0, cursor.column);
- var after = line.substr(cursor.column);
-
- var snippetMap = this.snippetMap;
- var snippet;
- this.getActiveScopes(editor).some(function(scope) {
- var snippets = snippetMap[scope];
- if (snippets)
- snippet = this.findMatchingSnippet(snippets, before, after);
- return !!snippet;
- }, this);
- if (!snippet)
- return false;
- if (options && options.dryRun)
- return true;
- editor.session.doc.removeInLine(cursor.row,
- cursor.column - snippet.replaceBefore.length,
- cursor.column + snippet.replaceAfter.length
- );
-
- this.variables.M__ = snippet.matchBefore;
- this.variables.T__ = snippet.matchAfter;
- this.insertSnippetForSelection(editor, snippet.content);
-
- this.variables.M__ = this.variables.T__ = null;
- return true;
- };
-
- this.findMatchingSnippet = function(snippetList, before, after) {
- for (var i = snippetList.length; i--;) {
- var s = snippetList[i];
- if (s.startRe && !s.startRe.test(before))
- continue;
- if (s.endRe && !s.endRe.test(after))
- continue;
- if (!s.startRe && !s.endRe)
- continue;
-
- s.matchBefore = s.startRe ? s.startRe.exec(before) : [""];
- s.matchAfter = s.endRe ? s.endRe.exec(after) : [""];
- s.replaceBefore = s.triggerRe ? s.triggerRe.exec(before)[0] : "";
- s.replaceAfter = s.endTriggerRe ? s.endTriggerRe.exec(after)[0] : "";
- return s;
- }
- };
-
- this.snippetMap = {};
- this.snippetNameMap = {};
- this.register = function(snippets, scope) {
- var snippetMap = this.snippetMap;
- var snippetNameMap = this.snippetNameMap;
- var self = this;
-
- if (!snippets)
- snippets = [];
-
- function wrapRegexp(src) {
- if (src && !/^\^?\(.*\)\$?$|^\\b$/.test(src))
- src = "(?:" + src + ")";
-
- return src || "";
- }
- function guardedRegexp(re, guard, opening) {
- re = wrapRegexp(re);
- guard = wrapRegexp(guard);
- if (opening) {
- re = guard + re;
- if (re && re[re.length - 1] != "$")
- re = re + "$";
- } else {
- re = re + guard;
- if (re && re[0] != "^")
- re = "^" + re;
- }
- return new RegExp(re);
- }
-
- function addSnippet(s) {
- if (!s.scope)
- s.scope = scope || "_";
- scope = s.scope;
- if (!snippetMap[scope]) {
- snippetMap[scope] = [];
- snippetNameMap[scope] = {};
- }
-
- var map = snippetNameMap[scope];
- if (s.name) {
- var old = map[s.name];
- if (old)
- self.unregister(old);
- map[s.name] = s;
- }
- snippetMap[scope].push(s);
-
- if (s.tabTrigger && !s.trigger) {
- if (!s.guard && /^\w/.test(s.tabTrigger))
- s.guard = "\\b";
- s.trigger = lang.escapeRegExp(s.tabTrigger);
- }
-
- if (!s.trigger && !s.guard && !s.endTrigger && !s.endGuard)
- return;
-
- s.startRe = guardedRegexp(s.trigger, s.guard, true);
- s.triggerRe = new RegExp(s.trigger, "", true);
-
- s.endRe = guardedRegexp(s.endTrigger, s.endGuard, true);
- s.endTriggerRe = new RegExp(s.endTrigger, "", true);
- }
-
- if (snippets && snippets.content)
- addSnippet(snippets);
- else if (Array.isArray(snippets))
- snippets.forEach(addSnippet);
-
- this._signal("registerSnippets", {scope: scope});
- };
- this.unregister = function(snippets, scope) {
- var snippetMap = this.snippetMap;
- var snippetNameMap = this.snippetNameMap;
-
- function removeSnippet(s) {
- var nameMap = snippetNameMap[s.scope||scope];
- if (nameMap && nameMap[s.name]) {
- delete nameMap[s.name];
- var map = snippetMap[s.scope||scope];
- var i = map && map.indexOf(s);
- if (i >= 0)
- map.splice(i, 1);
- }
- }
- if (snippets.content)
- removeSnippet(snippets);
- else if (Array.isArray(snippets))
- snippets.forEach(removeSnippet);
- };
- this.parseSnippetFile = function(str) {
- str = str.replace(/\r/g, "");
- var list = [], snippet = {};
- var re = /^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;
- var m;
- while (m = re.exec(str)) {
- if (m[1]) {
- try {
- snippet = JSON.parse(m[1]);
- list.push(snippet);
- } catch (e) {}
- } if (m[4]) {
- snippet.content = m[4].replace(/^\t/gm, "");
- list.push(snippet);
- snippet = {};
- } else {
- var key = m[2], val = m[3];
- if (key == "regex") {
- var guardRe = /\/((?:[^\/\\]|\\.)*)|$/g;
- snippet.guard = guardRe.exec(val)[1];
- snippet.trigger = guardRe.exec(val)[1];
- snippet.endTrigger = guardRe.exec(val)[1];
- snippet.endGuard = guardRe.exec(val)[1];
- } else if (key == "snippet") {
- snippet.tabTrigger = val.match(/^\S*/)[0];
- if (!snippet.name)
- snippet.name = val;
- } else {
- snippet[key] = val;
- }
- }
- }
- return list;
- };
- this.getSnippetByName = function(name, editor) {
- var snippetMap = this.snippetNameMap;
- var snippet;
- this.getActiveScopes(editor).some(function(scope) {
- var snippets = snippetMap[scope];
- if (snippets)
- snippet = snippets[name];
- return !!snippet;
- }, this);
- return snippet;
- };
-
-}).call(SnippetManager.prototype);
-
-
-var TabstopManager = function(editor) {
- if (editor.tabstopManager)
- return editor.tabstopManager;
- editor.tabstopManager = this;
- this.$onChange = this.onChange.bind(this);
- this.$onChangeSelection = lang.delayedCall(this.onChangeSelection.bind(this)).schedule;
- this.$onChangeSession = this.onChangeSession.bind(this);
- this.$onAfterExec = this.onAfterExec.bind(this);
- this.attach(editor);
-};
-(function() {
- this.attach = function(editor) {
- this.index = 0;
- this.ranges = [];
- this.tabstops = [];
- this.$openTabstops = null;
- this.selectedTabstop = null;
-
- this.editor = editor;
- this.editor.on("change", this.$onChange);
- this.editor.on("changeSelection", this.$onChangeSelection);
- this.editor.on("changeSession", this.$onChangeSession);
- this.editor.commands.on("afterExec", this.$onAfterExec);
- this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
- };
- this.detach = function() {
- this.tabstops.forEach(this.removeTabstopMarkers, this);
- this.ranges = null;
- this.tabstops = null;
- this.selectedTabstop = null;
- this.editor.removeListener("change", this.$onChange);
- this.editor.removeListener("changeSelection", this.$onChangeSelection);
- this.editor.removeListener("changeSession", this.$onChangeSession);
- this.editor.commands.removeListener("afterExec", this.$onAfterExec);
- this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
- this.editor.tabstopManager = null;
- this.editor = null;
- };
-
- this.onChange = function(delta) {
- var changeRange = delta;
- var isRemove = delta.action[0] == "r";
- var start = delta.start;
- var end = delta.end;
- var startRow = start.row;
- var endRow = end.row;
- var lineDif = endRow - startRow;
- var colDiff = end.column - start.column;
-
- if (isRemove) {
- lineDif = -lineDif;
- colDiff = -colDiff;
- }
- if (!this.$inChange && isRemove) {
- var ts = this.selectedTabstop;
- var changedOutside = ts && !ts.some(function(r) {
- return comparePoints(r.start, start) <= 0 && comparePoints(r.end, end) >= 0;
- });
- if (changedOutside)
- return this.detach();
- }
- var ranges = this.ranges;
- for (var i = 0; i < ranges.length; i++) {
- var r = ranges[i];
- if (r.end.row < start.row)
- continue;
-
- if (isRemove && comparePoints(start, r.start) < 0 && comparePoints(end, r.end) > 0) {
- this.removeRange(r);
- i--;
- continue;
- }
-
- if (r.start.row == startRow && r.start.column > start.column)
- r.start.column += colDiff;
- if (r.end.row == startRow && r.end.column >= start.column)
- r.end.column += colDiff;
- if (r.start.row >= startRow)
- r.start.row += lineDif;
- if (r.end.row >= startRow)
- r.end.row += lineDif;
-
- if (comparePoints(r.start, r.end) > 0)
- this.removeRange(r);
- }
- if (!ranges.length)
- this.detach();
- };
- this.updateLinkedFields = function() {
- var ts = this.selectedTabstop;
- if (!ts || !ts.hasLinkedRanges)
- return;
- this.$inChange = true;
- var session = this.editor.session;
- var text = session.getTextRange(ts.firstNonLinked);
- for (var i = ts.length; i--;) {
- var range = ts[i];
- if (!range.linked)
- continue;
- var fmt = exports.snippetManager.tmStrFormat(text, range.original);
- session.replace(range, fmt);
- }
- this.$inChange = false;
- };
- this.onAfterExec = function(e) {
- if (e.command && !e.command.readOnly)
- this.updateLinkedFields();
- };
- this.onChangeSelection = function() {
- if (!this.editor)
- return;
- var lead = this.editor.selection.lead;
- var anchor = this.editor.selection.anchor;
- var isEmpty = this.editor.selection.isEmpty();
- for (var i = this.ranges.length; i--;) {
- if (this.ranges[i].linked)
- continue;
- var containsLead = this.ranges[i].contains(lead.row, lead.column);
- var containsAnchor = isEmpty || this.ranges[i].contains(anchor.row, anchor.column);
- if (containsLead && containsAnchor)
- return;
- }
- this.detach();
- };
- this.onChangeSession = function() {
- this.detach();
- };
- this.tabNext = function(dir) {
- var max = this.tabstops.length;
- var index = this.index + (dir || 1);
- index = Math.min(Math.max(index, 1), max);
- if (index == max)
- index = 0;
- this.selectTabstop(index);
- if (index === 0)
- this.detach();
- };
- this.selectTabstop = function(index) {
- this.$openTabstops = null;
- var ts = this.tabstops[this.index];
- if (ts)
- this.addTabstopMarkers(ts);
- this.index = index;
- ts = this.tabstops[this.index];
- if (!ts || !ts.length)
- return;
-
- this.selectedTabstop = ts;
- if (!this.editor.inVirtualSelectionMode) {
- var sel = this.editor.multiSelect;
- sel.toSingleRange(ts.firstNonLinked.clone());
- for (var i = ts.length; i--;) {
- if (ts.hasLinkedRanges && ts[i].linked)
- continue;
- sel.addRange(ts[i].clone(), true);
- }
- if (sel.ranges[0])
- sel.addRange(sel.ranges[0].clone());
- } else {
- this.editor.selection.setRange(ts.firstNonLinked);
- }
-
- this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
- };
- this.addTabstops = function(tabstops, start, end) {
- if (!this.$openTabstops)
- this.$openTabstops = [];
- if (!tabstops[0]) {
- var p = Range.fromPoints(end, end);
- moveRelative(p.start, start);
- moveRelative(p.end, start);
- tabstops[0] = [p];
- tabstops[0].index = 0;
- }
-
- var i = this.index;
- var arg = [i + 1, 0];
- var ranges = this.ranges;
- tabstops.forEach(function(ts, index) {
- var dest = this.$openTabstops[index] || ts;
-
- for (var i = ts.length; i--;) {
- var p = ts[i];
- var range = Range.fromPoints(p.start, p.end || p.start);
- movePoint(range.start, start);
- movePoint(range.end, start);
- range.original = p;
- range.tabstop = dest;
- ranges.push(range);
- if (dest != ts)
- dest.unshift(range);
- else
- dest[i] = range;
- if (p.fmtString) {
- range.linked = true;
- dest.hasLinkedRanges = true;
- } else if (!dest.firstNonLinked)
- dest.firstNonLinked = range;
- }
- if (!dest.firstNonLinked)
- dest.hasLinkedRanges = false;
- if (dest === ts) {
- arg.push(dest);
- this.$openTabstops[index] = dest;
- }
- this.addTabstopMarkers(dest);
- }, this);
-
- if (arg.length > 2) {
- if (this.tabstops.length)
- arg.push(arg.splice(2, 1)[0]);
- this.tabstops.splice.apply(this.tabstops, arg);
- }
- };
-
- this.addTabstopMarkers = function(ts) {
- var session = this.editor.session;
- ts.forEach(function(range) {
- if (!range.markerId)
- range.markerId = session.addMarker(range, "ace_snippet-marker", "text");
- });
- };
- this.removeTabstopMarkers = function(ts) {
- var session = this.editor.session;
- ts.forEach(function(range) {
- session.removeMarker(range.markerId);
- range.markerId = null;
- });
- };
- this.removeRange = function(range) {
- var i = range.tabstop.indexOf(range);
- range.tabstop.splice(i, 1);
- i = this.ranges.indexOf(range);
- this.ranges.splice(i, 1);
- this.editor.session.removeMarker(range.markerId);
- if (!range.tabstop.length) {
- i = this.tabstops.indexOf(range.tabstop);
- if (i != -1)
- this.tabstops.splice(i, 1);
- if (!this.tabstops.length)
- this.detach();
- }
- };
-
- this.keyboardHandler = new HashHandler();
- this.keyboardHandler.bindKeys({
- "Tab": function(ed) {
- if (exports.snippetManager && exports.snippetManager.expandWithTab(ed)) {
- return;
- }
-
- ed.tabstopManager.tabNext(1);
- },
- "Shift-Tab": function(ed) {
- ed.tabstopManager.tabNext(-1);
- },
- "Esc": function(ed) {
- ed.tabstopManager.detach();
- },
- "Return": function(ed) {
- return false;
- }
- });
-}).call(TabstopManager.prototype);
-
-
-
-var changeTracker = {};
-changeTracker.onChange = Anchor.prototype.onChange;
-changeTracker.setPosition = function(row, column) {
- this.pos.row = row;
- this.pos.column = column;
-};
-changeTracker.update = function(pos, delta, $insertRight) {
- this.$insertRight = $insertRight;
- this.pos = pos;
- this.onChange(delta);
-};
-
-var movePoint = function(point, diff) {
- if (point.row == 0)
- point.column += diff.column;
- point.row += diff.row;
-};
-
-var moveRelative = function(point, start) {
- if (point.row == start.row)
- point.column -= start.column;
- point.row -= start.row;
-};
-
-
-require("./lib/dom").importCssString("\
-.ace_snippet-marker {\
- -moz-box-sizing: border-box;\
- box-sizing: border-box;\
- background: rgba(194, 193, 208, 0.09);\
- border: 1px dotted rgba(211, 208, 235, 0.62);\
- position: absolute;\
-}");
-
-exports.snippetManager = new SnippetManager();
-
-
-var Editor = require("./editor").Editor;
-(function() {
- this.insertSnippet = function(content, options) {
- return exports.snippetManager.insertSnippet(this, content, options);
- };
- this.expandSnippet = function(options) {
- return exports.snippetManager.expandWithTab(this, options);
- };
-}).call(Editor.prototype);
-
-});
-
-ace.define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"], function(require, exports, module) {
-"use strict";
-
-var Renderer = require("../virtual_renderer").VirtualRenderer;
-var Editor = require("../editor").Editor;
-var Range = require("../range").Range;
-var event = require("../lib/event");
-var lang = require("../lib/lang");
-var dom = require("../lib/dom");
-
-var $singleLineEditor = function(el) {
- var renderer = new Renderer(el);
-
- renderer.$maxLines = 4;
-
- var editor = new Editor(renderer);
-
- editor.setHighlightActiveLine(false);
- editor.setShowPrintMargin(false);
- editor.renderer.setShowGutter(false);
- editor.renderer.setHighlightGutterLine(false);
-
- editor.$mouseHandler.$focusWaitTimout = 0;
- editor.$highlightTagPending = true;
-
- return editor;
-};
-
-var AcePopup = function(parentNode) {
- var el = dom.createElement("div");
- var popup = new $singleLineEditor(el);
-
- if (parentNode)
- parentNode.appendChild(el);
- el.style.display = "none";
- popup.renderer.content.style.cursor = "default";
- popup.renderer.setStyle("ace_autocomplete");
-
- popup.setOption("displayIndentGuides", false);
- popup.setOption("dragDelay", 150);
-
- var noop = function(){};
-
- popup.focus = noop;
- popup.$isFocused = true;
-
- popup.renderer.$cursorLayer.restartTimer = noop;
- popup.renderer.$cursorLayer.element.style.opacity = 0;
-
- popup.renderer.$maxLines = 8;
- popup.renderer.$keepTextAreaAtCursor = false;
-
- popup.setHighlightActiveLine(false);
- popup.session.highlight("");
- popup.session.$searchHighlight.clazz = "ace_highlight-marker";
-
- popup.on("mousedown", function(e) {
- var pos = e.getDocumentPosition();
- popup.selection.moveToPosition(pos);
- selectionMarker.start.row = selectionMarker.end.row = pos.row;
- e.stop();
- });
-
- var lastMouseEvent;
- var hoverMarker = new Range(-1,0,-1,Infinity);
- var selectionMarker = new Range(-1,0,-1,Infinity);
- selectionMarker.id = popup.session.addMarker(selectionMarker, "ace_active-line", "fullLine");
- popup.setSelectOnHover = function(val) {
- if (!val) {
- hoverMarker.id = popup.session.addMarker(hoverMarker, "ace_line-hover", "fullLine");
- } else if (hoverMarker.id) {
- popup.session.removeMarker(hoverMarker.id);
- hoverMarker.id = null;
- }
- };
- popup.setSelectOnHover(false);
- popup.on("mousemove", function(e) {
- if (!lastMouseEvent) {
- lastMouseEvent = e;
- return;
- }
- if (lastMouseEvent.x == e.x && lastMouseEvent.y == e.y) {
- return;
- }
- lastMouseEvent = e;
- lastMouseEvent.scrollTop = popup.renderer.scrollTop;
- var row = lastMouseEvent.getDocumentPosition().row;
- if (hoverMarker.start.row != row) {
- if (!hoverMarker.id)
- popup.setRow(row);
- setHoverMarker(row);
- }
- });
- popup.renderer.on("beforeRender", function() {
- if (lastMouseEvent && hoverMarker.start.row != -1) {
- lastMouseEvent.$pos = null;
- var row = lastMouseEvent.getDocumentPosition().row;
- if (!hoverMarker.id)
- popup.setRow(row);
- setHoverMarker(row, true);
- }
- });
- popup.renderer.on("afterRender", function() {
- var row = popup.getRow();
- var t = popup.renderer.$textLayer;
- var selected = t.element.childNodes[row - t.config.firstRow];
- if (selected == t.selectedNode)
- return;
- if (t.selectedNode)
- dom.removeCssClass(t.selectedNode, "ace_selected");
- t.selectedNode = selected;
- if (selected)
- dom.addCssClass(selected, "ace_selected");
- });
- var hideHoverMarker = function() { setHoverMarker(-1) };
- var setHoverMarker = function(row, suppressRedraw) {
- if (row !== hoverMarker.start.row) {
- hoverMarker.start.row = hoverMarker.end.row = row;
- if (!suppressRedraw)
- popup.session._emit("changeBackMarker");
- popup._emit("changeHoverMarker");
- }
- };
- popup.getHoveredRow = function() {
- return hoverMarker.start.row;
- };
-
- event.addListener(popup.container, "mouseout", hideHoverMarker);
- popup.on("hide", hideHoverMarker);
- popup.on("changeSelection", hideHoverMarker);
-
- popup.session.doc.getLength = function() {
- return popup.data.length;
- };
- popup.session.doc.getLine = function(i) {
- var data = popup.data[i];
- if (typeof data == "string")
- return data;
- return (data && data.value) || "";
- };
-
- var bgTokenizer = popup.session.bgTokenizer;
- bgTokenizer.$tokenizeRow = function(row) {
- var data = popup.data[row];
- var tokens = [];
- if (!data)
- return tokens;
- if (typeof data == "string")
- data = {value: data};
- if (!data.caption)
- data.caption = data.value || data.name;
-
- var last = -1;
- var flag, c;
- for (var i = 0; i < data.caption.length; i++) {
- c = data.caption[i];
- flag = data.matchMask & (1 << i) ? 1 : 0;
- if (last !== flag) {
- tokens.push({type: data.className || "" + ( flag ? "completion-highlight" : ""), value: c});
- last = flag;
- } else {
- tokens[tokens.length - 1].value += c;
- }
- }
-
- if (data.meta) {
- var maxW = popup.renderer.$size.scrollerWidth / popup.renderer.layerConfig.characterWidth;
- var metaData = data.meta;
- if (metaData.length + data.caption.length > maxW - 2) {
- metaData = metaData.substr(0, maxW - data.caption.length - 3) + "\u2026"
- }
- tokens.push({type: "rightAlignedText", value: metaData});
- }
- return tokens;
- };
- bgTokenizer.$updateOnChange = noop;
- bgTokenizer.start = noop;
-
- popup.session.$computeWidth = function() {
- return this.screenWidth = 0;
- };
-
- popup.$blockScrolling = Infinity;
- popup.isOpen = false;
- popup.isTopdown = false;
-
- popup.data = [];
- popup.setData = function(list) {
- popup.setValue(lang.stringRepeat("\n", list.length), -1);
- popup.data = list || [];
- popup.setRow(0);
- };
- popup.getData = function(row) {
- return popup.data[row];
- };
-
- popup.getRow = function() {
- return selectionMarker.start.row;
- };
- popup.setRow = function(line) {
- line = Math.max(0, Math.min(this.data.length, line));
- if (selectionMarker.start.row != line) {
- popup.selection.clearSelection();
- selectionMarker.start.row = selectionMarker.end.row = line || 0;
- popup.session._emit("changeBackMarker");
- popup.moveCursorTo(line || 0, 0);
- if (popup.isOpen)
- popup._signal("select");
- }
- };
-
- popup.on("changeSelection", function() {
- if (popup.isOpen)
- popup.setRow(popup.selection.lead.row);
- popup.renderer.scrollCursorIntoView();
- });
-
- popup.hide = function() {
- this.container.style.display = "none";
- this._signal("hide");
- popup.isOpen = false;
- };
- popup.show = function(pos, lineHeight, topdownOnly) {
- var el = this.container;
- var screenHeight = window.innerHeight;
- var screenWidth = window.innerWidth;
- var renderer = this.renderer;
- var maxH = renderer.$maxLines * lineHeight * 1.4;
- var top = pos.top + this.$borderSize;
- if (top + maxH > screenHeight - lineHeight && !topdownOnly) {
- el.style.top = "";
- el.style.bottom = screenHeight - top + "px";
- popup.isTopdown = false;
- } else {
- top += lineHeight;
- el.style.top = top + "px";
- el.style.bottom = "";
- popup.isTopdown = true;
- }
-
- el.style.display = "";
- this.renderer.$textLayer.checkForSizeChanges();
-
- var left = pos.left;
- if (left + el.offsetWidth > screenWidth)
- left = screenWidth - el.offsetWidth;
-
- el.style.left = left + "px";
-
- this._signal("show");
- lastMouseEvent = null;
- popup.isOpen = true;
- };
-
- popup.getTextLeftOffset = function() {
- return this.$borderSize + this.renderer.$padding + this.$imageSize;
- };
-
- popup.$imageSize = 0;
- popup.$borderSize = 1;
-
- return popup;
-};
-
-dom.importCssString("\
-.ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line {\
- background-color: #CAD6FA;\
- z-index: 1;\
-}\
-.ace_editor.ace_autocomplete .ace_line-hover {\
- border: 1px solid #abbffe;\
- margin-top: -1px;\
- background: rgba(233,233,253,0.4);\
-}\
-.ace_editor.ace_autocomplete .ace_line-hover {\
- position: absolute;\
- z-index: 2;\
-}\
-.ace_editor.ace_autocomplete .ace_scroller {\
- background: none;\
- border: none;\
- box-shadow: none;\
-}\
-.ace_rightAlignedText {\
- color: gray;\
- display: inline-block;\
- position: absolute;\
- right: 4px;\
- text-align: right;\
- z-index: -1;\
-}\
-.ace_editor.ace_autocomplete .ace_completion-highlight{\
- color: #000;\
- text-shadow: 0 0 0.01em;\
-}\
-.ace_editor.ace_autocomplete {\
- width: 280px;\
- z-index: 200000;\
- background: #fbfbfb;\
- color: #444;\
- border: 1px lightgray solid;\
- position: fixed;\
- box-shadow: 2px 3px 5px rgba(0,0,0,.2);\
- line-height: 1.4;\
-}");
-
-exports.AcePopup = AcePopup;
-
-});
-
-ace.define("ace/autocomplete/util",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-exports.parForEach = function(array, fn, callback) {
- var completed = 0;
- var arLength = array.length;
- if (arLength === 0)
- callback();
- for (var i = 0; i < arLength; i++) {
- fn(array[i], function(result, err) {
- completed++;
- if (completed === arLength)
- callback(result, err);
- });
- }
-};
-
-var ID_REGEX = /[a-zA-Z_0-9\$\-\u00A2-\uFFFF]/;
-
-exports.retrievePrecedingIdentifier = function(text, pos, regex) {
- regex = regex || ID_REGEX;
- var buf = [];
- for (var i = pos-1; i >= 0; i--) {
- if (regex.test(text[i]))
- buf.push(text[i]);
- else
- break;
- }
- return buf.reverse().join("");
-};
-
-exports.retrieveFollowingIdentifier = function(text, pos, regex) {
- regex = regex || ID_REGEX;
- var buf = [];
- for (var i = pos; i < text.length; i++) {
- if (regex.test(text[i]))
- buf.push(text[i]);
- else
- break;
- }
- return buf;
-};
-
-exports.getCompletionPrefix = function (editor) {
- var pos = editor.getCursorPosition();
- var line = editor.session.getLine(pos.row);
- var prefix;
- editor.completers.forEach(function(completer) {
- if (completer.identifierRegexps) {
- completer.identifierRegexps.forEach(function(identifierRegex) {
- if (!prefix && identifierRegex)
- prefix = this.retrievePrecedingIdentifier(line, pos.column, identifierRegex);
- }.bind(this));
- }
- }.bind(this));
- return prefix || this.retrievePrecedingIdentifier(line, pos.column);
-};
-
-});
-
-ace.define("ace/autocomplete",["require","exports","module","ace/keyboard/hash_handler","ace/autocomplete/popup","ace/autocomplete/util","ace/lib/event","ace/lib/lang","ace/lib/dom","ace/snippets"], function(require, exports, module) {
-"use strict";
-
-var HashHandler = require("./keyboard/hash_handler").HashHandler;
-var AcePopup = require("./autocomplete/popup").AcePopup;
-var util = require("./autocomplete/util");
-var event = require("./lib/event");
-var lang = require("./lib/lang");
-var dom = require("./lib/dom");
-var snippetManager = require("./snippets").snippetManager;
-
-var Autocomplete = function() {
- this.autoInsert = false;
- this.autoSelect = true;
- this.exactMatch = false;
- this.gatherCompletionsId = 0;
- this.keyboardHandler = new HashHandler();
- this.keyboardHandler.bindKeys(this.commands);
-
- this.blurListener = this.blurListener.bind(this);
- this.changeListener = this.changeListener.bind(this);
- this.mousedownListener = this.mousedownListener.bind(this);
- this.mousewheelListener = this.mousewheelListener.bind(this);
-
- this.changeTimer = lang.delayedCall(function() {
- this.updateCompletions(true);
- }.bind(this));
-
- this.tooltipTimer = lang.delayedCall(this.updateDocTooltip.bind(this), 50);
-};
-
-(function() {
-
- this.$init = function() {
- this.popup = new AcePopup(document.body || document.documentElement);
- this.popup.on("click", function(e) {
- this.insertMatch();
- e.stop();
- }.bind(this));
- this.popup.focus = this.editor.focus.bind(this.editor);
- this.popup.on("show", this.tooltipTimer.bind(null, null));
- this.popup.on("select", this.tooltipTimer.bind(null, null));
- this.popup.on("changeHoverMarker", this.tooltipTimer.bind(null, null));
- return this.popup;
- };
-
- this.getPopup = function() {
- return this.popup || this.$init();
- };
-
- this.openPopup = function(editor, prefix, keepPopupPosition) {
- if (!this.popup)
- this.$init();
-
- this.popup.setData(this.completions.filtered);
-
- editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
-
- var renderer = editor.renderer;
- this.popup.setRow(this.autoSelect ? 0 : -1);
- if (!keepPopupPosition) {
- this.popup.setTheme(editor.getTheme());
- this.popup.setFontSize(editor.getFontSize());
-
- var lineHeight = renderer.layerConfig.lineHeight;
-
- var pos = renderer.$cursorLayer.getPixelPosition(this.base, true);
- pos.left -= this.popup.getTextLeftOffset();
-
- var rect = editor.container.getBoundingClientRect();
- pos.top += rect.top - renderer.layerConfig.offset;
- pos.left += rect.left - editor.renderer.scrollLeft;
- pos.left += renderer.gutterWidth;
-
- this.popup.show(pos, lineHeight);
- } else if (keepPopupPosition && !prefix) {
- this.detach();
- }
- };
-
- this.detach = function() {
- this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
- this.editor.off("changeSelection", this.changeListener);
- this.editor.off("blur", this.blurListener);
- this.editor.off("mousedown", this.mousedownListener);
- this.editor.off("mousewheel", this.mousewheelListener);
- this.changeTimer.cancel();
- this.hideDocTooltip();
-
- this.gatherCompletionsId += 1;
- if (this.popup && this.popup.isOpen)
- this.popup.hide();
-
- if (this.base)
- this.base.detach();
- this.activated = false;
- this.completions = this.base = null;
- };
-
- this.changeListener = function(e) {
- var cursor = this.editor.selection.lead;
- if (cursor.row != this.base.row || cursor.column < this.base.column) {
- this.detach();
- }
- if (this.activated)
- this.changeTimer.schedule();
- else
- this.detach();
- };
-
- this.blurListener = function(e) {
- var el = document.activeElement;
- var text = this.editor.textInput.getElement();
- var fromTooltip = e.relatedTarget && e.relatedTarget == this.tooltipNode;
- var container = this.popup && this.popup.container;
- if (el != text && el.parentNode != container && !fromTooltip
- && el != this.tooltipNode && e.relatedTarget != text
- ) {
- this.detach();
- }
- };
-
- this.mousedownListener = function(e) {
- this.detach();
- };
-
- this.mousewheelListener = function(e) {
- this.detach();
- };
-
- this.goTo = function(where) {
- var row = this.popup.getRow();
- var max = this.popup.session.getLength() - 1;
-
- switch(where) {
- case "up": row = row <= 0 ? max : row - 1; break;
- case "down": row = row >= max ? -1 : row + 1; break;
- case "start": row = 0; break;
- case "end": row = max; break;
- }
-
- this.popup.setRow(row);
- };
-
- this.insertMatch = function(data, options) {
- if (!data)
- data = this.popup.getData(this.popup.getRow());
- if (!data)
- return false;
-
- if (data.completer && data.completer.insertMatch) {
- data.completer.insertMatch(this.editor, data);
- } else {
- if (this.completions.filterText) {
- var ranges = this.editor.selection.getAllRanges();
- for (var i = 0, range; range = ranges[i]; i++) {
- range.start.column -= this.completions.filterText.length;
- this.editor.session.remove(range);
- }
- }
- if (data.snippet)
- snippetManager.insertSnippet(this.editor, data.snippet);
- else
- this.editor.execCommand("insertstring", data.value || data);
- }
- this.detach();
- };
-
-
- this.commands = {
- "Up": function(editor) { editor.completer.goTo("up"); },
- "Down": function(editor) { editor.completer.goTo("down"); },
- "Ctrl-Up|Ctrl-Home": function(editor) { editor.completer.goTo("start"); },
- "Ctrl-Down|Ctrl-End": function(editor) { editor.completer.goTo("end"); },
-
- "Esc": function(editor) { editor.completer.detach(); },
- "Return": function(editor) { return editor.completer.insertMatch(); },
- "Shift-Return": function(editor) { editor.completer.insertMatch(null, {deleteSuffix: true}); },
- "Tab": function(editor) {
- var result = editor.completer.insertMatch();
- if (!result && !editor.tabstopManager)
- editor.completer.goTo("down");
- else
- return result;
- },
-
- "PageUp": function(editor) { editor.completer.popup.gotoPageUp(); },
- "PageDown": function(editor) { editor.completer.popup.gotoPageDown(); }
- };
-
- this.gatherCompletions = function(editor, callback) {
- var session = editor.getSession();
- var pos = editor.getCursorPosition();
-
- var line = session.getLine(pos.row);
- var prefix = util.getCompletionPrefix(editor);
-
- this.base = session.doc.createAnchor(pos.row, pos.column - prefix.length);
- this.base.$insertRight = true;
-
- var matches = [];
- var total = editor.completers.length;
- editor.completers.forEach(function(completer, i) {
- completer.getCompletions(editor, session, pos, prefix, function(err, results) {
- if (!err && results)
- matches = matches.concat(results);
- var pos = editor.getCursorPosition();
- var line = session.getLine(pos.row);
- callback(null, {
- prefix: prefix,
- matches: matches,
- finished: (--total === 0)
- });
- });
- });
- return true;
- };
-
- this.showPopup = function(editor) {
- if (this.editor)
- this.detach();
-
- this.activated = true;
-
- this.editor = editor;
- if (editor.completer != this) {
- if (editor.completer)
- editor.completer.detach();
- editor.completer = this;
- }
-
- editor.on("changeSelection", this.changeListener);
- editor.on("blur", this.blurListener);
- editor.on("mousedown", this.mousedownListener);
- editor.on("mousewheel", this.mousewheelListener);
-
- this.updateCompletions();
- };
-
- this.updateCompletions = function(keepPopupPosition) {
- if (keepPopupPosition && this.base && this.completions) {
- var pos = this.editor.getCursorPosition();
- var prefix = this.editor.session.getTextRange({start: this.base, end: pos});
- if (prefix == this.completions.filterText)
- return;
- this.completions.setFilter(prefix);
- if (!this.completions.filtered.length)
- return this.detach();
- if (this.completions.filtered.length == 1
- && this.completions.filtered[0].value == prefix
- && !this.completions.filtered[0].snippet)
- return this.detach();
- this.openPopup(this.editor, prefix, keepPopupPosition);
- return;
- }
- var _id = this.gatherCompletionsId;
- this.gatherCompletions(this.editor, function(err, results) {
- var detachIfFinished = function() {
- if (!results.finished) return;
- return this.detach();
- }.bind(this);
-
- var prefix = results.prefix;
- var matches = results && results.matches;
-
- if (!matches || !matches.length)
- return detachIfFinished();
- if (prefix.indexOf(results.prefix) !== 0 || _id != this.gatherCompletionsId)
- return;
-
- this.completions = new FilteredList(matches);
-
- if (this.exactMatch)
- this.completions.exactMatch = true;
-
- this.completions.setFilter(prefix);
- var filtered = this.completions.filtered;
- if (!filtered.length)
- return detachIfFinished();
- if (filtered.length == 1 && filtered[0].value == prefix && !filtered[0].snippet)
- return detachIfFinished();
- if (this.autoInsert && filtered.length == 1 && results.finished)
- return this.insertMatch(filtered[0]);
-
- this.openPopup(this.editor, prefix, keepPopupPosition);
- }.bind(this));
- };
-
- this.cancelContextMenu = function() {
- this.editor.$mouseHandler.cancelContextMenu();
- };
-
- this.updateDocTooltip = function() {
- var popup = this.popup;
- var all = popup.data;
- var selected = all && (all[popup.getHoveredRow()] || all[popup.getRow()]);
- var doc = null;
- if (!selected || !this.editor || !this.popup.isOpen)
- return this.hideDocTooltip();
- this.editor.completers.some(function(completer) {
- if (completer.getDocTooltip)
- doc = completer.getDocTooltip(selected);
- return doc;
- });
- if (!doc)
- doc = selected;
-
- if (typeof doc == "string")
- doc = {docText: doc};
- if (!doc || !(doc.docHTML || doc.docText))
- return this.hideDocTooltip();
- this.showDocTooltip(doc);
- };
-
- this.showDocTooltip = function(item) {
- if (!this.tooltipNode) {
- this.tooltipNode = dom.createElement("div");
- this.tooltipNode.className = "ace_tooltip ace_doc-tooltip";
- this.tooltipNode.style.margin = 0;
- this.tooltipNode.style.pointerEvents = "auto";
- this.tooltipNode.tabIndex = -1;
- this.tooltipNode.onblur = this.blurListener.bind(this);
- }
-
- var tooltipNode = this.tooltipNode;
- if (item.docHTML) {
- tooltipNode.innerHTML = item.docHTML;
- } else if (item.docText) {
- tooltipNode.textContent = item.docText;
- }
-
- if (!tooltipNode.parentNode)
- document.body.appendChild(tooltipNode);
- var popup = this.popup;
- var rect = popup.container.getBoundingClientRect();
- tooltipNode.style.top = popup.container.style.top;
- tooltipNode.style.bottom = popup.container.style.bottom;
-
- if (window.innerWidth - rect.right < 320) {
- tooltipNode.style.right = window.innerWidth - rect.left + "px";
- tooltipNode.style.left = "";
- } else {
- tooltipNode.style.left = (rect.right + 1) + "px";
- tooltipNode.style.right = "";
- }
- tooltipNode.style.display = "block";
- };
-
- this.hideDocTooltip = function() {
- this.tooltipTimer.cancel();
- if (!this.tooltipNode) return;
- var el = this.tooltipNode;
- if (!this.editor.isFocused() && document.activeElement == el)
- this.editor.focus();
- this.tooltipNode = null;
- if (el.parentNode)
- el.parentNode.removeChild(el);
- };
-
-}).call(Autocomplete.prototype);
-
-Autocomplete.startCommand = {
- name: "startAutocomplete",
- exec: function(editor) {
- if (!editor.completer)
- editor.completer = new Autocomplete();
- editor.completer.autoInsert = false;
- editor.completer.autoSelect = true;
- editor.completer.showPopup(editor);
- editor.completer.cancelContextMenu();
- },
- bindKey: "Ctrl-Space|Ctrl-Shift-Space|Alt-Space"
-};
-
-var FilteredList = function(array, filterText) {
- this.all = array;
- this.filtered = array;
- this.filterText = filterText || "";
- this.exactMatch = false;
-};
-(function(){
- this.setFilter = function(str) {
- if (str.length > this.filterText && str.lastIndexOf(this.filterText, 0) === 0)
- var matches = this.filtered;
- else
- var matches = this.all;
-
- this.filterText = str;
- matches = this.filterCompletions(matches, this.filterText);
- matches = matches.sort(function(a, b) {
- return b.exactMatch - a.exactMatch || b.score - a.score;
- });
- var prev = null;
- matches = matches.filter(function(item){
- var caption = item.snippet || item.caption || item.value;
- if (caption === prev) return false;
- prev = caption;
- return true;
- });
-
- this.filtered = matches;
- };
- this.filterCompletions = function(items, needle) {
- var results = [];
- var upper = needle.toUpperCase();
- var lower = needle.toLowerCase();
- loop: for (var i = 0, item; item = items[i]; i++) {
- var caption = item.value || item.caption || item.snippet;
- if (!caption) continue;
- var lastIndex = -1;
- var matchMask = 0;
- var penalty = 0;
- var index, distance;
-
- if (this.exactMatch) {
- if (needle !== caption.substr(0, needle.length))
- continue loop;
- }else{
- for (var j = 0; j < needle.length; j++) {
- var i1 = caption.indexOf(lower[j], lastIndex + 1);
- var i2 = caption.indexOf(upper[j], lastIndex + 1);
- index = (i1 >= 0) ? ((i2 < 0 || i1 < i2) ? i1 : i2) : i2;
- if (index < 0)
- continue loop;
- distance = index - lastIndex - 1;
- if (distance > 0) {
- if (lastIndex === -1)
- penalty += 10;
- penalty += distance;
- }
- matchMask = matchMask | (1 << index);
- lastIndex = index;
- }
- }
- item.matchMask = matchMask;
- item.exactMatch = penalty ? 0 : 1;
- item.score = (item.score || 0) - penalty;
- results.push(item);
- }
- return results;
- };
-}).call(FilteredList.prototype);
-
-exports.Autocomplete = Autocomplete;
-exports.FilteredList = FilteredList;
-
-});
-
-ace.define("ace/autocomplete/text_completer",["require","exports","module","ace/range"], function(require, exports, module) {
- var Range = require("../range").Range;
-
- var splitRegex = /[^a-zA-Z_0-9\$\-\u00C0-\u1FFF\u2C00-\uD7FF\w]+/;
-
- function getWordIndex(doc, pos) {
- var textBefore = doc.getTextRange(Range.fromPoints({row: 0, column:0}, pos));
- return textBefore.split(splitRegex).length - 1;
- }
- function wordDistance(doc, pos) {
- var prefixPos = getWordIndex(doc, pos);
- var words = doc.getValue().split(splitRegex);
- var wordScores = Object.create(null);
-
- var currentWord = words[prefixPos];
-
- words.forEach(function(word, idx) {
- if (!word || word === currentWord) return;
-
- var distance = Math.abs(prefixPos - idx);
- var score = words.length - distance;
- if (wordScores[word]) {
- wordScores[word] = Math.max(score, wordScores[word]);
- } else {
- wordScores[word] = score;
- }
- });
- return wordScores;
- }
-
- exports.getCompletions = function(editor, session, pos, prefix, callback) {
- var wordScore = wordDistance(session, pos, prefix);
- var wordList = Object.keys(wordScore);
- callback(null, wordList.map(function(word) {
- return {
- caption: word,
- value: word,
- score: wordScore[word],
- meta: "local"
- };
- }));
- };
-});
-
-ace.define("ace/ext/language_tools",["require","exports","module","ace/snippets","ace/autocomplete","ace/config","ace/lib/lang","ace/autocomplete/util","ace/autocomplete/text_completer","ace/editor","ace/config"], function(require, exports, module) {
-"use strict";
-
-var snippetManager = require("../snippets").snippetManager;
-var Autocomplete = require("../autocomplete").Autocomplete;
-var config = require("../config");
-var lang = require("../lib/lang");
-var util = require("../autocomplete/util");
-
-var textCompleter = require("../autocomplete/text_completer");
-var keyWordCompleter = {
- getCompletions: function(editor, session, pos, prefix, callback) {
- if (session.$mode.completer) {
- return session.$mode.completer.getCompletions(editor, session, pos, prefix, callback);
- }
- var state = editor.session.getState(pos.row);
- var completions = session.$mode.getCompletions(state, session, pos, prefix);
- callback(null, completions);
- }
-};
-
-var snippetCompleter = {
- getCompletions: function(editor, session, pos, prefix, callback) {
- var snippetMap = snippetManager.snippetMap;
- var completions = [];
- snippetManager.getActiveScopes(editor).forEach(function(scope) {
- var snippets = snippetMap[scope] || [];
- for (var i = snippets.length; i--;) {
- var s = snippets[i];
- var caption = s.name || s.tabTrigger;
- if (!caption)
- continue;
- completions.push({
- caption: caption,
- snippet: s.content,
- meta: s.tabTrigger && !s.name ? s.tabTrigger + "\u21E5 " : "snippet",
- type: "snippet"
- });
- }
- }, this);
- callback(null, completions);
- },
- getDocTooltip: function(item) {
- if (item.type == "snippet" && !item.docHTML) {
- item.docHTML = [
- "
", lang.escapeHTML(item.caption), "", "
",
- lang.escapeHTML(item.snippet)
- ].join("");
- }
- }
-};
-
-var completers = [snippetCompleter, textCompleter, keyWordCompleter];
-exports.setCompleters = function(val) {
- completers.length = 0;
- if (val) completers.push.apply(completers, val);
-};
-exports.addCompleter = function(completer) {
- completers.push(completer);
-};
-exports.textCompleter = textCompleter;
-exports.keyWordCompleter = keyWordCompleter;
-exports.snippetCompleter = snippetCompleter;
-
-var expandSnippet = {
- name: "expandSnippet",
- exec: function(editor) {
- return snippetManager.expandWithTab(editor);
- },
- bindKey: "Tab"
-};
-
-var onChangeMode = function(e, editor) {
- loadSnippetsForMode(editor.session.$mode);
-};
-
-var loadSnippetsForMode = function(mode) {
- var id = mode.$id;
- if (!snippetManager.files)
- snippetManager.files = {};
- loadSnippetFile(id);
- if (mode.modes)
- mode.modes.forEach(loadSnippetsForMode);
-};
-
-var loadSnippetFile = function(id) {
- if (!id || snippetManager.files[id])
- return;
- var snippetFilePath = id.replace("mode", "snippets");
- snippetManager.files[id] = {};
- config.loadModule(snippetFilePath, function(m) {
- if (m) {
- snippetManager.files[id] = m;
- if (!m.snippets && m.snippetText)
- m.snippets = snippetManager.parseSnippetFile(m.snippetText);
- snippetManager.register(m.snippets || [], m.scope);
- if (m.includeScopes) {
- snippetManager.snippetMap[m.scope].includeScopes = m.includeScopes;
- m.includeScopes.forEach(function(x) {
- loadSnippetFile("ace/mode/" + x);
- });
- }
- }
- });
-};
-
-var doLiveAutocomplete = function(e) {
- var editor = e.editor;
- var hasCompleter = editor.completer && editor.completer.activated;
- if (e.command.name === "backspace") {
- if (hasCompleter && !util.getCompletionPrefix(editor))
- editor.completer.detach();
- }
- else if (e.command.name === "insertstring") {
- var prefix = util.getCompletionPrefix(editor);
- if (prefix && !hasCompleter) {
- if (!editor.completer) {
- editor.completer = new Autocomplete();
- }
- editor.completer.autoInsert = false;
- editor.completer.showPopup(editor);
- }
- }
-};
-
-var Editor = require("../editor").Editor;
-require("../config").defineOptions(Editor.prototype, "editor", {
- enableBasicAutocompletion: {
- set: function(val) {
- if (val) {
- if (!this.completers)
- this.completers = Array.isArray(val)? val: completers;
- this.commands.addCommand(Autocomplete.startCommand);
- } else {
- this.commands.removeCommand(Autocomplete.startCommand);
- }
- },
- value: false
- },
- enableLiveAutocompletion: {
- set: function(val) {
- if (val) {
- if (!this.completers)
- this.completers = Array.isArray(val)? val: completers;
- this.commands.on('afterExec', doLiveAutocomplete);
- } else {
- this.commands.removeListener('afterExec', doLiveAutocomplete);
- }
- },
- value: false
- },
- enableSnippets: {
- set: function(val) {
- if (val) {
- this.commands.addCommand(expandSnippet);
- this.on("changeMode", onChangeMode);
- onChangeMode(null, this);
- } else {
- this.commands.removeCommand(expandSnippet);
- this.off("changeMode", onChangeMode);
- }
- },
- value: false
- }
-});
-});
- (function() {
- ace.require(["ace/ext/language_tools"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-linking.js b/icestudio/lib/ace-builds/src-noconflict/ext-linking.js
deleted file mode 100644
index c6ad15dfb..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-linking.js
+++ /dev/null
@@ -1,52 +0,0 @@
-ace.define("ace/ext/linking",["require","exports","module","ace/editor","ace/config"], function(require, exports, module) {
-
-var Editor = require("ace/editor").Editor;
-
-require("../config").defineOptions(Editor.prototype, "editor", {
- enableLinking: {
- set: function(val) {
- if (val) {
- this.on("click", onClick);
- this.on("mousemove", onMouseMove);
- } else {
- this.off("click", onClick);
- this.off("mousemove", onMouseMove);
- }
- },
- value: false
- }
-})
-
-function onMouseMove(e) {
- var editor = e.editor;
- var ctrl = e.getAccelKey();
-
- if (ctrl) {
- var editor = e.editor;
- var docPos = e.getDocumentPosition();
- var session = editor.session;
- var token = session.getTokenAt(docPos.row, docPos.column);
-
- editor._emit("linkHover", {position: docPos, token: token});
- }
-}
-
-function onClick(e) {
- var ctrl = e.getAccelKey();
- var button = e.getButton();
-
- if (button == 0 && ctrl) {
- var editor = e.editor;
- var docPos = e.getDocumentPosition();
- var session = editor.session;
- var token = session.getTokenAt(docPos.row, docPos.column);
-
- editor._emit("linkClick", {position: docPos, token: token});
- }
-}
-
-});
- (function() {
- ace.require(["ace/ext/linking"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-modelist.js b/icestudio/lib/ace-builds/src-noconflict/ext-modelist.js
deleted file mode 100644
index 18898f4d1..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-modelist.js
+++ /dev/null
@@ -1,201 +0,0 @@
-ace.define("ace/ext/modelist",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-var modes = [];
-function getModeForPath(path) {
- var mode = modesByName.text;
- var fileName = path.split(/[\/\\]/).pop();
- for (var i = 0; i < modes.length; i++) {
- if (modes[i].supportsFile(fileName)) {
- mode = modes[i];
- break;
- }
- }
- return mode;
-}
-
-var Mode = function(name, caption, extensions) {
- this.name = name;
- this.caption = caption;
- this.mode = "ace/mode/" + name;
- this.extensions = extensions;
- var re;
- if (/\^/.test(extensions)) {
- re = extensions.replace(/\|(\^)?/g, function(a, b){
- return "$|" + (b ? "^" : "^.*\\.");
- }) + "$";
- } else {
- re = "^.*\\.(" + extensions + ")$";
- }
-
- this.extRe = new RegExp(re, "gi");
-};
-
-Mode.prototype.supportsFile = function(filename) {
- return filename.match(this.extRe);
-};
-var supportedModes = {
- ABAP: ["abap"],
- ABC: ["abc"],
- ActionScript:["as"],
- ADA: ["ada|adb"],
- Apache_Conf: ["^htaccess|^htgroups|^htpasswd|^conf|htaccess|htgroups|htpasswd"],
- AsciiDoc: ["asciidoc|adoc"],
- Assembly_x86:["asm|a"],
- AutoHotKey: ["ahk"],
- BatchFile: ["bat|cmd"],
- C_Cpp: ["cpp|c|cc|cxx|h|hh|hpp|ino"],
- C9Search: ["c9search_results"],
- Cirru: ["cirru|cr"],
- Clojure: ["clj|cljs"],
- Cobol: ["CBL|COB"],
- coffee: ["coffee|cf|cson|^Cakefile"],
- ColdFusion: ["cfm"],
- CSharp: ["cs"],
- CSS: ["css"],
- Curly: ["curly"],
- D: ["d|di"],
- Dart: ["dart"],
- Diff: ["diff|patch"],
- Dockerfile: ["^Dockerfile"],
- Dot: ["dot"],
- Dummy: ["dummy"],
- DummySyntax: ["dummy"],
- Eiffel: ["e|ge"],
- EJS: ["ejs"],
- Elixir: ["ex|exs"],
- Elm: ["elm"],
- Erlang: ["erl|hrl"],
- Forth: ["frt|fs|ldr"],
- FTL: ["ftl"],
- Gcode: ["gcode"],
- Gherkin: ["feature"],
- Gitignore: ["^.gitignore"],
- Glsl: ["glsl|frag|vert"],
- Gobstones: ["gbs"],
- golang: ["go"],
- Groovy: ["groovy"],
- HAML: ["haml"],
- Handlebars: ["hbs|handlebars|tpl|mustache"],
- Haskell: ["hs"],
- haXe: ["hx"],
- HTML: ["html|htm|xhtml"],
- HTML_Elixir: ["eex|html.eex"],
- HTML_Ruby: ["erb|rhtml|html.erb"],
- INI: ["ini|conf|cfg|prefs"],
- Io: ["io"],
- Jack: ["jack"],
- Jade: ["jade"],
- Java: ["java"],
- JavaScript: ["js|jsm|jsx"],
- JSON: ["json"],
- JSONiq: ["jq"],
- JSP: ["jsp"],
- JSX: ["jsx"],
- Julia: ["jl"],
- LaTeX: ["tex|latex|ltx|bib"],
- Lean: ["lean|hlean"],
- LESS: ["less"],
- Liquid: ["liquid"],
- Lisp: ["lisp"],
- LiveScript: ["ls"],
- LogiQL: ["logic|lql"],
- LSL: ["lsl"],
- Lua: ["lua"],
- LuaPage: ["lp"],
- Lucene: ["lucene"],
- Makefile: ["^Makefile|^GNUmakefile|^makefile|^OCamlMakefile|make"],
- Markdown: ["md|markdown"],
- Mask: ["mask"],
- MATLAB: ["matlab"],
- Maze: ["mz"],
- MEL: ["mel"],
- MUSHCode: ["mc|mush"],
- MySQL: ["mysql"],
- Nix: ["nix"],
- NSIS: ["nsi|nsh"],
- ObjectiveC: ["m|mm"],
- OCaml: ["ml|mli"],
- Pascal: ["pas|p"],
- Perl: ["pl|pm"],
- pgSQL: ["pgsql"],
- PHP: ["php|phtml|shtml|php3|php4|php5|phps|phpt|aw|ctp|module"],
- Powershell: ["ps1"],
- Praat: ["praat|praatscript|psc|proc"],
- Prolog: ["plg|prolog"],
- Properties: ["properties"],
- Protobuf: ["proto"],
- Python: ["py"],
- R: ["r"],
- Razor: ["cshtml"],
- RDoc: ["Rd"],
- RHTML: ["Rhtml"],
- RST: ["rst"],
- Ruby: ["rb|ru|gemspec|rake|^Guardfile|^Rakefile|^Gemfile"],
- Rust: ["rs"],
- SASS: ["sass"],
- SCAD: ["scad"],
- Scala: ["scala"],
- Scheme: ["scm|sm|rkt|oak|scheme"],
- SCSS: ["scss"],
- SH: ["sh|bash|^.bashrc"],
- SJS: ["sjs"],
- Smarty: ["smarty|tpl"],
- snippets: ["snippets"],
- Soy_Template:["soy"],
- Space: ["space"],
- SQL: ["sql"],
- SQLServer: ["sqlserver"],
- Stylus: ["styl|stylus"],
- SVG: ["svg"],
- Swift: ["swift"],
- Tcl: ["tcl"],
- Tex: ["tex"],
- Text: ["txt"],
- Textile: ["textile"],
- Toml: ["toml"],
- Twig: ["twig|swig"],
- Typescript: ["ts|typescript|str"],
- Vala: ["vala"],
- VBScript: ["vbs|vb"],
- Velocity: ["vm"],
- Verilog: ["v|vh|sv|svh"],
- VHDL: ["vhd|vhdl"],
- Wollok: ["wlk|wpgm|wtest"],
- XML: ["xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl|xaml"],
- XQuery: ["xq"],
- YAML: ["yaml|yml"],
- Django: ["html"]
-};
-
-var nameOverrides = {
- ObjectiveC: "Objective-C",
- CSharp: "C#",
- golang: "Go",
- C_Cpp: "C and C++",
- coffee: "CoffeeScript",
- HTML_Ruby: "HTML (Ruby)",
- HTML_Elixir: "HTML (Elixir)",
- FTL: "FreeMarker"
-};
-var modesByName = {};
-for (var name in supportedModes) {
- var data = supportedModes[name];
- var displayName = (nameOverrides[name] || name).replace(/_/g, " ");
- var filename = name.toLowerCase();
- var mode = new Mode(filename, displayName, data[0]);
- modesByName[filename] = mode;
- modes.push(mode);
-}
-
-module.exports = {
- getModeForPath: getModeForPath,
- modes: modes,
- modesByName: modesByName
-};
-
-});
- (function() {
- ace.require(["ace/ext/modelist"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-old_ie.js b/icestudio/lib/ace-builds/src-noconflict/ext-old_ie.js
deleted file mode 100644
index 3eacfe4cd..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-old_ie.js
+++ /dev/null
@@ -1,501 +0,0 @@
-ace.define("ace/ext/searchbox",["require","exports","module","ace/lib/dom","ace/lib/lang","ace/lib/event","ace/keyboard/hash_handler","ace/lib/keys"], function(require, exports, module) {
-"use strict";
-
-var dom = require("../lib/dom");
-var lang = require("../lib/lang");
-var event = require("../lib/event");
-var searchboxCss = "\
-.ace_search {\
-background-color: #ddd;\
-border: 1px solid #cbcbcb;\
-border-top: 0 none;\
-max-width: 325px;\
-overflow: hidden;\
-margin: 0;\
-padding: 4px;\
-padding-right: 6px;\
-padding-bottom: 0;\
-position: absolute;\
-top: 0px;\
-z-index: 99;\
-white-space: normal;\
-}\
-.ace_search.left {\
-border-left: 0 none;\
-border-radius: 0px 0px 5px 0px;\
-left: 0;\
-}\
-.ace_search.right {\
-border-radius: 0px 0px 0px 5px;\
-border-right: 0 none;\
-right: 0;\
-}\
-.ace_search_form, .ace_replace_form {\
-border-radius: 3px;\
-border: 1px solid #cbcbcb;\
-float: left;\
-margin-bottom: 4px;\
-overflow: hidden;\
-}\
-.ace_search_form.ace_nomatch {\
-outline: 1px solid red;\
-}\
-.ace_search_field {\
-background-color: white;\
-border-right: 1px solid #cbcbcb;\
-border: 0 none;\
--webkit-box-sizing: border-box;\
--moz-box-sizing: border-box;\
-box-sizing: border-box;\
-float: left;\
-height: 22px;\
-outline: 0;\
-padding: 0 7px;\
-width: 214px;\
-margin: 0;\
-}\
-.ace_searchbtn,\
-.ace_replacebtn {\
-background: #fff;\
-border: 0 none;\
-border-left: 1px solid #dcdcdc;\
-cursor: pointer;\
-float: left;\
-height: 22px;\
-margin: 0;\
-position: relative;\
-}\
-.ace_searchbtn:last-child,\
-.ace_replacebtn:last-child {\
-border-top-right-radius: 3px;\
-border-bottom-right-radius: 3px;\
-}\
-.ace_searchbtn:disabled {\
-background: none;\
-cursor: default;\
-}\
-.ace_searchbtn {\
-background-position: 50% 50%;\
-background-repeat: no-repeat;\
-width: 27px;\
-}\
-.ace_searchbtn.prev {\
-background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADFJREFUeNpiSU1NZUAC/6E0I0yACYskCpsJiySKIiY0SUZk40FyTEgCjGgKwTRAgAEAQJUIPCE+qfkAAAAASUVORK5CYII=); \
-}\
-.ace_searchbtn.next {\
-background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADRJREFUeNpiTE1NZQCC/0DMyIAKwGJMUAYDEo3M/s+EpvM/mkKwCQxYjIeLMaELoLMBAgwAU7UJObTKsvAAAAAASUVORK5CYII=); \
-}\
-.ace_searchbtn_close {\
-background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAcCAYAAABRVo5BAAAAZ0lEQVR42u2SUQrAMAhDvazn8OjZBilCkYVVxiis8H4CT0VrAJb4WHT3C5xU2a2IQZXJjiQIRMdkEoJ5Q2yMqpfDIo+XY4k6h+YXOyKqTIj5REaxloNAd0xiKmAtsTHqW8sR2W5f7gCu5nWFUpVjZwAAAABJRU5ErkJggg==) no-repeat 50% 0;\
-border-radius: 50%;\
-border: 0 none;\
-color: #656565;\
-cursor: pointer;\
-float: right;\
-font: 16px/16px Arial;\
-height: 14px;\
-margin: 5px 1px 9px 5px;\
-padding: 0;\
-text-align: center;\
-width: 14px;\
-}\
-.ace_searchbtn_close:hover {\
-background-color: #656565;\
-background-position: 50% 100%;\
-color: white;\
-}\
-.ace_replacebtn.prev {\
-width: 54px\
-}\
-.ace_replacebtn.next {\
-width: 27px\
-}\
-.ace_button {\
-margin-left: 2px;\
-cursor: pointer;\
--webkit-user-select: none;\
--moz-user-select: none;\
--o-user-select: none;\
--ms-user-select: none;\
-user-select: none;\
-overflow: hidden;\
-opacity: 0.7;\
-border: 1px solid rgba(100,100,100,0.23);\
-padding: 1px;\
--moz-box-sizing: border-box;\
-box-sizing: border-box;\
-color: black;\
-}\
-.ace_button:hover {\
-background-color: #eee;\
-opacity:1;\
-}\
-.ace_button:active {\
-background-color: #ddd;\
-}\
-.ace_button.checked {\
-border-color: #3399ff;\
-opacity:1;\
-}\
-.ace_search_options{\
-margin-bottom: 3px;\
-text-align: right;\
--webkit-user-select: none;\
--moz-user-select: none;\
--o-user-select: none;\
--ms-user-select: none;\
-user-select: none;\
-}";
-var HashHandler = require("../keyboard/hash_handler").HashHandler;
-var keyUtil = require("../lib/keys");
-
-dom.importCssString(searchboxCss, "ace_searchbox");
-
-var html = '
\
-
\
-
\
- \
- \
- \
- \
-
\
-
\
- \
- \
- \
-
\
-
\
- .*\
- Aa\
- \\b\
-
\
-
'.replace(/>\s+/g, ">");
-
-var SearchBox = function(editor, range, showReplaceForm) {
- var div = dom.createElement("div");
- div.innerHTML = html;
- this.element = div.firstChild;
-
- this.$init();
- this.setEditor(editor);
-};
-
-(function() {
- this.setEditor = function(editor) {
- editor.searchBox = this;
- editor.container.appendChild(this.element);
- this.editor = editor;
- };
-
- this.$initElements = function(sb) {
- this.searchBox = sb.querySelector(".ace_search_form");
- this.replaceBox = sb.querySelector(".ace_replace_form");
- this.searchOptions = sb.querySelector(".ace_search_options");
- this.regExpOption = sb.querySelector("[action=toggleRegexpMode]");
- this.caseSensitiveOption = sb.querySelector("[action=toggleCaseSensitive]");
- this.wholeWordOption = sb.querySelector("[action=toggleWholeWords]");
- this.searchInput = this.searchBox.querySelector(".ace_search_field");
- this.replaceInput = this.replaceBox.querySelector(".ace_search_field");
- };
-
- this.$init = function() {
- var sb = this.element;
-
- this.$initElements(sb);
-
- var _this = this;
- event.addListener(sb, "mousedown", function(e) {
- setTimeout(function(){
- _this.activeInput.focus();
- }, 0);
- event.stopPropagation(e);
- });
- event.addListener(sb, "click", function(e) {
- var t = e.target || e.srcElement;
- var action = t.getAttribute("action");
- if (action && _this[action])
- _this[action]();
- else if (_this.$searchBarKb.commands[action])
- _this.$searchBarKb.commands[action].exec(_this);
- event.stopPropagation(e);
- });
-
- event.addCommandKeyListener(sb, function(e, hashId, keyCode) {
- var keyString = keyUtil.keyCodeToString(keyCode);
- var command = _this.$searchBarKb.findKeyCommand(hashId, keyString);
- if (command && command.exec) {
- command.exec(_this);
- event.stopEvent(e);
- }
- });
-
- this.$onChange = lang.delayedCall(function() {
- _this.find(false, false);
- });
-
- event.addListener(this.searchInput, "input", function() {
- _this.$onChange.schedule(20);
- });
- event.addListener(this.searchInput, "focus", function() {
- _this.activeInput = _this.searchInput;
- _this.searchInput.value && _this.highlight();
- });
- event.addListener(this.replaceInput, "focus", function() {
- _this.activeInput = _this.replaceInput;
- _this.searchInput.value && _this.highlight();
- });
- };
- this.$closeSearchBarKb = new HashHandler([{
- bindKey: "Esc",
- name: "closeSearchBar",
- exec: function(editor) {
- editor.searchBox.hide();
- }
- }]);
- this.$searchBarKb = new HashHandler();
- this.$searchBarKb.bindKeys({
- "Ctrl-f|Command-f": function(sb) {
- var isReplace = sb.isReplace = !sb.isReplace;
- sb.replaceBox.style.display = isReplace ? "" : "none";
- sb.searchInput.focus();
- },
- "Ctrl-H|Command-Option-F": function(sb) {
- sb.replaceBox.style.display = "";
- sb.replaceInput.focus();
- },
- "Ctrl-G|Command-G": function(sb) {
- sb.findNext();
- },
- "Ctrl-Shift-G|Command-Shift-G": function(sb) {
- sb.findPrev();
- },
- "esc": function(sb) {
- setTimeout(function() { sb.hide();});
- },
- "Return": function(sb) {
- if (sb.activeInput == sb.replaceInput)
- sb.replace();
- sb.findNext();
- },
- "Shift-Return": function(sb) {
- if (sb.activeInput == sb.replaceInput)
- sb.replace();
- sb.findPrev();
- },
- "Alt-Return": function(sb) {
- if (sb.activeInput == sb.replaceInput)
- sb.replaceAll();
- sb.findAll();
- },
- "Tab": function(sb) {
- (sb.activeInput == sb.replaceInput ? sb.searchInput : sb.replaceInput).focus();
- }
- });
-
- this.$searchBarKb.addCommands([{
- name: "toggleRegexpMode",
- bindKey: {win: "Alt-R|Alt-/", mac: "Ctrl-Alt-R|Ctrl-Alt-/"},
- exec: function(sb) {
- sb.regExpOption.checked = !sb.regExpOption.checked;
- sb.$syncOptions();
- }
- }, {
- name: "toggleCaseSensitive",
- bindKey: {win: "Alt-C|Alt-I", mac: "Ctrl-Alt-R|Ctrl-Alt-I"},
- exec: function(sb) {
- sb.caseSensitiveOption.checked = !sb.caseSensitiveOption.checked;
- sb.$syncOptions();
- }
- }, {
- name: "toggleWholeWords",
- bindKey: {win: "Alt-B|Alt-W", mac: "Ctrl-Alt-B|Ctrl-Alt-W"},
- exec: function(sb) {
- sb.wholeWordOption.checked = !sb.wholeWordOption.checked;
- sb.$syncOptions();
- }
- }]);
-
- this.$syncOptions = function() {
- dom.setCssClass(this.regExpOption, "checked", this.regExpOption.checked);
- dom.setCssClass(this.wholeWordOption, "checked", this.wholeWordOption.checked);
- dom.setCssClass(this.caseSensitiveOption, "checked", this.caseSensitiveOption.checked);
- this.find(false, false);
- };
-
- this.highlight = function(re) {
- this.editor.session.highlight(re || this.editor.$search.$options.re);
- this.editor.renderer.updateBackMarkers()
- };
- this.find = function(skipCurrent, backwards, preventScroll) {
- var range = this.editor.find(this.searchInput.value, {
- skipCurrent: skipCurrent,
- backwards: backwards,
- wrap: true,
- regExp: this.regExpOption.checked,
- caseSensitive: this.caseSensitiveOption.checked,
- wholeWord: this.wholeWordOption.checked,
- preventScroll: preventScroll
- });
- var noMatch = !range && this.searchInput.value;
- dom.setCssClass(this.searchBox, "ace_nomatch", noMatch);
- this.editor._emit("findSearchBox", { match: !noMatch });
- this.highlight();
- };
- this.findNext = function() {
- this.find(true, false);
- };
- this.findPrev = function() {
- this.find(true, true);
- };
- this.findAll = function(){
- var range = this.editor.findAll(this.searchInput.value, {
- regExp: this.regExpOption.checked,
- caseSensitive: this.caseSensitiveOption.checked,
- wholeWord: this.wholeWordOption.checked
- });
- var noMatch = !range && this.searchInput.value;
- dom.setCssClass(this.searchBox, "ace_nomatch", noMatch);
- this.editor._emit("findSearchBox", { match: !noMatch });
- this.highlight();
- this.hide();
- };
- this.replace = function() {
- if (!this.editor.getReadOnly())
- this.editor.replace(this.replaceInput.value);
- };
- this.replaceAndFindNext = function() {
- if (!this.editor.getReadOnly()) {
- this.editor.replace(this.replaceInput.value);
- this.findNext()
- }
- };
- this.replaceAll = function() {
- if (!this.editor.getReadOnly())
- this.editor.replaceAll(this.replaceInput.value);
- };
-
- this.hide = function() {
- this.element.style.display = "none";
- this.editor.keyBinding.removeKeyboardHandler(this.$closeSearchBarKb);
- this.editor.focus();
- };
- this.show = function(value, isReplace) {
- this.element.style.display = "";
- this.replaceBox.style.display = isReplace ? "" : "none";
-
- this.isReplace = isReplace;
-
- if (value)
- this.searchInput.value = value;
-
- this.find(false, false, true);
-
- this.searchInput.focus();
- this.searchInput.select();
-
- this.editor.keyBinding.addKeyboardHandler(this.$closeSearchBarKb);
- };
-
- this.isFocused = function() {
- var el = document.activeElement;
- return el == this.searchInput || el == this.replaceInput;
- }
-}).call(SearchBox.prototype);
-
-exports.SearchBox = SearchBox;
-
-exports.Search = function(editor, isReplace) {
- var sb = editor.searchBox || new SearchBox(editor);
- sb.show(editor.session.getTextRange(), isReplace);
-};
-
-});
-
-ace.define("ace/ext/old_ie",["require","exports","module","ace/lib/useragent","ace/tokenizer","ace/ext/searchbox","ace/mode/text"], function(require, exports, module) {
-"use strict";
-var MAX_TOKEN_COUNT = 1000;
-var useragent = require("../lib/useragent");
-var TokenizerModule = require("../tokenizer");
-
-function patch(obj, name, regexp, replacement) {
- eval("obj['" + name + "']=" + obj[name].toString().replace(
- regexp, replacement
- ));
-}
-
-if (useragent.isIE && useragent.isIE < 10 && window.top.document.compatMode === "BackCompat")
- useragent.isOldIE = true;
-
-if (typeof document != "undefined" && !document.documentElement.querySelector) {
- useragent.isOldIE = true;
- var qs = function(el, selector) {
- if (selector.charAt(0) == ".") {
- var classNeme = selector.slice(1);
- } else {
- var m = selector.match(/(\w+)=(\w+)/);
- var attr = m && m[1];
- var attrVal = m && m[2];
- }
- for (var i = 0; i < el.all.length; i++) {
- var ch = el.all[i];
- if (classNeme) {
- if (ch.className.indexOf(classNeme) != -1)
- return ch;
- } else if (attr) {
- if (ch.getAttribute(attr) == attrVal)
- return ch;
- }
- }
- };
- var sb = require("./searchbox").SearchBox.prototype;
- patch(
- sb, "$initElements",
- /([^\s=]*).querySelector\((".*?")\)/g,
- "qs($1, $2)"
- );
-}
-
-var compliantExecNpcg = /()??/.exec("")[1] === undefined;
-if (compliantExecNpcg)
- return;
-var proto = TokenizerModule.Tokenizer.prototype;
-TokenizerModule.Tokenizer_orig = TokenizerModule.Tokenizer;
-proto.getLineTokens_orig = proto.getLineTokens;
-
-patch(
- TokenizerModule, "Tokenizer",
- "ruleRegExps.push(adjustedregex);\n",
- function(m) {
- return m + '\
- if (state[i].next && RegExp(adjustedregex).test(""))\n\
- rule._qre = RegExp(adjustedregex, "g");\n\
- ';
- }
-);
-TokenizerModule.Tokenizer.prototype = proto;
-patch(
- proto, "getLineTokens",
- /if \(match\[i \+ 1\] === undefined\)\s*continue;/,
- "if (!match[i + 1]) {\n\
- if (value)continue;\n\
- var qre = state[mapping[i]]._qre;\n\
- if (!qre) continue;\n\
- qre.lastIndex = lastIndex;\n\
- if (!qre.exec(line) || qre.lastIndex != lastIndex)\n\
- continue;\n\
- }"
-);
-
-patch(
- require("../mode/text").Mode.prototype, "getTokenizer",
- /Tokenizer/,
- "TokenizerModule.Tokenizer"
-);
-
-useragent.isOldIE = true;
-
-});
- (function() {
- ace.require(["ace/ext/old_ie"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-searchbox.js b/icestudio/lib/ace-builds/src-noconflict/ext-searchbox.js
deleted file mode 100644
index ef31f6903..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-searchbox.js
+++ /dev/null
@@ -1,416 +0,0 @@
-ace.define("ace/ext/searchbox",["require","exports","module","ace/lib/dom","ace/lib/lang","ace/lib/event","ace/keyboard/hash_handler","ace/lib/keys"], function(require, exports, module) {
-"use strict";
-
-var dom = require("../lib/dom");
-var lang = require("../lib/lang");
-var event = require("../lib/event");
-var searchboxCss = "\
-.ace_search {\
-background-color: #ddd;\
-border: 1px solid #cbcbcb;\
-border-top: 0 none;\
-max-width: 325px;\
-overflow: hidden;\
-margin: 0;\
-padding: 4px;\
-padding-right: 6px;\
-padding-bottom: 0;\
-position: absolute;\
-top: 0px;\
-z-index: 99;\
-white-space: normal;\
-}\
-.ace_search.left {\
-border-left: 0 none;\
-border-radius: 0px 0px 5px 0px;\
-left: 0;\
-}\
-.ace_search.right {\
-border-radius: 0px 0px 0px 5px;\
-border-right: 0 none;\
-right: 0;\
-}\
-.ace_search_form, .ace_replace_form {\
-border-radius: 3px;\
-border: 1px solid #cbcbcb;\
-float: left;\
-margin-bottom: 4px;\
-overflow: hidden;\
-}\
-.ace_search_form.ace_nomatch {\
-outline: 1px solid red;\
-}\
-.ace_search_field {\
-background-color: white;\
-border-right: 1px solid #cbcbcb;\
-border: 0 none;\
--webkit-box-sizing: border-box;\
--moz-box-sizing: border-box;\
-box-sizing: border-box;\
-float: left;\
-height: 22px;\
-outline: 0;\
-padding: 0 7px;\
-width: 214px;\
-margin: 0;\
-}\
-.ace_searchbtn,\
-.ace_replacebtn {\
-background: #fff;\
-border: 0 none;\
-border-left: 1px solid #dcdcdc;\
-cursor: pointer;\
-float: left;\
-height: 22px;\
-margin: 0;\
-position: relative;\
-}\
-.ace_searchbtn:last-child,\
-.ace_replacebtn:last-child {\
-border-top-right-radius: 3px;\
-border-bottom-right-radius: 3px;\
-}\
-.ace_searchbtn:disabled {\
-background: none;\
-cursor: default;\
-}\
-.ace_searchbtn {\
-background-position: 50% 50%;\
-background-repeat: no-repeat;\
-width: 27px;\
-}\
-.ace_searchbtn.prev {\
-background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADFJREFUeNpiSU1NZUAC/6E0I0yACYskCpsJiySKIiY0SUZk40FyTEgCjGgKwTRAgAEAQJUIPCE+qfkAAAAASUVORK5CYII=); \
-}\
-.ace_searchbtn.next {\
-background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADRJREFUeNpiTE1NZQCC/0DMyIAKwGJMUAYDEo3M/s+EpvM/mkKwCQxYjIeLMaELoLMBAgwAU7UJObTKsvAAAAAASUVORK5CYII=); \
-}\
-.ace_searchbtn_close {\
-background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAcCAYAAABRVo5BAAAAZ0lEQVR42u2SUQrAMAhDvazn8OjZBilCkYVVxiis8H4CT0VrAJb4WHT3C5xU2a2IQZXJjiQIRMdkEoJ5Q2yMqpfDIo+XY4k6h+YXOyKqTIj5REaxloNAd0xiKmAtsTHqW8sR2W5f7gCu5nWFUpVjZwAAAABJRU5ErkJggg==) no-repeat 50% 0;\
-border-radius: 50%;\
-border: 0 none;\
-color: #656565;\
-cursor: pointer;\
-float: right;\
-font: 16px/16px Arial;\
-height: 14px;\
-margin: 5px 1px 9px 5px;\
-padding: 0;\
-text-align: center;\
-width: 14px;\
-}\
-.ace_searchbtn_close:hover {\
-background-color: #656565;\
-background-position: 50% 100%;\
-color: white;\
-}\
-.ace_replacebtn.prev {\
-width: 54px\
-}\
-.ace_replacebtn.next {\
-width: 27px\
-}\
-.ace_button {\
-margin-left: 2px;\
-cursor: pointer;\
--webkit-user-select: none;\
--moz-user-select: none;\
--o-user-select: none;\
--ms-user-select: none;\
-user-select: none;\
-overflow: hidden;\
-opacity: 0.7;\
-border: 1px solid rgba(100,100,100,0.23);\
-padding: 1px;\
--moz-box-sizing: border-box;\
-box-sizing: border-box;\
-color: black;\
-}\
-.ace_button:hover {\
-background-color: #eee;\
-opacity:1;\
-}\
-.ace_button:active {\
-background-color: #ddd;\
-}\
-.ace_button.checked {\
-border-color: #3399ff;\
-opacity:1;\
-}\
-.ace_search_options{\
-margin-bottom: 3px;\
-text-align: right;\
--webkit-user-select: none;\
--moz-user-select: none;\
--o-user-select: none;\
--ms-user-select: none;\
-user-select: none;\
-}";
-var HashHandler = require("../keyboard/hash_handler").HashHandler;
-var keyUtil = require("../lib/keys");
-
-dom.importCssString(searchboxCss, "ace_searchbox");
-
-var html = '
\
-
\
-
\
- \
- \
- \
- \
-
\
-
\
- \
- \
- \
-
\
-
\
- .*\
- Aa\
- \\b\
-
\
-
'.replace(/>\s+/g, ">");
-
-var SearchBox = function(editor, range, showReplaceForm) {
- var div = dom.createElement("div");
- div.innerHTML = html;
- this.element = div.firstChild;
-
- this.$init();
- this.setEditor(editor);
-};
-
-(function() {
- this.setEditor = function(editor) {
- editor.searchBox = this;
- editor.container.appendChild(this.element);
- this.editor = editor;
- };
-
- this.$initElements = function(sb) {
- this.searchBox = sb.querySelector(".ace_search_form");
- this.replaceBox = sb.querySelector(".ace_replace_form");
- this.searchOptions = sb.querySelector(".ace_search_options");
- this.regExpOption = sb.querySelector("[action=toggleRegexpMode]");
- this.caseSensitiveOption = sb.querySelector("[action=toggleCaseSensitive]");
- this.wholeWordOption = sb.querySelector("[action=toggleWholeWords]");
- this.searchInput = this.searchBox.querySelector(".ace_search_field");
- this.replaceInput = this.replaceBox.querySelector(".ace_search_field");
- };
-
- this.$init = function() {
- var sb = this.element;
-
- this.$initElements(sb);
-
- var _this = this;
- event.addListener(sb, "mousedown", function(e) {
- setTimeout(function(){
- _this.activeInput.focus();
- }, 0);
- event.stopPropagation(e);
- });
- event.addListener(sb, "click", function(e) {
- var t = e.target || e.srcElement;
- var action = t.getAttribute("action");
- if (action && _this[action])
- _this[action]();
- else if (_this.$searchBarKb.commands[action])
- _this.$searchBarKb.commands[action].exec(_this);
- event.stopPropagation(e);
- });
-
- event.addCommandKeyListener(sb, function(e, hashId, keyCode) {
- var keyString = keyUtil.keyCodeToString(keyCode);
- var command = _this.$searchBarKb.findKeyCommand(hashId, keyString);
- if (command && command.exec) {
- command.exec(_this);
- event.stopEvent(e);
- }
- });
-
- this.$onChange = lang.delayedCall(function() {
- _this.find(false, false);
- });
-
- event.addListener(this.searchInput, "input", function() {
- _this.$onChange.schedule(20);
- });
- event.addListener(this.searchInput, "focus", function() {
- _this.activeInput = _this.searchInput;
- _this.searchInput.value && _this.highlight();
- });
- event.addListener(this.replaceInput, "focus", function() {
- _this.activeInput = _this.replaceInput;
- _this.searchInput.value && _this.highlight();
- });
- };
- this.$closeSearchBarKb = new HashHandler([{
- bindKey: "Esc",
- name: "closeSearchBar",
- exec: function(editor) {
- editor.searchBox.hide();
- }
- }]);
- this.$searchBarKb = new HashHandler();
- this.$searchBarKb.bindKeys({
- "Ctrl-f|Command-f": function(sb) {
- var isReplace = sb.isReplace = !sb.isReplace;
- sb.replaceBox.style.display = isReplace ? "" : "none";
- sb.searchInput.focus();
- },
- "Ctrl-H|Command-Option-F": function(sb) {
- sb.replaceBox.style.display = "";
- sb.replaceInput.focus();
- },
- "Ctrl-G|Command-G": function(sb) {
- sb.findNext();
- },
- "Ctrl-Shift-G|Command-Shift-G": function(sb) {
- sb.findPrev();
- },
- "esc": function(sb) {
- setTimeout(function() { sb.hide();});
- },
- "Return": function(sb) {
- if (sb.activeInput == sb.replaceInput)
- sb.replace();
- sb.findNext();
- },
- "Shift-Return": function(sb) {
- if (sb.activeInput == sb.replaceInput)
- sb.replace();
- sb.findPrev();
- },
- "Alt-Return": function(sb) {
- if (sb.activeInput == sb.replaceInput)
- sb.replaceAll();
- sb.findAll();
- },
- "Tab": function(sb) {
- (sb.activeInput == sb.replaceInput ? sb.searchInput : sb.replaceInput).focus();
- }
- });
-
- this.$searchBarKb.addCommands([{
- name: "toggleRegexpMode",
- bindKey: {win: "Alt-R|Alt-/", mac: "Ctrl-Alt-R|Ctrl-Alt-/"},
- exec: function(sb) {
- sb.regExpOption.checked = !sb.regExpOption.checked;
- sb.$syncOptions();
- }
- }, {
- name: "toggleCaseSensitive",
- bindKey: {win: "Alt-C|Alt-I", mac: "Ctrl-Alt-R|Ctrl-Alt-I"},
- exec: function(sb) {
- sb.caseSensitiveOption.checked = !sb.caseSensitiveOption.checked;
- sb.$syncOptions();
- }
- }, {
- name: "toggleWholeWords",
- bindKey: {win: "Alt-B|Alt-W", mac: "Ctrl-Alt-B|Ctrl-Alt-W"},
- exec: function(sb) {
- sb.wholeWordOption.checked = !sb.wholeWordOption.checked;
- sb.$syncOptions();
- }
- }]);
-
- this.$syncOptions = function() {
- dom.setCssClass(this.regExpOption, "checked", this.regExpOption.checked);
- dom.setCssClass(this.wholeWordOption, "checked", this.wholeWordOption.checked);
- dom.setCssClass(this.caseSensitiveOption, "checked", this.caseSensitiveOption.checked);
- this.find(false, false);
- };
-
- this.highlight = function(re) {
- this.editor.session.highlight(re || this.editor.$search.$options.re);
- this.editor.renderer.updateBackMarkers()
- };
- this.find = function(skipCurrent, backwards, preventScroll) {
- var range = this.editor.find(this.searchInput.value, {
- skipCurrent: skipCurrent,
- backwards: backwards,
- wrap: true,
- regExp: this.regExpOption.checked,
- caseSensitive: this.caseSensitiveOption.checked,
- wholeWord: this.wholeWordOption.checked,
- preventScroll: preventScroll
- });
- var noMatch = !range && this.searchInput.value;
- dom.setCssClass(this.searchBox, "ace_nomatch", noMatch);
- this.editor._emit("findSearchBox", { match: !noMatch });
- this.highlight();
- };
- this.findNext = function() {
- this.find(true, false);
- };
- this.findPrev = function() {
- this.find(true, true);
- };
- this.findAll = function(){
- var range = this.editor.findAll(this.searchInput.value, {
- regExp: this.regExpOption.checked,
- caseSensitive: this.caseSensitiveOption.checked,
- wholeWord: this.wholeWordOption.checked
- });
- var noMatch = !range && this.searchInput.value;
- dom.setCssClass(this.searchBox, "ace_nomatch", noMatch);
- this.editor._emit("findSearchBox", { match: !noMatch });
- this.highlight();
- this.hide();
- };
- this.replace = function() {
- if (!this.editor.getReadOnly())
- this.editor.replace(this.replaceInput.value);
- };
- this.replaceAndFindNext = function() {
- if (!this.editor.getReadOnly()) {
- this.editor.replace(this.replaceInput.value);
- this.findNext()
- }
- };
- this.replaceAll = function() {
- if (!this.editor.getReadOnly())
- this.editor.replaceAll(this.replaceInput.value);
- };
-
- this.hide = function() {
- this.element.style.display = "none";
- this.editor.keyBinding.removeKeyboardHandler(this.$closeSearchBarKb);
- this.editor.focus();
- };
- this.show = function(value, isReplace) {
- this.element.style.display = "";
- this.replaceBox.style.display = isReplace ? "" : "none";
-
- this.isReplace = isReplace;
-
- if (value)
- this.searchInput.value = value;
-
- this.find(false, false, true);
-
- this.searchInput.focus();
- this.searchInput.select();
-
- this.editor.keyBinding.addKeyboardHandler(this.$closeSearchBarKb);
- };
-
- this.isFocused = function() {
- var el = document.activeElement;
- return el == this.searchInput || el == this.replaceInput;
- }
-}).call(SearchBox.prototype);
-
-exports.SearchBox = SearchBox;
-
-exports.Search = function(editor, isReplace) {
- var sb = editor.searchBox || new SearchBox(editor);
- sb.show(editor.session.getTextRange(), isReplace);
-};
-
-});
- (function() {
- ace.require(["ace/ext/searchbox"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-settings_menu.js b/icestudio/lib/ace-builds/src-noconflict/ext-settings_menu.js
deleted file mode 100644
index a1dcd675e..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-settings_menu.js
+++ /dev/null
@@ -1,653 +0,0 @@
-ace.define("ace/ext/menu_tools/element_generator",["require","exports","module"], function(require, exports, module) {
-'use strict';
-module.exports.createOption = function createOption (obj) {
- var attribute;
- var el = document.createElement('option');
- for(attribute in obj) {
- if(obj.hasOwnProperty(attribute)) {
- if(attribute === 'selected') {
- el.setAttribute(attribute, obj[attribute]);
- } else {
- el[attribute] = obj[attribute];
- }
- }
- }
- return el;
-};
-module.exports.createCheckbox = function createCheckbox (id, checked, clss) {
- var el = document.createElement('input');
- el.setAttribute('type', 'checkbox');
- el.setAttribute('id', id);
- el.setAttribute('name', id);
- el.setAttribute('value', checked);
- el.setAttribute('class', clss);
- if(checked) {
- el.setAttribute('checked', 'checked');
- }
- return el;
-};
-module.exports.createInput = function createInput (id, value, clss) {
- var el = document.createElement('input');
- el.setAttribute('type', 'text');
- el.setAttribute('id', id);
- el.setAttribute('name', id);
- el.setAttribute('value', value);
- el.setAttribute('class', clss);
- return el;
-};
-module.exports.createLabel = function createLabel (text, labelFor) {
- var el = document.createElement('label');
- el.setAttribute('for', labelFor);
- el.textContent = text;
- return el;
-};
-module.exports.createSelection = function createSelection (id, values, clss) {
- var el = document.createElement('select');
- el.setAttribute('id', id);
- el.setAttribute('name', id);
- el.setAttribute('class', clss);
- values.forEach(function(item) {
- el.appendChild(module.exports.createOption(item));
- });
- return el;
-};
-
-});
-
-ace.define("ace/ext/modelist",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-var modes = [];
-function getModeForPath(path) {
- var mode = modesByName.text;
- var fileName = path.split(/[\/\\]/).pop();
- for (var i = 0; i < modes.length; i++) {
- if (modes[i].supportsFile(fileName)) {
- mode = modes[i];
- break;
- }
- }
- return mode;
-}
-
-var Mode = function(name, caption, extensions) {
- this.name = name;
- this.caption = caption;
- this.mode = "ace/mode/" + name;
- this.extensions = extensions;
- var re;
- if (/\^/.test(extensions)) {
- re = extensions.replace(/\|(\^)?/g, function(a, b){
- return "$|" + (b ? "^" : "^.*\\.");
- }) + "$";
- } else {
- re = "^.*\\.(" + extensions + ")$";
- }
-
- this.extRe = new RegExp(re, "gi");
-};
-
-Mode.prototype.supportsFile = function(filename) {
- return filename.match(this.extRe);
-};
-var supportedModes = {
- ABAP: ["abap"],
- ABC: ["abc"],
- ActionScript:["as"],
- ADA: ["ada|adb"],
- Apache_Conf: ["^htaccess|^htgroups|^htpasswd|^conf|htaccess|htgroups|htpasswd"],
- AsciiDoc: ["asciidoc|adoc"],
- Assembly_x86:["asm|a"],
- AutoHotKey: ["ahk"],
- BatchFile: ["bat|cmd"],
- C_Cpp: ["cpp|c|cc|cxx|h|hh|hpp|ino"],
- C9Search: ["c9search_results"],
- Cirru: ["cirru|cr"],
- Clojure: ["clj|cljs"],
- Cobol: ["CBL|COB"],
- coffee: ["coffee|cf|cson|^Cakefile"],
- ColdFusion: ["cfm"],
- CSharp: ["cs"],
- CSS: ["css"],
- Curly: ["curly"],
- D: ["d|di"],
- Dart: ["dart"],
- Diff: ["diff|patch"],
- Dockerfile: ["^Dockerfile"],
- Dot: ["dot"],
- Dummy: ["dummy"],
- DummySyntax: ["dummy"],
- Eiffel: ["e|ge"],
- EJS: ["ejs"],
- Elixir: ["ex|exs"],
- Elm: ["elm"],
- Erlang: ["erl|hrl"],
- Forth: ["frt|fs|ldr"],
- FTL: ["ftl"],
- Gcode: ["gcode"],
- Gherkin: ["feature"],
- Gitignore: ["^.gitignore"],
- Glsl: ["glsl|frag|vert"],
- Gobstones: ["gbs"],
- golang: ["go"],
- Groovy: ["groovy"],
- HAML: ["haml"],
- Handlebars: ["hbs|handlebars|tpl|mustache"],
- Haskell: ["hs"],
- haXe: ["hx"],
- HTML: ["html|htm|xhtml"],
- HTML_Elixir: ["eex|html.eex"],
- HTML_Ruby: ["erb|rhtml|html.erb"],
- INI: ["ini|conf|cfg|prefs"],
- Io: ["io"],
- Jack: ["jack"],
- Jade: ["jade"],
- Java: ["java"],
- JavaScript: ["js|jsm|jsx"],
- JSON: ["json"],
- JSONiq: ["jq"],
- JSP: ["jsp"],
- JSX: ["jsx"],
- Julia: ["jl"],
- LaTeX: ["tex|latex|ltx|bib"],
- Lean: ["lean|hlean"],
- LESS: ["less"],
- Liquid: ["liquid"],
- Lisp: ["lisp"],
- LiveScript: ["ls"],
- LogiQL: ["logic|lql"],
- LSL: ["lsl"],
- Lua: ["lua"],
- LuaPage: ["lp"],
- Lucene: ["lucene"],
- Makefile: ["^Makefile|^GNUmakefile|^makefile|^OCamlMakefile|make"],
- Markdown: ["md|markdown"],
- Mask: ["mask"],
- MATLAB: ["matlab"],
- Maze: ["mz"],
- MEL: ["mel"],
- MUSHCode: ["mc|mush"],
- MySQL: ["mysql"],
- Nix: ["nix"],
- NSIS: ["nsi|nsh"],
- ObjectiveC: ["m|mm"],
- OCaml: ["ml|mli"],
- Pascal: ["pas|p"],
- Perl: ["pl|pm"],
- pgSQL: ["pgsql"],
- PHP: ["php|phtml|shtml|php3|php4|php5|phps|phpt|aw|ctp|module"],
- Powershell: ["ps1"],
- Praat: ["praat|praatscript|psc|proc"],
- Prolog: ["plg|prolog"],
- Properties: ["properties"],
- Protobuf: ["proto"],
- Python: ["py"],
- R: ["r"],
- Razor: ["cshtml"],
- RDoc: ["Rd"],
- RHTML: ["Rhtml"],
- RST: ["rst"],
- Ruby: ["rb|ru|gemspec|rake|^Guardfile|^Rakefile|^Gemfile"],
- Rust: ["rs"],
- SASS: ["sass"],
- SCAD: ["scad"],
- Scala: ["scala"],
- Scheme: ["scm|sm|rkt|oak|scheme"],
- SCSS: ["scss"],
- SH: ["sh|bash|^.bashrc"],
- SJS: ["sjs"],
- Smarty: ["smarty|tpl"],
- snippets: ["snippets"],
- Soy_Template:["soy"],
- Space: ["space"],
- SQL: ["sql"],
- SQLServer: ["sqlserver"],
- Stylus: ["styl|stylus"],
- SVG: ["svg"],
- Swift: ["swift"],
- Tcl: ["tcl"],
- Tex: ["tex"],
- Text: ["txt"],
- Textile: ["textile"],
- Toml: ["toml"],
- Twig: ["twig|swig"],
- Typescript: ["ts|typescript|str"],
- Vala: ["vala"],
- VBScript: ["vbs|vb"],
- Velocity: ["vm"],
- Verilog: ["v|vh|sv|svh"],
- VHDL: ["vhd|vhdl"],
- Wollok: ["wlk|wpgm|wtest"],
- XML: ["xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl|xaml"],
- XQuery: ["xq"],
- YAML: ["yaml|yml"],
- Django: ["html"]
-};
-
-var nameOverrides = {
- ObjectiveC: "Objective-C",
- CSharp: "C#",
- golang: "Go",
- C_Cpp: "C and C++",
- coffee: "CoffeeScript",
- HTML_Ruby: "HTML (Ruby)",
- HTML_Elixir: "HTML (Elixir)",
- FTL: "FreeMarker"
-};
-var modesByName = {};
-for (var name in supportedModes) {
- var data = supportedModes[name];
- var displayName = (nameOverrides[name] || name).replace(/_/g, " ");
- var filename = name.toLowerCase();
- var mode = new Mode(filename, displayName, data[0]);
- modesByName[filename] = mode;
- modes.push(mode);
-}
-
-module.exports = {
- getModeForPath: getModeForPath,
- modes: modes,
- modesByName: modesByName
-};
-
-});
-
-ace.define("ace/ext/themelist",["require","exports","module","ace/lib/fixoldbrowsers"], function(require, exports, module) {
-"use strict";
-require("ace/lib/fixoldbrowsers");
-
-var themeData = [
- ["Chrome" ],
- ["Clouds" ],
- ["Crimson Editor" ],
- ["Dawn" ],
- ["Dreamweaver" ],
- ["Eclipse" ],
- ["GitHub" ],
- ["IPlastic" ],
- ["Solarized Light"],
- ["TextMate" ],
- ["Tomorrow" ],
- ["XCode" ],
- ["Kuroir"],
- ["KatzenMilch"],
- ["SQL Server" ,"sqlserver" , "light"],
- ["Ambiance" ,"ambiance" , "dark"],
- ["Chaos" ,"chaos" , "dark"],
- ["Clouds Midnight" ,"clouds_midnight" , "dark"],
- ["Cobalt" ,"cobalt" , "dark"],
- ["idle Fingers" ,"idle_fingers" , "dark"],
- ["krTheme" ,"kr_theme" , "dark"],
- ["Merbivore" ,"merbivore" , "dark"],
- ["Merbivore Soft" ,"merbivore_soft" , "dark"],
- ["Mono Industrial" ,"mono_industrial" , "dark"],
- ["Monokai" ,"monokai" , "dark"],
- ["Pastel on dark" ,"pastel_on_dark" , "dark"],
- ["Solarized Dark" ,"solarized_dark" , "dark"],
- ["Terminal" ,"terminal" , "dark"],
- ["Tomorrow Night" ,"tomorrow_night" , "dark"],
- ["Tomorrow Night Blue" ,"tomorrow_night_blue" , "dark"],
- ["Tomorrow Night Bright","tomorrow_night_bright" , "dark"],
- ["Tomorrow Night 80s" ,"tomorrow_night_eighties" , "dark"],
- ["Twilight" ,"twilight" , "dark"],
- ["Vibrant Ink" ,"vibrant_ink" , "dark"]
-];
-
-
-exports.themesByName = {};
-exports.themes = themeData.map(function(data) {
- var name = data[1] || data[0].replace(/ /g, "_").toLowerCase();
- var theme = {
- caption: data[0],
- theme: "ace/theme/" + name,
- isDark: data[2] == "dark",
- name: name
- };
- exports.themesByName[name] = theme;
- return theme;
-});
-
-});
-
-ace.define("ace/ext/menu_tools/add_editor_menu_options",["require","exports","module","ace/ext/modelist","ace/ext/themelist"], function(require, exports, module) {
-'use strict';
-module.exports.addEditorMenuOptions = function addEditorMenuOptions (editor) {
- var modelist = require('../modelist');
- var themelist = require('../themelist');
- editor.menuOptions = {
- setNewLineMode: [{
- textContent: "unix",
- value: "unix"
- }, {
- textContent: "windows",
- value: "windows"
- }, {
- textContent: "auto",
- value: "auto"
- }],
- setTheme: [],
- setMode: [],
- setKeyboardHandler: [{
- textContent: "ace",
- value: ""
- }, {
- textContent: "vim",
- value: "ace/keyboard/vim"
- }, {
- textContent: "emacs",
- value: "ace/keyboard/emacs"
- }, {
- textContent: "textarea",
- value: "ace/keyboard/textarea"
- }, {
- textContent: "sublime",
- value: "ace/keyboard/sublime"
- }]
- };
-
- editor.menuOptions.setTheme = themelist.themes.map(function(theme) {
- return {
- textContent: theme.caption,
- value: theme.theme
- };
- });
-
- editor.menuOptions.setMode = modelist.modes.map(function(mode) {
- return {
- textContent: mode.name,
- value: mode.mode
- };
- });
-};
-
-
-});
-
-ace.define("ace/ext/menu_tools/get_set_functions",["require","exports","module"], function(require, exports, module) {
-'use strict';
-module.exports.getSetFunctions = function getSetFunctions (editor) {
- var out = [];
- var my = {
- 'editor' : editor,
- 'session' : editor.session,
- 'renderer' : editor.renderer
- };
- var opts = [];
- var skip = [
- 'setOption',
- 'setUndoManager',
- 'setDocument',
- 'setValue',
- 'setBreakpoints',
- 'setScrollTop',
- 'setScrollLeft',
- 'setSelectionStyle',
- 'setWrapLimitRange'
- ];
- ['renderer', 'session', 'editor'].forEach(function(esra) {
- var esr = my[esra];
- var clss = esra;
- for(var fn in esr) {
- if(skip.indexOf(fn) === -1) {
- if(/^set/.test(fn) && opts.indexOf(fn) === -1) {
- opts.push(fn);
- out.push({
- 'functionName' : fn,
- 'parentObj' : esr,
- 'parentName' : clss
- });
- }
- }
- }
- });
- return out;
-};
-
-});
-
-ace.define("ace/ext/menu_tools/generate_settings_menu",["require","exports","module","ace/ext/menu_tools/element_generator","ace/ext/menu_tools/add_editor_menu_options","ace/ext/menu_tools/get_set_functions","ace/ace"], function(require, exports, module) {
-'use strict';
-var egen = require('./element_generator');
-var addEditorMenuOptions = require('./add_editor_menu_options').addEditorMenuOptions;
-var getSetFunctions = require('./get_set_functions').getSetFunctions;
-module.exports.generateSettingsMenu = function generateSettingsMenu (editor) {
- var elements = [];
- function cleanupElementsList() {
- elements.sort(function(a, b) {
- var x = a.getAttribute('contains');
- var y = b.getAttribute('contains');
- return x.localeCompare(y);
- });
- }
- function wrapElements() {
- var topmenu = document.createElement('div');
- topmenu.setAttribute('id', 'ace_settingsmenu');
- elements.forEach(function(element) {
- topmenu.appendChild(element);
- });
-
- var el = topmenu.appendChild(document.createElement('div'));
- var version = require("../../ace").version;
- el.style.padding = "1em";
- el.textContent = "Ace version " + version;
-
- return topmenu;
- }
- function createNewEntry(obj, clss, item, val) {
- var el;
- var div = document.createElement('div');
- div.setAttribute('contains', item);
- div.setAttribute('class', 'ace_optionsMenuEntry');
- div.setAttribute('style', 'clear: both;');
-
- div.appendChild(egen.createLabel(
- item.replace(/^set/, '').replace(/([A-Z])/g, ' $1').trim(),
- item
- ));
-
- if (Array.isArray(val)) {
- el = egen.createSelection(item, val, clss);
- el.addEventListener('change', function(e) {
- try{
- editor.menuOptions[e.target.id].forEach(function(x) {
- if(x.textContent !== e.target.textContent) {
- delete x.selected;
- }
- });
- obj[e.target.id](e.target.value);
- } catch (err) {
- throw new Error(err);
- }
- });
- } else if(typeof val === 'boolean') {
- el = egen.createCheckbox(item, val, clss);
- el.addEventListener('change', function(e) {
- try{
- obj[e.target.id](!!e.target.checked);
- } catch (err) {
- throw new Error(err);
- }
- });
- } else {
- el = egen.createInput(item, val, clss);
- el.addEventListener('change', function(e) {
- try{
- if(e.target.value === 'true') {
- obj[e.target.id](true);
- } else if(e.target.value === 'false') {
- obj[e.target.id](false);
- } else {
- obj[e.target.id](e.target.value);
- }
- } catch (err) {
- throw new Error(err);
- }
- });
- }
- el.style.cssText = 'float:right;';
- div.appendChild(el);
- return div;
- }
- function makeDropdown(item, esr, clss, fn) {
- var val = editor.menuOptions[item];
- var currentVal = esr[fn]();
- if (typeof currentVal == 'object')
- currentVal = currentVal.$id;
- val.forEach(function(valuex) {
- if (valuex.value === currentVal)
- valuex.selected = 'selected';
- });
- return createNewEntry(esr, clss, item, val);
- }
- function handleSet(setObj) {
- var item = setObj.functionName;
- var esr = setObj.parentObj;
- var clss = setObj.parentName;
- var val;
- var fn = item.replace(/^set/, 'get');
- if(editor.menuOptions[item] !== undefined) {
- elements.push(makeDropdown(item, esr, clss, fn));
- } else if(typeof esr[fn] === 'function') {
- try {
- val = esr[fn]();
- if(typeof val === 'object') {
- val = val.$id;
- }
- elements.push(
- createNewEntry(esr, clss, item, val)
- );
- } catch (e) {
- }
- }
- }
- addEditorMenuOptions(editor);
- getSetFunctions(editor).forEach(function(setObj) {
- handleSet(setObj);
- });
- cleanupElementsList();
- return wrapElements();
-};
-
-});
-
-ace.define("ace/ext/menu_tools/overlay_page",["require","exports","module","ace/lib/dom"], function(require, exports, module) {
-'use strict';
-var dom = require("../../lib/dom");
-var cssText = "#ace_settingsmenu, #kbshortcutmenu {\
-background-color: #F7F7F7;\
-color: black;\
-box-shadow: -5px 4px 5px rgba(126, 126, 126, 0.55);\
-padding: 1em 0.5em 2em 1em;\
-overflow: auto;\
-position: absolute;\
-margin: 0;\
-bottom: 0;\
-right: 0;\
-top: 0;\
-z-index: 9991;\
-cursor: default;\
-}\
-.ace_dark #ace_settingsmenu, .ace_dark #kbshortcutmenu {\
-box-shadow: -20px 10px 25px rgba(126, 126, 126, 0.25);\
-background-color: rgba(255, 255, 255, 0.6);\
-color: black;\
-}\
-.ace_optionsMenuEntry:hover {\
-background-color: rgba(100, 100, 100, 0.1);\
--webkit-transition: all 0.5s;\
-transition: all 0.3s\
-}\
-.ace_closeButton {\
-background: rgba(245, 146, 146, 0.5);\
-border: 1px solid #F48A8A;\
-border-radius: 50%;\
-padding: 7px;\
-position: absolute;\
-right: -8px;\
-top: -8px;\
-z-index: 1000;\
-}\
-.ace_closeButton{\
-background: rgba(245, 146, 146, 0.9);\
-}\
-.ace_optionsMenuKey {\
-color: darkslateblue;\
-font-weight: bold;\
-}\
-.ace_optionsMenuCommand {\
-color: darkcyan;\
-font-weight: normal;\
-}";
-dom.importCssString(cssText);
-module.exports.overlayPage = function overlayPage(editor, contentElement, top, right, bottom, left) {
- top = top ? 'top: ' + top + ';' : '';
- bottom = bottom ? 'bottom: ' + bottom + ';' : '';
- right = right ? 'right: ' + right + ';' : '';
- left = left ? 'left: ' + left + ';' : '';
-
- var closer = document.createElement('div');
- var contentContainer = document.createElement('div');
-
- function documentEscListener(e) {
- if (e.keyCode === 27) {
- closer.click();
- }
- }
-
- closer.style.cssText = 'margin: 0; padding: 0; ' +
- 'position: fixed; top:0; bottom:0; left:0; right:0;' +
- 'z-index: 9990; ' +
- 'background-color: rgba(0, 0, 0, 0.3);';
- closer.addEventListener('click', function() {
- document.removeEventListener('keydown', documentEscListener);
- closer.parentNode.removeChild(closer);
- editor.focus();
- closer = null;
- });
- document.addEventListener('keydown', documentEscListener);
-
- contentContainer.style.cssText = top + right + bottom + left;
- contentContainer.addEventListener('click', function(e) {
- e.stopPropagation();
- });
-
- var wrapper = dom.createElement("div");
- wrapper.style.position = "relative";
-
- var closeButton = dom.createElement("div");
- closeButton.className = "ace_closeButton";
- closeButton.addEventListener('click', function() {
- closer.click();
- });
-
- wrapper.appendChild(closeButton);
- contentContainer.appendChild(wrapper);
-
- contentContainer.appendChild(contentElement);
- closer.appendChild(contentContainer);
- document.body.appendChild(closer);
- editor.blur();
-};
-
-});
-
-ace.define("ace/ext/settings_menu",["require","exports","module","ace/ext/menu_tools/generate_settings_menu","ace/ext/menu_tools/overlay_page","ace/editor"], function(require, exports, module) {
-"use strict";
-var generateSettingsMenu = require('./menu_tools/generate_settings_menu').generateSettingsMenu;
-var overlayPage = require('./menu_tools/overlay_page').overlayPage;
-function showSettingsMenu(editor) {
- var sm = document.getElementById('ace_settingsmenu');
- if (!sm)
- overlayPage(editor, generateSettingsMenu(editor), '0', '0', '0');
-}
-module.exports.init = function(editor) {
- var Editor = require("ace/editor").Editor;
- Editor.prototype.showSettingsMenu = function() {
- showSettingsMenu(this);
- };
-};
-});
- (function() {
- ace.require(["ace/ext/settings_menu"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-spellcheck.js b/icestudio/lib/ace-builds/src-noconflict/ext-spellcheck.js
deleted file mode 100644
index 8d3b5f6cb..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-spellcheck.js
+++ /dev/null
@@ -1,71 +0,0 @@
-ace.define("ace/ext/spellcheck",["require","exports","module","ace/lib/event","ace/editor","ace/config"], function(require, exports, module) {
-"use strict";
-var event = require("../lib/event");
-
-exports.contextMenuHandler = function(e){
- var host = e.target;
- var text = host.textInput.getElement();
- if (!host.selection.isEmpty())
- return;
- var c = host.getCursorPosition();
- var r = host.session.getWordRange(c.row, c.column);
- var w = host.session.getTextRange(r);
-
- host.session.tokenRe.lastIndex = 0;
- if (!host.session.tokenRe.test(w))
- return;
- var PLACEHOLDER = "\x01\x01";
- var value = w + " " + PLACEHOLDER;
- text.value = value;
- text.setSelectionRange(w.length, w.length + 1);
- text.setSelectionRange(0, 0);
- text.setSelectionRange(0, w.length);
-
- var afterKeydown = false;
- event.addListener(text, "keydown", function onKeydown() {
- event.removeListener(text, "keydown", onKeydown);
- afterKeydown = true;
- });
-
- host.textInput.setInputHandler(function(newVal) {
- console.log(newVal , value, text.selectionStart, text.selectionEnd)
- if (newVal == value)
- return '';
- if (newVal.lastIndexOf(value, 0) === 0)
- return newVal.slice(value.length);
- if (newVal.substr(text.selectionEnd) == value)
- return newVal.slice(0, -value.length);
- if (newVal.slice(-2) == PLACEHOLDER) {
- var val = newVal.slice(0, -2);
- if (val.slice(-1) == " ") {
- if (afterKeydown)
- return val.substring(0, text.selectionEnd);
- val = val.slice(0, -1);
- host.session.replace(r, val);
- return "";
- }
- }
-
- return newVal;
- });
-};
-var Editor = require("../editor").Editor;
-require("../config").defineOptions(Editor.prototype, "editor", {
- spellcheck: {
- set: function(val) {
- var text = this.textInput.getElement();
- text.spellcheck = !!val;
- if (!val)
- this.removeListener("nativecontextmenu", exports.contextMenuHandler);
- else
- this.on("nativecontextmenu", exports.contextMenuHandler);
- },
- value: true
- }
-});
-
-});
- (function() {
- ace.require(["ace/ext/spellcheck"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-split.js b/icestudio/lib/ace-builds/src-noconflict/ext-split.js
deleted file mode 100644
index 29dd20efb..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-split.js
+++ /dev/null
@@ -1,246 +0,0 @@
-ace.define("ace/split",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter","ace/editor","ace/virtual_renderer","ace/edit_session"], function(require, exports, module) {
-"use strict";
-
-var oop = require("./lib/oop");
-var lang = require("./lib/lang");
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-
-var Editor = require("./editor").Editor;
-var Renderer = require("./virtual_renderer").VirtualRenderer;
-var EditSession = require("./edit_session").EditSession;
-
-
-var Split = function(container, theme, splits) {
- this.BELOW = 1;
- this.BESIDE = 0;
-
- this.$container = container;
- this.$theme = theme;
- this.$splits = 0;
- this.$editorCSS = "";
- this.$editors = [];
- this.$orientation = this.BESIDE;
-
- this.setSplits(splits || 1);
- this.$cEditor = this.$editors[0];
-
-
- this.on("focus", function(editor) {
- this.$cEditor = editor;
- }.bind(this));
-};
-
-(function(){
-
- oop.implement(this, EventEmitter);
-
- this.$createEditor = function() {
- var el = document.createElement("div");
- el.className = this.$editorCSS;
- el.style.cssText = "position: absolute; top:0px; bottom:0px";
- this.$container.appendChild(el);
- var editor = new Editor(new Renderer(el, this.$theme));
-
- editor.on("focus", function() {
- this._emit("focus", editor);
- }.bind(this));
-
- this.$editors.push(editor);
- editor.setFontSize(this.$fontSize);
- return editor;
- };
-
- this.setSplits = function(splits) {
- var editor;
- if (splits < 1) {
- throw "The number of splits have to be > 0!";
- }
-
- if (splits == this.$splits) {
- return;
- } else if (splits > this.$splits) {
- while (this.$splits < this.$editors.length && this.$splits < splits) {
- editor = this.$editors[this.$splits];
- this.$container.appendChild(editor.container);
- editor.setFontSize(this.$fontSize);
- this.$splits ++;
- }
- while (this.$splits < splits) {
- this.$createEditor();
- this.$splits ++;
- }
- } else {
- while (this.$splits > splits) {
- editor = this.$editors[this.$splits - 1];
- this.$container.removeChild(editor.container);
- this.$splits --;
- }
- }
- this.resize();
- };
- this.getSplits = function() {
- return this.$splits;
- };
- this.getEditor = function(idx) {
- return this.$editors[idx];
- };
- this.getCurrentEditor = function() {
- return this.$cEditor;
- };
- this.focus = function() {
- this.$cEditor.focus();
- };
- this.blur = function() {
- this.$cEditor.blur();
- };
- this.setTheme = function(theme) {
- this.$editors.forEach(function(editor) {
- editor.setTheme(theme);
- });
- };
- this.setKeyboardHandler = function(keybinding) {
- this.$editors.forEach(function(editor) {
- editor.setKeyboardHandler(keybinding);
- });
- };
- this.forEach = function(callback, scope) {
- this.$editors.forEach(callback, scope);
- };
-
-
- this.$fontSize = "";
- this.setFontSize = function(size) {
- this.$fontSize = size;
- this.forEach(function(editor) {
- editor.setFontSize(size);
- });
- };
-
- this.$cloneSession = function(session) {
- var s = new EditSession(session.getDocument(), session.getMode());
-
- var undoManager = session.getUndoManager();
- if (undoManager) {
- var undoManagerProxy = new UndoManagerProxy(undoManager, s);
- s.setUndoManager(undoManagerProxy);
- }
- s.$informUndoManager = lang.delayedCall(function() { s.$deltas = []; });
- s.setTabSize(session.getTabSize());
- s.setUseSoftTabs(session.getUseSoftTabs());
- s.setOverwrite(session.getOverwrite());
- s.setBreakpoints(session.getBreakpoints());
- s.setUseWrapMode(session.getUseWrapMode());
- s.setUseWorker(session.getUseWorker());
- s.setWrapLimitRange(session.$wrapLimitRange.min,
- session.$wrapLimitRange.max);
- s.$foldData = session.$cloneFoldData();
-
- return s;
- };
- this.setSession = function(session, idx) {
- var editor;
- if (idx == null) {
- editor = this.$cEditor;
- } else {
- editor = this.$editors[idx];
- }
- var isUsed = this.$editors.some(function(editor) {
- return editor.session === session;
- });
-
- if (isUsed) {
- session = this.$cloneSession(session);
- }
- editor.setSession(session);
- return session;
- };
- this.getOrientation = function() {
- return this.$orientation;
- };
- this.setOrientation = function(orientation) {
- if (this.$orientation == orientation) {
- return;
- }
- this.$orientation = orientation;
- this.resize();
- };
- this.resize = function() {
- var width = this.$container.clientWidth;
- var height = this.$container.clientHeight;
- var editor;
-
- if (this.$orientation == this.BESIDE) {
- var editorWidth = width / this.$splits;
- for (var i = 0; i < this.$splits; i++) {
- editor = this.$editors[i];
- editor.container.style.width = editorWidth + "px";
- editor.container.style.top = "0px";
- editor.container.style.left = i * editorWidth + "px";
- editor.container.style.height = height + "px";
- editor.resize();
- }
- } else {
- var editorHeight = height / this.$splits;
- for (var i = 0; i < this.$splits; i++) {
- editor = this.$editors[i];
- editor.container.style.width = width + "px";
- editor.container.style.top = i * editorHeight + "px";
- editor.container.style.left = "0px";
- editor.container.style.height = editorHeight + "px";
- editor.resize();
- }
- }
- };
-
-}).call(Split.prototype);
-
-
-function UndoManagerProxy(undoManager, session) {
- this.$u = undoManager;
- this.$doc = session;
-}
-
-(function() {
- this.execute = function(options) {
- this.$u.execute(options);
- };
-
- this.undo = function() {
- var selectionRange = this.$u.undo(true);
- if (selectionRange) {
- this.$doc.selection.setSelectionRange(selectionRange);
- }
- };
-
- this.redo = function() {
- var selectionRange = this.$u.redo(true);
- if (selectionRange) {
- this.$doc.selection.setSelectionRange(selectionRange);
- }
- };
-
- this.reset = function() {
- this.$u.reset();
- };
-
- this.hasUndo = function() {
- return this.$u.hasUndo();
- };
-
- this.hasRedo = function() {
- return this.$u.hasRedo();
- };
-}).call(UndoManagerProxy.prototype);
-
-exports.Split = Split;
-});
-
-ace.define("ace/ext/split",["require","exports","module","ace/split"], function(require, exports, module) {
-"use strict";
-module.exports = require("../split");
-
-});
- (function() {
- ace.require(["ace/ext/split"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-static_highlight.js b/icestudio/lib/ace-builds/src-noconflict/ext-static_highlight.js
deleted file mode 100644
index 98ee7ea51..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-static_highlight.js
+++ /dev/null
@@ -1,161 +0,0 @@
-ace.define("ace/ext/static_highlight",["require","exports","module","ace/edit_session","ace/layer/text","ace/config","ace/lib/dom"], function(require, exports, module) {
-"use strict";
-
-var EditSession = require("../edit_session").EditSession;
-var TextLayer = require("../layer/text").Text;
-var baseStyles = ".ace_static_highlight {\
-font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'Droid Sans Mono', monospace;\
-font-size: 12px;\
-white-space: pre-wrap\
-}\
-.ace_static_highlight .ace_gutter {\
-width: 2em;\
-text-align: right;\
-padding: 0 3px 0 0;\
-margin-right: 3px;\
-}\
-.ace_static_highlight.ace_show_gutter .ace_line {\
-padding-left: 2.6em;\
-}\
-.ace_static_highlight .ace_line { position: relative; }\
-.ace_static_highlight .ace_gutter-cell {\
--moz-user-select: -moz-none;\
--khtml-user-select: none;\
--webkit-user-select: none;\
-user-select: none;\
-top: 0;\
-bottom: 0;\
-left: 0;\
-position: absolute;\
-}\
-.ace_static_highlight .ace_gutter-cell:before {\
-content: counter(ace_line, decimal);\
-counter-increment: ace_line;\
-}\
-.ace_static_highlight {\
-counter-reset: ace_line;\
-}\
-";
-var config = require("../config");
-var dom = require("../lib/dom");
-
-var SimpleTextLayer = function() {
- this.config = {};
-};
-SimpleTextLayer.prototype = TextLayer.prototype;
-
-var highlight = function(el, opts, callback) {
- var m = el.className.match(/lang-(\w+)/);
- var mode = opts.mode || m && ("ace/mode/" + m[1]);
- if (!mode)
- return false;
- var theme = opts.theme || "ace/theme/textmate";
-
- var data = "";
- var nodes = [];
-
- if (el.firstElementChild) {
- var textLen = 0;
- for (var i = 0; i < el.childNodes.length; i++) {
- var ch = el.childNodes[i];
- if (ch.nodeType == 3) {
- textLen += ch.data.length;
- data += ch.data;
- } else {
- nodes.push(textLen, ch);
- }
- }
- } else {
- data = dom.getInnerText(el);
- if (opts.trim)
- data = data.trim();
- }
-
- highlight.render(data, mode, theme, opts.firstLineNumber, !opts.showGutter, function (highlighted) {
- dom.importCssString(highlighted.css, "ace_highlight");
- el.innerHTML = highlighted.html;
- var container = el.firstChild.firstChild;
- for (var i = 0; i < nodes.length; i += 2) {
- var pos = highlighted.session.doc.indexToPosition(nodes[i]);
- var node = nodes[i + 1];
- var lineEl = container.children[pos.row];
- lineEl && lineEl.appendChild(node);
- }
- callback && callback();
- });
-};
-highlight.render = function(input, mode, theme, lineStart, disableGutter, callback) {
- var waiting = 1;
- var modeCache = EditSession.prototype.$modes;
- if (typeof theme == "string") {
- waiting++;
- config.loadModule(['theme', theme], function(m) {
- theme = m;
- --waiting || done();
- });
- }
- var modeOptions;
- if (mode && typeof mode === "object" && !mode.getTokenizer) {
- modeOptions = mode;
- mode = modeOptions.path;
- }
- if (typeof mode == "string") {
- waiting++;
- config.loadModule(['mode', mode], function(m) {
- if (!modeCache[mode] || modeOptions)
- modeCache[mode] = new m.Mode(modeOptions);
- mode = modeCache[mode];
- --waiting || done();
- });
- }
- function done() {
- var result = highlight.renderSync(input, mode, theme, lineStart, disableGutter);
- return callback ? callback(result) : result;
- }
- return --waiting || done();
-};
-highlight.renderSync = function(input, mode, theme, lineStart, disableGutter) {
- lineStart = parseInt(lineStart || 1, 10);
-
- var session = new EditSession("");
- session.setUseWorker(false);
- session.setMode(mode);
-
- var textLayer = new SimpleTextLayer();
- textLayer.setSession(session);
-
- session.setValue(input);
-
- var stringBuilder = [];
- var length = session.getLength();
-
- for(var ix = 0; ix < length; ix++) {
- stringBuilder.push("
");
- if (!disableGutter)
- stringBuilder.push("" + /*(ix + lineStart) + */ "");
- textLayer.$renderLine(stringBuilder, ix, true, false);
- stringBuilder.push("\n
");
- }
- var html = "
" +
- "
" +
- stringBuilder.join("") +
- "
" +
- "
";
-
- textLayer.destroy();
-
- return {
- css: baseStyles + theme.cssText,
- html: html,
- session: session
- };
-};
-
-module.exports = highlight;
-module.exports.highlight =highlight;
-});
- (function() {
- ace.require(["ace/ext/static_highlight"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-statusbar.js b/icestudio/lib/ace-builds/src-noconflict/ext-statusbar.js
deleted file mode 100644
index 0c46b3812..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-statusbar.js
+++ /dev/null
@@ -1,53 +0,0 @@
-ace.define("ace/ext/statusbar",["require","exports","module","ace/lib/dom","ace/lib/lang"], function(require, exports, module) {
-"use strict";
-var dom = require("ace/lib/dom");
-var lang = require("ace/lib/lang");
-
-var StatusBar = function(editor, parentNode) {
- this.element = dom.createElement("div");
- this.element.className = "ace_status-indicator";
- this.element.style.cssText = "display: inline-block;";
- parentNode.appendChild(this.element);
-
- var statusUpdate = lang.delayedCall(function(){
- this.updateStatus(editor)
- }.bind(this)).schedule.bind(null, 100);
-
- editor.on("changeStatus", statusUpdate);
- editor.on("changeSelection", statusUpdate);
- editor.on("keyboardActivity", statusUpdate);
-};
-
-(function(){
- this.updateStatus = function(editor) {
- var status = [];
- function add(str, separator) {
- str && status.push(str, separator || "|");
- }
-
- add(editor.keyBinding.getStatusText(editor));
- if (editor.commands.recording)
- add("REC");
-
- var sel = editor.selection;
- var c = sel.lead;
-
- if (!sel.isEmpty()) {
- var r = editor.getSelectionRange();
- add("(" + (r.end.row - r.start.row) + ":" +(r.end.column - r.start.column) + ")", " ");
- }
- add(c.row + ":" + c.column, " ");
- if (sel.rangeCount)
- add("[" + sel.rangeCount + "]", " ");
- status.pop();
- this.element.textContent = status.join("");
- };
-}).call(StatusBar.prototype);
-
-exports.StatusBar = StatusBar;
-
-});
- (function() {
- ace.require(["ace/ext/statusbar"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-textarea.js b/icestudio/lib/ace-builds/src-noconflict/ext-textarea.js
deleted file mode 100644
index 17aa92f55..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-textarea.js
+++ /dev/null
@@ -1,559 +0,0 @@
-ace.define("ace/theme/textmate",["require","exports","module","ace/lib/dom"], function(require, exports, module) {
-"use strict";
-
-exports.isDark = false;
-exports.cssClass = "ace-tm";
-exports.cssText = ".ace-tm .ace_gutter {\
-background: #f0f0f0;\
-color: #333;\
-}\
-.ace-tm .ace_print-margin {\
-width: 1px;\
-background: #e8e8e8;\
-}\
-.ace-tm .ace_fold {\
-background-color: #6B72E6;\
-}\
-.ace-tm {\
-background-color: #FFFFFF;\
-color: black;\
-}\
-.ace-tm .ace_cursor {\
-color: black;\
-}\
-.ace-tm .ace_invisible {\
-color: rgb(191, 191, 191);\
-}\
-.ace-tm .ace_storage,\
-.ace-tm .ace_keyword {\
-color: blue;\
-}\
-.ace-tm .ace_constant {\
-color: rgb(197, 6, 11);\
-}\
-.ace-tm .ace_constant.ace_buildin {\
-color: rgb(88, 72, 246);\
-}\
-.ace-tm .ace_constant.ace_language {\
-color: rgb(88, 92, 246);\
-}\
-.ace-tm .ace_constant.ace_library {\
-color: rgb(6, 150, 14);\
-}\
-.ace-tm .ace_invalid {\
-background-color: rgba(255, 0, 0, 0.1);\
-color: red;\
-}\
-.ace-tm .ace_support.ace_function {\
-color: rgb(60, 76, 114);\
-}\
-.ace-tm .ace_support.ace_constant {\
-color: rgb(6, 150, 14);\
-}\
-.ace-tm .ace_support.ace_type,\
-.ace-tm .ace_support.ace_class {\
-color: rgb(109, 121, 222);\
-}\
-.ace-tm .ace_keyword.ace_operator {\
-color: rgb(104, 118, 135);\
-}\
-.ace-tm .ace_string {\
-color: rgb(3, 106, 7);\
-}\
-.ace-tm .ace_comment {\
-color: rgb(76, 136, 107);\
-}\
-.ace-tm .ace_comment.ace_doc {\
-color: rgb(0, 102, 255);\
-}\
-.ace-tm .ace_comment.ace_doc.ace_tag {\
-color: rgb(128, 159, 191);\
-}\
-.ace-tm .ace_constant.ace_numeric {\
-color: rgb(0, 0, 205);\
-}\
-.ace-tm .ace_variable {\
-color: rgb(49, 132, 149);\
-}\
-.ace-tm .ace_xml-pe {\
-color: rgb(104, 104, 91);\
-}\
-.ace-tm .ace_entity.ace_name.ace_function {\
-color: #0000A2;\
-}\
-.ace-tm .ace_heading {\
-color: rgb(12, 7, 255);\
-}\
-.ace-tm .ace_list {\
-color:rgb(185, 6, 144);\
-}\
-.ace-tm .ace_meta.ace_tag {\
-color:rgb(0, 22, 142);\
-}\
-.ace-tm .ace_string.ace_regex {\
-color: rgb(255, 0, 0)\
-}\
-.ace-tm .ace_marker-layer .ace_selection {\
-background: rgb(181, 213, 255);\
-}\
-.ace-tm.ace_multiselect .ace_selection.ace_start {\
-box-shadow: 0 0 3px 0px white;\
-}\
-.ace-tm .ace_marker-layer .ace_step {\
-background: rgb(252, 255, 0);\
-}\
-.ace-tm .ace_marker-layer .ace_stack {\
-background: rgb(164, 229, 101);\
-}\
-.ace-tm .ace_marker-layer .ace_bracket {\
-margin: -1px 0 0 -1px;\
-border: 1px solid rgb(192, 192, 192);\
-}\
-.ace-tm .ace_marker-layer .ace_active-line {\
-background: rgba(0, 0, 0, 0.07);\
-}\
-.ace-tm .ace_gutter-active-line {\
-background-color : #dcdcdc;\
-}\
-.ace-tm .ace_marker-layer .ace_selected-word {\
-background: rgb(250, 250, 255);\
-border: 1px solid rgb(200, 200, 250);\
-}\
-.ace-tm .ace_indent-guide {\
-background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\
-}\
-";
-
-var dom = require("../lib/dom");
-dom.importCssString(exports.cssText, exports.cssClass);
-});
-
-ace.define("ace/ext/textarea",["require","exports","module","ace/lib/event","ace/lib/useragent","ace/lib/net","ace/ace","ace/theme/textmate"], function(require, exports, module) {
-"use strict";
-
-var event = require("../lib/event");
-var UA = require("../lib/useragent");
-var net = require("../lib/net");
-var ace = require("../ace");
-
-require("../theme/textmate");
-
-module.exports = exports = ace;
-var getCSSProperty = function(element, container, property) {
- var ret = element.style[property];
-
- if (!ret) {
- if (window.getComputedStyle) {
- ret = window.getComputedStyle(element, '').getPropertyValue(property);
- } else {
- ret = element.currentStyle[property];
- }
- }
-
- if (!ret || ret == 'auto' || ret == 'intrinsic') {
- ret = container.style[property];
- }
- return ret;
-};
-
-function applyStyles(elm, styles) {
- for (var style in styles) {
- elm.style[style] = styles[style];
- }
-}
-
-function setupContainer(element, getValue) {
- if (element.type != 'textarea') {
- throw new Error("Textarea required!");
- }
-
- var parentNode = element.parentNode;
- var container = document.createElement('div');
- var resizeEvent = function() {
- var style = 'position:relative;';
- [
- 'margin-top', 'margin-left', 'margin-right', 'margin-bottom'
- ].forEach(function(item) {
- style += item + ':' +
- getCSSProperty(element, container, item) + ';';
- });
- var width = getCSSProperty(element, container, 'width') || (element.clientWidth + "px");
- var height = getCSSProperty(element, container, 'height') || (element.clientHeight + "px");
- style += 'height:' + height + ';width:' + width + ';';
- style += 'display:inline-block;';
- container.setAttribute('style', style);
- };
- event.addListener(window, 'resize', resizeEvent);
- resizeEvent();
- parentNode.insertBefore(container, element.nextSibling);
- while (parentNode !== document) {
- if (parentNode.tagName.toUpperCase() === 'FORM') {
- var oldSumit = parentNode.onsubmit;
- parentNode.onsubmit = function(evt) {
- element.value = getValue();
- if (oldSumit) {
- oldSumit.call(this, evt);
- }
- };
- break;
- }
- parentNode = parentNode.parentNode;
- }
- return container;
-}
-
-exports.transformTextarea = function(element, options) {
- var session;
- var container = setupContainer(element, function() {
- return session.getValue();
- });
- element.style.display = 'none';
- container.style.background = 'white';
- var editorDiv = document.createElement("div");
- applyStyles(editorDiv, {
- top: "0px",
- left: "0px",
- right: "0px",
- bottom: "0px",
- border: "1px solid gray",
- position: "absolute"
- });
- container.appendChild(editorDiv);
-
- var settingOpener = document.createElement("div");
- applyStyles(settingOpener, {
- position: "absolute",
- right: "0px",
- bottom: "0px",
- background: "red",
- cursor: "nw-resize",
- borderStyle: "solid",
- borderWidth: "9px 8px 10px 9px",
- width: "2px",
- borderColor: "lightblue gray gray lightblue",
- zIndex: 101
- });
-
- var settingDiv = document.createElement("div");
- var settingDivStyles = {
- top: "0px",
- left: "20%",
- right: "0px",
- bottom: "0px",
- position: "absolute",
- padding: "5px",
- zIndex: 100,
- color: "white",
- display: "none",
- overflow: "auto",
- fontSize: "14px",
- boxShadow: "-5px 2px 3px gray"
- };
- if (!UA.isOldIE) {
- settingDivStyles.backgroundColor = "rgba(0, 0, 0, 0.6)";
- } else {
- settingDivStyles.backgroundColor = "#333";
- }
-
- applyStyles(settingDiv, settingDivStyles);
- container.appendChild(settingDiv);
-
- options = options || exports.defaultOptions;
- var editor = ace.edit(editorDiv);
- session = editor.getSession();
-
- session.setValue(element.value || element.innerHTML);
- editor.focus();
- container.appendChild(settingOpener);
- setupApi(editor, editorDiv, settingDiv, ace, options, load);
- setupSettingPanel(settingDiv, settingOpener, editor);
-
- var state = "";
- event.addListener(settingOpener, "mousemove", function(e) {
- var rect = this.getBoundingClientRect();
- var x = e.clientX - rect.left, y = e.clientY - rect.top;
- if (x + y < (rect.width + rect.height)/2) {
- this.style.cursor = "pointer";
- state = "toggle";
- } else {
- state = "resize";
- this.style.cursor = "nw-resize";
- }
- });
-
- event.addListener(settingOpener, "mousedown", function(e) {
- if (state == "toggle") {
- editor.setDisplaySettings();
- return;
- }
- container.style.zIndex = 100000;
- var rect = container.getBoundingClientRect();
- var startX = rect.width + rect.left - e.clientX;
- var startY = rect.height + rect.top - e.clientY;
- event.capture(settingOpener, function(e) {
- container.style.width = e.clientX - rect.left + startX + "px";
- container.style.height = e.clientY - rect.top + startY + "px";
- editor.resize();
- }, function() {});
- });
-
- return editor;
-};
-
-function load(url, module, callback) {
- net.loadScript(url, function() {
- require([module], callback);
- });
-}
-
-function setupApi(editor, editorDiv, settingDiv, ace, options, loader) {
- var session = editor.getSession();
- var renderer = editor.renderer;
- loader = loader || load;
-
- function toBool(value) {
- return value === "true" || value == true;
- }
-
- editor.setDisplaySettings = function(display) {
- if (display == null)
- display = settingDiv.style.display == "none";
- if (display) {
- settingDiv.style.display = "block";
- settingDiv.hideButton.focus();
- editor.on("focus", function onFocus() {
- editor.removeListener("focus", onFocus);
- settingDiv.style.display = "none";
- });
- } else {
- editor.focus();
- }
- };
-
- editor.$setOption = editor.setOption;
- editor.$getOption = editor.getOption;
- editor.setOption = function(key, value) {
- switch (key) {
- case "mode":
- editor.$setOption("mode", "ace/mode/" + value)
- break;
- case "theme":
- editor.$setOption("theme", "ace/theme/" + value)
- break;
- case "keybindings":
- switch (value) {
- case "vim":
- editor.setKeyboardHandler("ace/keyboard/vim");
- break;
- case "emacs":
- editor.setKeyboardHandler("ace/keyboard/emacs");
- break;
- default:
- editor.setKeyboardHandler(null);
- }
- break;
-
- case "softWrap":
- case "fontSize":
- editor.$setOption(key, value);
- break;
-
- default:
- editor.$setOption(key, toBool(value));
- }
- };
-
- editor.getOption = function(key) {
- switch (key) {
- case "mode":
- return editor.$getOption("mode").substr("ace/mode/".length)
- break;
-
- case "theme":
- return editor.$getOption("theme").substr("ace/theme/".length)
- break;
-
- case "keybindings":
- var value = editor.getKeyboardHandler()
- switch (value && value.$id) {
- case "ace/keyboard/vim":
- return "vim";
- case "ace/keyboard/emacs":
- return "emacs";
- default:
- return "ace";
- }
- break;
-
- default:
- return editor.$getOption(key);
- }
- };
-
- editor.setOptions(options);
- return editor;
-}
-
-function setupSettingPanel(settingDiv, settingOpener, editor) {
- var BOOL = null;
-
- var desc = {
- mode: "Mode:",
- wrap: "Soft Wrap:",
- theme: "Theme:",
- fontSize: "Font Size:",
- showGutter: "Display Gutter:",
- keybindings: "Keyboard",
- showPrintMargin: "Show Print Margin:",
- useSoftTabs: "Use Soft Tabs:",
- showInvisibles: "Show Invisibles"
- };
-
- var optionValues = {
- mode: {
- text: "Plain",
- javascript: "JavaScript",
- xml: "XML",
- html: "HTML",
- css: "CSS",
- scss: "SCSS",
- python: "Python",
- php: "PHP",
- java: "Java",
- ruby: "Ruby",
- c_cpp: "C/C++",
- coffee: "CoffeeScript",
- json: "json",
- perl: "Perl",
- clojure: "Clojure",
- ocaml: "OCaml",
- csharp: "C#",
- haxe: "haXe",
- svg: "SVG",
- textile: "Textile",
- groovy: "Groovy",
- liquid: "Liquid",
- Scala: "Scala"
- },
- theme: {
- clouds: "Clouds",
- clouds_midnight: "Clouds Midnight",
- cobalt: "Cobalt",
- crimson_editor: "Crimson Editor",
- dawn: "Dawn",
- eclipse: "Eclipse",
- idle_fingers: "Idle Fingers",
- kr_theme: "Kr Theme",
- merbivore: "Merbivore",
- merbivore_soft: "Merbivore Soft",
- mono_industrial: "Mono Industrial",
- monokai: "Monokai",
- pastel_on_dark: "Pastel On Dark",
- solarized_dark: "Solarized Dark",
- solarized_light: "Solarized Light",
- textmate: "Textmate",
- twilight: "Twilight",
- vibrant_ink: "Vibrant Ink"
- },
- showGutter: BOOL,
- fontSize: {
- "10px": "10px",
- "11px": "11px",
- "12px": "12px",
- "14px": "14px",
- "16px": "16px"
- },
- wrap: {
- off: "Off",
- 40: "40",
- 80: "80",
- free: "Free"
- },
- keybindings: {
- ace: "ace",
- vim: "vim",
- emacs: "emacs"
- },
- showPrintMargin: BOOL,
- useSoftTabs: BOOL,
- showInvisibles: BOOL
- };
-
- var table = [];
- table.push("
Setting | Value |
");
-
- function renderOption(builder, option, obj, cValue) {
- if (!obj) {
- builder.push(
- ""
- );
- return;
- }
- builder.push("");
- }
-
- for (var option in exports.defaultOptions) {
- table.push("", desc[option], " | ");
- table.push("");
- renderOption(table, option, optionValues[option], editor.getOption(option));
- table.push(" |
");
- }
- table.push("
");
- settingDiv.innerHTML = table.join("");
-
- var onChange = function(e) {
- var select = e.currentTarget;
- editor.setOption(select.title, select.value);
- };
- var onClick = function(e) {
- var cb = e.currentTarget;
- editor.setOption(cb.title, cb.checked);
- };
- var selects = settingDiv.getElementsByTagName("select");
- for (var i = 0; i < selects.length; i++)
- selects[i].onchange = onChange;
- var cbs = settingDiv.getElementsByTagName("input");
- for (var i = 0; i < cbs.length; i++)
- cbs[i].onclick = onClick;
-
-
- var button = document.createElement("input");
- button.type = "button";
- button.value = "Hide";
- event.addListener(button, "click", function() {
- editor.setDisplaySettings(false);
- });
- settingDiv.appendChild(button);
- settingDiv.hideButton = button;
-}
-exports.defaultOptions = {
- mode: "javascript",
- theme: "textmate",
- wrap: "off",
- fontSize: "12px",
- showGutter: "false",
- keybindings: "ace",
- showPrintMargin: "false",
- useSoftTabs: "true",
- showInvisibles: "false"
-};
-
-});
- (function() {
- ace.require(["ace/ext/textarea"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-themelist.js b/icestudio/lib/ace-builds/src-noconflict/ext-themelist.js
deleted file mode 100644
index 099795655..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-themelist.js
+++ /dev/null
@@ -1,60 +0,0 @@
-ace.define("ace/ext/themelist",["require","exports","module","ace/lib/fixoldbrowsers"], function(require, exports, module) {
-"use strict";
-require("ace/lib/fixoldbrowsers");
-
-var themeData = [
- ["Chrome" ],
- ["Clouds" ],
- ["Crimson Editor" ],
- ["Dawn" ],
- ["Dreamweaver" ],
- ["Eclipse" ],
- ["GitHub" ],
- ["IPlastic" ],
- ["Solarized Light"],
- ["TextMate" ],
- ["Tomorrow" ],
- ["XCode" ],
- ["Kuroir"],
- ["KatzenMilch"],
- ["SQL Server" ,"sqlserver" , "light"],
- ["Ambiance" ,"ambiance" , "dark"],
- ["Chaos" ,"chaos" , "dark"],
- ["Clouds Midnight" ,"clouds_midnight" , "dark"],
- ["Cobalt" ,"cobalt" , "dark"],
- ["idle Fingers" ,"idle_fingers" , "dark"],
- ["krTheme" ,"kr_theme" , "dark"],
- ["Merbivore" ,"merbivore" , "dark"],
- ["Merbivore Soft" ,"merbivore_soft" , "dark"],
- ["Mono Industrial" ,"mono_industrial" , "dark"],
- ["Monokai" ,"monokai" , "dark"],
- ["Pastel on dark" ,"pastel_on_dark" , "dark"],
- ["Solarized Dark" ,"solarized_dark" , "dark"],
- ["Terminal" ,"terminal" , "dark"],
- ["Tomorrow Night" ,"tomorrow_night" , "dark"],
- ["Tomorrow Night Blue" ,"tomorrow_night_blue" , "dark"],
- ["Tomorrow Night Bright","tomorrow_night_bright" , "dark"],
- ["Tomorrow Night 80s" ,"tomorrow_night_eighties" , "dark"],
- ["Twilight" ,"twilight" , "dark"],
- ["Vibrant Ink" ,"vibrant_ink" , "dark"]
-];
-
-
-exports.themesByName = {};
-exports.themes = themeData.map(function(data) {
- var name = data[1] || data[0].replace(/ /g, "_").toLowerCase();
- var theme = {
- caption: data[0],
- theme: "ace/theme/" + name,
- isDark: data[2] == "dark",
- name: name
- };
- exports.themesByName[name] = theme;
- return theme;
-});
-
-});
- (function() {
- ace.require(["ace/ext/themelist"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/ext-whitespace.js b/icestudio/lib/ace-builds/src-noconflict/ext-whitespace.js
deleted file mode 100644
index 22d6bd685..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/ext-whitespace.js
+++ /dev/null
@@ -1,185 +0,0 @@
-ace.define("ace/ext/whitespace",["require","exports","module","ace/lib/lang"], function(require, exports, module) {
-"use strict";
-
-var lang = require("../lib/lang");
-exports.$detectIndentation = function(lines, fallback) {
- var stats = [];
- var changes = [];
- var tabIndents = 0;
- var prevSpaces = 0;
- var max = Math.min(lines.length, 1000);
- for (var i = 0; i < max; i++) {
- var line = lines[i];
- if (!/^\s*[^*+\-\s]/.test(line))
- continue;
-
- if (line[0] == "\t") {
- tabIndents++;
- prevSpaces = -Number.MAX_VALUE;
- } else {
- var spaces = line.match(/^ */)[0].length;
- if (spaces && line[spaces] != "\t") {
- var diff = spaces - prevSpaces;
- if (diff > 0 && !(prevSpaces%diff) && !(spaces%diff))
- changes[diff] = (changes[diff] || 0) + 1;
-
- stats[spaces] = (stats[spaces] || 0) + 1;
- }
- prevSpaces = spaces;
- }
- while (i < max && line[line.length - 1] == "\\")
- line = lines[i++];
- }
-
- function getScore(indent) {
- var score = 0;
- for (var i = indent; i < stats.length; i += indent)
- score += stats[i] || 0;
- return score;
- }
-
- var changesTotal = changes.reduce(function(a,b){return a+b}, 0);
-
- var first = {score: 0, length: 0};
- var spaceIndents = 0;
- for (var i = 1; i < 12; i++) {
- var score = getScore(i);
- if (i == 1) {
- spaceIndents = score;
- score = stats[1] ? 0.9 : 0.8;
- if (!stats.length)
- score = 0;
- } else
- score /= spaceIndents;
-
- if (changes[i])
- score += changes[i] / changesTotal;
-
- if (score > first.score)
- first = {score: score, length: i};
- }
-
- if (first.score && first.score > 1.4)
- var tabLength = first.length;
-
- if (tabIndents > spaceIndents + 1) {
- if (tabLength == 1 || spaceIndents < tabIndents / 4 || first.score < 1.8)
- tabLength = undefined;
- return {ch: "\t", length: tabLength};
- }
- if (spaceIndents > tabIndents + 1)
- return {ch: " ", length: tabLength};
-};
-
-exports.detectIndentation = function(session) {
- var lines = session.getLines(0, 1000);
- var indent = exports.$detectIndentation(lines) || {};
-
- if (indent.ch)
- session.setUseSoftTabs(indent.ch == " ");
-
- if (indent.length)
- session.setTabSize(indent.length);
- return indent;
-};
-
-exports.trimTrailingSpace = function(session, trimEmpty) {
- var doc = session.getDocument();
- var lines = doc.getAllLines();
-
- var min = trimEmpty ? -1 : 0;
-
- for (var i = 0, l=lines.length; i < l; i++) {
- var line = lines[i];
- var index = line.search(/\s+$/);
-
- if (index > min)
- doc.removeInLine(i, index, line.length);
- }
-};
-
-exports.convertIndentation = function(session, ch, len) {
- var oldCh = session.getTabString()[0];
- var oldLen = session.getTabSize();
- if (!len) len = oldLen;
- if (!ch) ch = oldCh;
-
- var tab = ch == "\t" ? ch: lang.stringRepeat(ch, len);
-
- var doc = session.doc;
- var lines = doc.getAllLines();
-
- var cache = {};
- var spaceCache = {};
- for (var i = 0, l=lines.length; i < l; i++) {
- var line = lines[i];
- var match = line.match(/^\s*/)[0];
- if (match) {
- var w = session.$getStringScreenWidth(match)[0];
- var tabCount = Math.floor(w/oldLen);
- var reminder = w%oldLen;
- var toInsert = cache[tabCount] || (cache[tabCount] = lang.stringRepeat(tab, tabCount));
- toInsert += spaceCache[reminder] || (spaceCache[reminder] = lang.stringRepeat(" ", reminder));
-
- if (toInsert != match) {
- doc.removeInLine(i, 0, match.length);
- doc.insertInLine({row: i, column: 0}, toInsert);
- }
- }
- }
- session.setTabSize(len);
- session.setUseSoftTabs(ch == " ");
-};
-
-exports.$parseStringArg = function(text) {
- var indent = {};
- if (/t/.test(text))
- indent.ch = "\t";
- else if (/s/.test(text))
- indent.ch = " ";
- var m = text.match(/\d+/);
- if (m)
- indent.length = parseInt(m[0], 10);
- return indent;
-};
-
-exports.$parseArg = function(arg) {
- if (!arg)
- return {};
- if (typeof arg == "string")
- return exports.$parseStringArg(arg);
- if (typeof arg.text == "string")
- return exports.$parseStringArg(arg.text);
- return arg;
-};
-
-exports.commands = [{
- name: "detectIndentation",
- exec: function(editor) {
- exports.detectIndentation(editor.session);
- }
-}, {
- name: "trimTrailingSpace",
- exec: function(editor) {
- exports.trimTrailingSpace(editor.session);
- }
-}, {
- name: "convertIndentation",
- exec: function(editor, arg) {
- var indent = exports.$parseArg(arg);
- exports.convertIndentation(editor.session, indent.ch, indent.length);
- }
-}, {
- name: "setIndentation",
- exec: function(editor, arg) {
- var indent = exports.$parseArg(arg);
- indent.length && editor.session.setTabSize(indent.length);
- indent.ch && editor.session.setUseSoftTabs(indent.ch == " ");
- }
-}];
-
-});
- (function() {
- ace.require(["ace/ext/whitespace"], function() {});
- })();
-
\ No newline at end of file
diff --git a/icestudio/lib/ace-builds/src-noconflict/keybinding-emacs.js b/icestudio/lib/ace-builds/src-noconflict/keybinding-emacs.js
deleted file mode 100644
index a6cb038e9..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/keybinding-emacs.js
+++ /dev/null
@@ -1,1181 +0,0 @@
-ace.define("ace/occur",["require","exports","module","ace/lib/oop","ace/range","ace/search","ace/edit_session","ace/search_highlight","ace/lib/dom"], function(require, exports, module) {
-"use strict";
-
-var oop = require("./lib/oop");
-var Range = require("./range").Range;
-var Search = require("./search").Search;
-var EditSession = require("./edit_session").EditSession;
-var SearchHighlight = require("./search_highlight").SearchHighlight;
-function Occur() {}
-
-oop.inherits(Occur, Search);
-
-(function() {
- this.enter = function(editor, options) {
- if (!options.needle) return false;
- var pos = editor.getCursorPosition();
- this.displayOccurContent(editor, options);
- var translatedPos = this.originalToOccurPosition(editor.session, pos);
- editor.moveCursorToPosition(translatedPos);
- return true;
- }
- this.exit = function(editor, options) {
- var pos = options.translatePosition && editor.getCursorPosition();
- var translatedPos = pos && this.occurToOriginalPosition(editor.session, pos);
- this.displayOriginalContent(editor);
- if (translatedPos)
- editor.moveCursorToPosition(translatedPos);
- return true;
- }
-
- this.highlight = function(sess, regexp) {
- var hl = sess.$occurHighlight = sess.$occurHighlight || sess.addDynamicMarker(
- new SearchHighlight(null, "ace_occur-highlight", "text"));
- hl.setRegexp(regexp);
- sess._emit("changeBackMarker"); // force highlight layer redraw
- }
-
- this.displayOccurContent = function(editor, options) {
- this.$originalSession = editor.session;
- var found = this.matchingLines(editor.session, options);
- var lines = found.map(function(foundLine) { return foundLine.content; });
- var occurSession = new EditSession(lines.join('\n'));
- occurSession.$occur = this;
- occurSession.$occurMatchingLines = found;
- editor.setSession(occurSession);
- this.$useEmacsStyleLineStart = this.$originalSession.$useEmacsStyleLineStart;
- occurSession.$useEmacsStyleLineStart = this.$useEmacsStyleLineStart;
- this.highlight(occurSession, options.re);
- occurSession._emit('changeBackMarker');
- }
-
- this.displayOriginalContent = function(editor) {
- editor.setSession(this.$originalSession);
- this.$originalSession.$useEmacsStyleLineStart = this.$useEmacsStyleLineStart;
- }
- this.originalToOccurPosition = function(session, pos) {
- var lines = session.$occurMatchingLines;
- var nullPos = {row: 0, column: 0};
- if (!lines) return nullPos;
- for (var i = 0; i < lines.length; i++) {
- if (lines[i].row === pos.row)
- return {row: i, column: pos.column};
- }
- return nullPos;
- }
- this.occurToOriginalPosition = function(session, pos) {
- var lines = session.$occurMatchingLines;
- if (!lines || !lines[pos.row])
- return pos;
- return {row: lines[pos.row].row, column: pos.column};
- }
-
- this.matchingLines = function(session, options) {
- options = oop.mixin({}, options);
- if (!session || !options.needle) return [];
- var search = new Search();
- search.set(options);
- return search.findAll(session).reduce(function(lines, range) {
- var row = range.start.row;
- var last = lines[lines.length-1];
- return last && last.row === row ?
- lines :
- lines.concat({row: row, content: session.getLine(row)});
- }, []);
- }
-
-}).call(Occur.prototype);
-
-var dom = require('./lib/dom');
-dom.importCssString(".ace_occur-highlight {\n\
- border-radius: 4px;\n\
- background-color: rgba(87, 255, 8, 0.25);\n\
- position: absolute;\n\
- z-index: 4;\n\
- -moz-box-sizing: border-box;\n\
- -webkit-box-sizing: border-box;\n\
- box-sizing: border-box;\n\
- box-shadow: 0 0 4px rgb(91, 255, 50);\n\
-}\n\
-.ace_dark .ace_occur-highlight {\n\
- background-color: rgb(80, 140, 85);\n\
- box-shadow: 0 0 4px rgb(60, 120, 70);\n\
-}\n", "incremental-occur-highlighting");
-
-exports.Occur = Occur;
-
-});
-
-ace.define("ace/commands/occur_commands",["require","exports","module","ace/config","ace/occur","ace/keyboard/hash_handler","ace/lib/oop"], function(require, exports, module) {
-
-var config = require("../config"),
- Occur = require("../occur").Occur;
-var occurStartCommand = {
- name: "occur",
- exec: function(editor, options) {
- var alreadyInOccur = !!editor.session.$occur;
- var occurSessionActive = new Occur().enter(editor, options);
- if (occurSessionActive && !alreadyInOccur)
- OccurKeyboardHandler.installIn(editor);
- },
- readOnly: true
-};
-
-var occurCommands = [{
- name: "occurexit",
- bindKey: 'esc|Ctrl-G',
- exec: function(editor) {
- var occur = editor.session.$occur;
- if (!occur) return;
- occur.exit(editor, {});
- if (!editor.session.$occur) OccurKeyboardHandler.uninstallFrom(editor);
- },
- readOnly: true
-}, {
- name: "occuraccept",
- bindKey: 'enter',
- exec: function(editor) {
- var occur = editor.session.$occur;
- if (!occur) return;
- occur.exit(editor, {translatePosition: true});
- if (!editor.session.$occur) OccurKeyboardHandler.uninstallFrom(editor);
- },
- readOnly: true
-}];
-
-var HashHandler = require("../keyboard/hash_handler").HashHandler;
-var oop = require("../lib/oop");
-
-
-function OccurKeyboardHandler() {}
-
-oop.inherits(OccurKeyboardHandler, HashHandler);
-
-(function() {
-
- this.isOccurHandler = true;
-
- this.attach = function(editor) {
- HashHandler.call(this, occurCommands, editor.commands.platform);
- this.$editor = editor;
- }
-
- var handleKeyboard$super = this.handleKeyboard;
- this.handleKeyboard = function(data, hashId, key, keyCode) {
- var cmd = handleKeyboard$super.call(this, data, hashId, key, keyCode);
- return (cmd && cmd.command) ? cmd : undefined;
- }
-
-}).call(OccurKeyboardHandler.prototype);
-
-OccurKeyboardHandler.installIn = function(editor) {
- var handler = new this();
- editor.keyBinding.addKeyboardHandler(handler);
- editor.commands.addCommands(occurCommands);
-}
-
-OccurKeyboardHandler.uninstallFrom = function(editor) {
- editor.commands.removeCommands(occurCommands);
- var handler = editor.getKeyboardHandler();
- if (handler.isOccurHandler)
- editor.keyBinding.removeKeyboardHandler(handler);
-}
-
-exports.occurStartCommand = occurStartCommand;
-
-});
-
-ace.define("ace/commands/incremental_search_commands",["require","exports","module","ace/config","ace/lib/oop","ace/keyboard/hash_handler","ace/commands/occur_commands"], function(require, exports, module) {
-
-var config = require("../config");
-var oop = require("../lib/oop");
-var HashHandler = require("../keyboard/hash_handler").HashHandler;
-var occurStartCommand = require("./occur_commands").occurStartCommand;
-exports.iSearchStartCommands = [{
- name: "iSearch",
- bindKey: {win: "Ctrl-F", mac: "Command-F"},
- exec: function(editor, options) {
- config.loadModule(["core", "ace/incremental_search"], function(e) {
- var iSearch = e.iSearch = e.iSearch || new e.IncrementalSearch();
- iSearch.activate(editor, options.backwards);
- if (options.jumpToFirstMatch) iSearch.next(options);
- });
- },
- readOnly: true
-}, {
- name: "iSearchBackwards",
- exec: function(editor, jumpToNext) { editor.execCommand('iSearch', {backwards: true}); },
- readOnly: true
-}, {
- name: "iSearchAndGo",
- bindKey: {win: "Ctrl-K", mac: "Command-G"},
- exec: function(editor, jumpToNext) { editor.execCommand('iSearch', {jumpToFirstMatch: true, useCurrentOrPrevSearch: true}); },
- readOnly: true
-}, {
- name: "iSearchBackwardsAndGo",
- bindKey: {win: "Ctrl-Shift-K", mac: "Command-Shift-G"},
- exec: function(editor) { editor.execCommand('iSearch', {jumpToFirstMatch: true, backwards: true, useCurrentOrPrevSearch: true}); },
- readOnly: true
-}];
-exports.iSearchCommands = [{
- name: "restartSearch",
- bindKey: {win: "Ctrl-F", mac: "Command-F"},
- exec: function(iSearch) {
- iSearch.cancelSearch(true);
- }
-}, {
- name: "searchForward",
- bindKey: {win: "Ctrl-S|Ctrl-K", mac: "Ctrl-S|Command-G"},
- exec: function(iSearch, options) {
- options.useCurrentOrPrevSearch = true;
- iSearch.next(options);
- }
-}, {
- name: "searchBackward",
- bindKey: {win: "Ctrl-R|Ctrl-Shift-K", mac: "Ctrl-R|Command-Shift-G"},
- exec: function(iSearch, options) {
- options.useCurrentOrPrevSearch = true;
- options.backwards = true;
- iSearch.next(options);
- }
-}, {
- name: "extendSearchTerm",
- exec: function(iSearch, string) {
- iSearch.addString(string);
- }
-}, {
- name: "extendSearchTermSpace",
- bindKey: "space",
- exec: function(iSearch) { iSearch.addString(' '); }
-}, {
- name: "shrinkSearchTerm",
- bindKey: "backspace",
- exec: function(iSearch) {
- iSearch.removeChar();
- }
-}, {
- name: 'confirmSearch',
- bindKey: 'return',
- exec: function(iSearch) { iSearch.deactivate(); }
-}, {
- name: 'cancelSearch',
- bindKey: 'esc|Ctrl-G',
- exec: function(iSearch) { iSearch.deactivate(true); }
-}, {
- name: 'occurisearch',
- bindKey: 'Ctrl-O',
- exec: function(iSearch) {
- var options = oop.mixin({}, iSearch.$options);
- iSearch.deactivate();
- occurStartCommand.exec(iSearch.$editor, options);
- }
-}, {
- name: "yankNextWord",
- bindKey: "Ctrl-w",
- exec: function(iSearch) {
- var ed = iSearch.$editor,
- range = ed.selection.getRangeOfMovements(function(sel) { sel.moveCursorWordRight(); }),
- string = ed.session.getTextRange(range);
- iSearch.addString(string);
- }
-}, {
- name: "yankNextChar",
- bindKey: "Ctrl-Alt-y",
- exec: function(iSearch) {
- var ed = iSearch.$editor,
- range = ed.selection.getRangeOfMovements(function(sel) { sel.moveCursorRight(); }),
- string = ed.session.getTextRange(range);
- iSearch.addString(string);
- }
-}, {
- name: 'recenterTopBottom',
- bindKey: 'Ctrl-l',
- exec: function(iSearch) { iSearch.$editor.execCommand('recenterTopBottom'); }
-}, {
- name: 'selectAllMatches',
- bindKey: 'Ctrl-space',
- exec: function(iSearch) {
- var ed = iSearch.$editor,
- hl = ed.session.$isearchHighlight,
- ranges = hl && hl.cache ? hl.cache
- .reduce(function(ranges, ea) {
- return ranges.concat(ea ? ea : []); }, []) : [];
- iSearch.deactivate(false);
- ranges.forEach(ed.selection.addRange.bind(ed.selection));
- }
-}, {
- name: 'searchAsRegExp',
- bindKey: 'Alt-r',
- exec: function(iSearch) {
- iSearch.convertNeedleToRegExp();
- }
-}].map(function(cmd) {
- cmd.readOnly = true;
- cmd.isIncrementalSearchCommand = true;
- cmd.scrollIntoView = "animate-cursor";
- return cmd;
-});
-
-function IncrementalSearchKeyboardHandler(iSearch) {
- this.$iSearch = iSearch;
-}
-
-oop.inherits(IncrementalSearchKeyboardHandler, HashHandler);
-
-(function() {
-
- this.attach = function(editor) {
- var iSearch = this.$iSearch;
- HashHandler.call(this, exports.iSearchCommands, editor.commands.platform);
- this.$commandExecHandler = editor.commands.addEventListener('exec', function(e) {
- if (!e.command.isIncrementalSearchCommand)
- return iSearch.deactivate();
- e.stopPropagation();
- e.preventDefault();
- var scrollTop = editor.session.getScrollTop();
- var result = e.command.exec(iSearch, e.args || {});
- editor.renderer.scrollCursorIntoView(null, 0.5);
- editor.renderer.animateScrolling(scrollTop);
- return result;
- });
- };
-
- this.detach = function(editor) {
- if (!this.$commandExecHandler) return;
- editor.commands.removeEventListener('exec', this.$commandExecHandler);
- delete this.$commandExecHandler;
- };
-
- var handleKeyboard$super = this.handleKeyboard;
- this.handleKeyboard = function(data, hashId, key, keyCode) {
- if (((hashId === 1/*ctrl*/ || hashId === 8/*command*/) && key === 'v')
- || (hashId === 1/*ctrl*/ && key === 'y')) return null;
- var cmd = handleKeyboard$super.call(this, data, hashId, key, keyCode);
- if (cmd.command) { return cmd; }
- if (hashId == -1) {
- var extendCmd = this.commands.extendSearchTerm;
- if (extendCmd) { return {command: extendCmd, args: key}; }
- }
- return false;
- };
-
-}).call(IncrementalSearchKeyboardHandler.prototype);
-
-
-exports.IncrementalSearchKeyboardHandler = IncrementalSearchKeyboardHandler;
-
-});
-
-ace.define("ace/incremental_search",["require","exports","module","ace/lib/oop","ace/range","ace/search","ace/search_highlight","ace/commands/incremental_search_commands","ace/lib/dom","ace/commands/command_manager","ace/editor","ace/config"], function(require, exports, module) {
-"use strict";
-
-var oop = require("./lib/oop");
-var Range = require("./range").Range;
-var Search = require("./search").Search;
-var SearchHighlight = require("./search_highlight").SearchHighlight;
-var iSearchCommandModule = require("./commands/incremental_search_commands");
-var ISearchKbd = iSearchCommandModule.IncrementalSearchKeyboardHandler;
-function IncrementalSearch() {
- this.$options = {wrap: false, skipCurrent: false};
- this.$keyboardHandler = new ISearchKbd(this);
-}
-
-oop.inherits(IncrementalSearch, Search);
-
-function isRegExp(obj) {
- return obj instanceof RegExp;
-}
-
-function regExpToObject(re) {
- var string = String(re),
- start = string.indexOf('/'),
- flagStart = string.lastIndexOf('/');
- return {
- expression: string.slice(start+1, flagStart),
- flags: string.slice(flagStart+1)
- }
-}
-
-function stringToRegExp(string, flags) {
- try {
- return new RegExp(string, flags);
- } catch (e) { return string; }
-}
-
-function objectToRegExp(obj) {
- return stringToRegExp(obj.expression, obj.flags);
-}
-
-(function() {
-
- this.activate = function(ed, backwards) {
- this.$editor = ed;
- this.$startPos = this.$currentPos = ed.getCursorPosition();
- this.$options.needle = '';
- this.$options.backwards = backwards;
- ed.keyBinding.addKeyboardHandler(this.$keyboardHandler);
- this.$originalEditorOnPaste = ed.onPaste; ed.onPaste = this.onPaste.bind(this);
- this.$mousedownHandler = ed.addEventListener('mousedown', this.onMouseDown.bind(this));
- this.selectionFix(ed);
- this.statusMessage(true);
- };
-
- this.deactivate = function(reset) {
- this.cancelSearch(reset);
- var ed = this.$editor;
- ed.keyBinding.removeKeyboardHandler(this.$keyboardHandler);
- if (this.$mousedownHandler) {
- ed.removeEventListener('mousedown', this.$mousedownHandler);
- delete this.$mousedownHandler;
- }
- ed.onPaste = this.$originalEditorOnPaste;
- this.message('');
- };
-
- this.selectionFix = function(editor) {
- if (editor.selection.isEmpty() && !editor.session.$emacsMark) {
- editor.clearSelection();
- }
- };
-
- this.highlight = function(regexp) {
- var sess = this.$editor.session,
- hl = sess.$isearchHighlight = sess.$isearchHighlight || sess.addDynamicMarker(
- new SearchHighlight(null, "ace_isearch-result", "text"));
- hl.setRegexp(regexp);
- sess._emit("changeBackMarker"); // force highlight layer redraw
- };
-
- this.cancelSearch = function(reset) {
- var e = this.$editor;
- this.$prevNeedle = this.$options.needle;
- this.$options.needle = '';
- if (reset) {
- e.moveCursorToPosition(this.$startPos);
- this.$currentPos = this.$startPos;
- } else {
- e.pushEmacsMark && e.pushEmacsMark(this.$startPos, false);
- }
- this.highlight(null);
- return Range.fromPoints(this.$currentPos, this.$currentPos);
- };
-
- this.highlightAndFindWithNeedle = function(moveToNext, needleUpdateFunc) {
- if (!this.$editor) return null;
- var options = this.$options;
- if (needleUpdateFunc) {
- options.needle = needleUpdateFunc.call(this, options.needle || '') || '';
- }
- if (options.needle.length === 0) {
- this.statusMessage(true);
- return this.cancelSearch(true);
- }
- options.start = this.$currentPos;
- var session = this.$editor.session,
- found = this.find(session),
- shouldSelect = this.$editor.emacsMark ?
- !!this.$editor.emacsMark() : !this.$editor.selection.isEmpty();
- if (found) {
- if (options.backwards) found = Range.fromPoints(found.end, found.start);
- this.$editor.selection.setRange(Range.fromPoints(shouldSelect ? this.$startPos : found.end, found.end));
- if (moveToNext) this.$currentPos = found.end;
- this.highlight(options.re);
- }
-
- this.statusMessage(found);
-
- return found;
- };
-
- this.addString = function(s) {
- return this.highlightAndFindWithNeedle(false, function(needle) {
- if (!isRegExp(needle))
- return needle + s;
- var reObj = regExpToObject(needle);
- reObj.expression += s;
- return objectToRegExp(reObj);
- });
- };
-
- this.removeChar = function(c) {
- return this.highlightAndFindWithNeedle(false, function(needle) {
- if (!isRegExp(needle))
- return needle.substring(0, needle.length-1);
- var reObj = regExpToObject(needle);
- reObj.expression = reObj.expression.substring(0, reObj.expression.length-1);
- return objectToRegExp(reObj);
- });
- };
-
- this.next = function(options) {
- options = options || {};
- this.$options.backwards = !!options.backwards;
- this.$currentPos = this.$editor.getCursorPosition();
- return this.highlightAndFindWithNeedle(true, function(needle) {
- return options.useCurrentOrPrevSearch && needle.length === 0 ?
- this.$prevNeedle || '' : needle;
- });
- };
-
- this.onMouseDown = function(evt) {
- this.deactivate();
- return true;
- };
-
- this.onPaste = function(text) {
- this.addString(text);
- };
-
- this.convertNeedleToRegExp = function() {
- return this.highlightAndFindWithNeedle(false, function(needle) {
- return isRegExp(needle) ? needle : stringToRegExp(needle, 'ig');
- });
- };
-
- this.convertNeedleToString = function() {
- return this.highlightAndFindWithNeedle(false, function(needle) {
- return isRegExp(needle) ? regExpToObject(needle).expression : needle;
- });
- };
-
- this.statusMessage = function(found) {
- var options = this.$options, msg = '';
- msg += options.backwards ? 'reverse-' : '';
- msg += 'isearch: ' + options.needle;
- msg += found ? '' : ' (not found)';
- this.message(msg);
- };
-
- this.message = function(msg) {
- if (this.$editor.showCommandLine) {
- this.$editor.showCommandLine(msg);
- this.$editor.focus();
- } else {
- console.log(msg);
- }
- };
-
-}).call(IncrementalSearch.prototype);
-
-
-exports.IncrementalSearch = IncrementalSearch;
-
-var dom = require('./lib/dom');
-dom.importCssString && dom.importCssString("\
-.ace_marker-layer .ace_isearch-result {\
- position: absolute;\
- z-index: 6;\
- -moz-box-sizing: border-box;\
- -webkit-box-sizing: border-box;\
- box-sizing: border-box;\
-}\
-div.ace_isearch-result {\
- border-radius: 4px;\
- background-color: rgba(255, 200, 0, 0.5);\
- box-shadow: 0 0 4px rgb(255, 200, 0);\
-}\
-.ace_dark div.ace_isearch-result {\
- background-color: rgb(100, 110, 160);\
- box-shadow: 0 0 4px rgb(80, 90, 140);\
-}", "incremental-search-highlighting");
-var commands = require("./commands/command_manager");
-(function() {
- this.setupIncrementalSearch = function(editor, val) {
- if (this.usesIncrementalSearch == val) return;
- this.usesIncrementalSearch = val;
- var iSearchCommands = iSearchCommandModule.iSearchStartCommands;
- var method = val ? 'addCommands' : 'removeCommands';
- this[method](iSearchCommands);
- };
-}).call(commands.CommandManager.prototype);
-var Editor = require("./editor").Editor;
-require("./config").defineOptions(Editor.prototype, "editor", {
- useIncrementalSearch: {
- set: function(val) {
- this.keyBinding.$handlers.forEach(function(handler) {
- if (handler.setupIncrementalSearch) {
- handler.setupIncrementalSearch(this, val);
- }
- });
- this._emit('incrementalSearchSettingChanged', {isEnabled: val});
- }
- }
-});
-
-});
-
-ace.define("ace/keyboard/emacs",["require","exports","module","ace/lib/dom","ace/incremental_search","ace/commands/incremental_search_commands","ace/keyboard/hash_handler","ace/lib/keys"], function(require, exports, module) {
-"use strict";
-
-var dom = require("../lib/dom");
-require("../incremental_search");
-var iSearchCommandModule = require("../commands/incremental_search_commands");
-
-
-var screenToTextBlockCoordinates = function(x, y) {
- var canvasPos = this.scroller.getBoundingClientRect();
-
- var col = Math.floor(
- (x + this.scrollLeft - canvasPos.left - this.$padding) / this.characterWidth
- );
- var row = Math.floor(
- (y + this.scrollTop - canvasPos.top) / this.lineHeight
- );
-
- return this.session.screenToDocumentPosition(row, col);
-};
-
-var HashHandler = require("./hash_handler").HashHandler;
-exports.handler = new HashHandler();
-
-exports.handler.isEmacs = true;
-exports.handler.$id = "ace/keyboard/emacs";
-
-var initialized = false;
-var $formerLongWords;
-var $formerLineStart;
-
-exports.handler.attach = function(editor) {
- if (!initialized) {
- initialized = true;
- dom.importCssString('\
- .emacs-mode .ace_cursor{\
- border: 1px rgba(50,250,50,0.8) solid!important;\
- -moz-box-sizing: border-box!important;\
- -webkit-box-sizing: border-box!important;\
- box-sizing: border-box!important;\
- background-color: rgba(0,250,0,0.9);\
- opacity: 0.5;\
- }\
- .emacs-mode .ace_hidden-cursors .ace_cursor{\
- opacity: 1;\
- background-color: transparent;\
- }\
- .emacs-mode .ace_overwrite-cursors .ace_cursor {\
- opacity: 1;\
- background-color: transparent;\
- border-width: 0 0 2px 2px !important;\
- }\
- .emacs-mode .ace_text-layer {\
- z-index: 4\
- }\
- .emacs-mode .ace_cursor-layer {\
- z-index: 2\
- }', 'emacsMode'
- );
- }
- $formerLongWords = editor.session.$selectLongWords;
- editor.session.$selectLongWords = true;
- $formerLineStart = editor.session.$useEmacsStyleLineStart;
- editor.session.$useEmacsStyleLineStart = true;
-
- editor.session.$emacsMark = null; // the active mark
- editor.session.$emacsMarkRing = editor.session.$emacsMarkRing || [];
-
- editor.emacsMark = function() {
- return this.session.$emacsMark;
- };
-
- editor.setEmacsMark = function(p) {
- this.session.$emacsMark = p;
- };
-
- editor.pushEmacsMark = function(p, activate) {
- var prevMark = this.session.$emacsMark;
- if (prevMark)
- this.session.$emacsMarkRing.push(prevMark);
- if (!p || activate) this.setEmacsMark(p);
- else this.session.$emacsMarkRing.push(p);
- };
-
- editor.popEmacsMark = function() {
- var mark = this.emacsMark();
- if (mark) { this.setEmacsMark(null); return mark; }
- return this.session.$emacsMarkRing.pop();
- };
-
- editor.getLastEmacsMark = function(p) {
- return this.session.$emacsMark || this.session.$emacsMarkRing.slice(-1)[0];
- };
-
- editor.emacsMarkForSelection = function(replacement) {
- var sel = this.selection,
- multiRangeLength = this.multiSelect ?
- this.multiSelect.getAllRanges().length : 1,
- selIndex = sel.index || 0,
- markRing = this.session.$emacsMarkRing,
- markIndex = markRing.length - (multiRangeLength - selIndex),
- lastMark = markRing[markIndex] || sel.anchor;
- if (replacement) {
- markRing.splice(markIndex, 1,
- "row" in replacement && "column" in replacement ?
- replacement : undefined);
- }
- return lastMark;
- }
-
- editor.on("click", $resetMarkMode);
- editor.on("changeSession", $kbSessionChange);
- editor.renderer.screenToTextCoordinates = screenToTextBlockCoordinates;
- editor.setStyle("emacs-mode");
- editor.commands.addCommands(commands);
- exports.handler.platform = editor.commands.platform;
- editor.$emacsModeHandler = this;
- editor.addEventListener('copy', this.onCopy);
- editor.addEventListener('paste', this.onPaste);
-};
-
-exports.handler.detach = function(editor) {
- delete editor.renderer.screenToTextCoordinates;
- editor.session.$selectLongWords = $formerLongWords;
- editor.session.$useEmacsStyleLineStart = $formerLineStart;
- editor.removeEventListener("click", $resetMarkMode);
- editor.removeEventListener("changeSession", $kbSessionChange);
- editor.unsetStyle("emacs-mode");
- editor.commands.removeCommands(commands);
- editor.removeEventListener('copy', this.onCopy);
- editor.removeEventListener('paste', this.onPaste);
- editor.$emacsModeHandler = null;
-};
-
-var $kbSessionChange = function(e) {
- if (e.oldSession) {
- e.oldSession.$selectLongWords = $formerLongWords;
- e.oldSession.$useEmacsStyleLineStart = $formerLineStart;
- }
-
- $formerLongWords = e.session.$selectLongWords;
- e.session.$selectLongWords = true;
- $formerLineStart = e.session.$useEmacsStyleLineStart;
- e.session.$useEmacsStyleLineStart = true;
-
- if (!e.session.hasOwnProperty('$emacsMark'))
- e.session.$emacsMark = null;
- if (!e.session.hasOwnProperty('$emacsMarkRing'))
- e.session.$emacsMarkRing = [];
-};
-
-var $resetMarkMode = function(e) {
- e.editor.session.$emacsMark = null;
-};
-
-var keys = require("../lib/keys").KEY_MODS;
-var eMods = {C: "ctrl", S: "shift", M: "alt", CMD: "command"};
-var combinations = ["C-S-M-CMD",
- "S-M-CMD", "C-M-CMD", "C-S-CMD", "C-S-M",
- "M-CMD", "S-CMD", "S-M", "C-CMD", "C-M", "C-S",
- "CMD", "M", "S", "C"];
-combinations.forEach(function(c) {
- var hashId = 0;
- c.split("-").forEach(function(c) {
- hashId = hashId | keys[eMods[c]];
- });
- eMods[hashId] = c.toLowerCase() + "-";
-});
-
-exports.handler.onCopy = function(e, editor) {
- if (editor.$handlesEmacsOnCopy) return;
- editor.$handlesEmacsOnCopy = true;
- exports.handler.commands.killRingSave.exec(editor);
- editor.$handlesEmacsOnCopy = false;
-};
-
-exports.handler.onPaste = function(e, editor) {
- editor.pushEmacsMark(editor.getCursorPosition());
-};
-
-exports.handler.bindKey = function(key, command) {
- if (typeof key == "object")
- key = key[this.platform];
- if (!key)
- return;
-
- var ckb = this.commandKeyBinding;
- key.split("|").forEach(function(keyPart) {
- keyPart = keyPart.toLowerCase();
- ckb[keyPart] = command;
- var keyParts = keyPart.split(" ").slice(0,-1);
- keyParts.reduce(function(keyMapKeys, keyPart, i) {
- var prefix = keyMapKeys[i-1] ? keyMapKeys[i-1] + ' ' : '';
- return keyMapKeys.concat([prefix + keyPart]);
- }, []).forEach(function(keyPart) {
- if (!ckb[keyPart]) ckb[keyPart] = "null";
- });
- }, this);
-};
-
-exports.handler.getStatusText = function(editor, data) {
- var str = "";
- if (data.count)
- str += data.count;
- if (data.keyChain)
- str += " " + data.keyChain
- return str;
-};
-
-exports.handler.handleKeyboard = function(data, hashId, key, keyCode) {
- if (keyCode === -1) return undefined;
-
- var editor = data.editor;
- editor._signal("changeStatus");
- if (hashId == -1) {
- editor.pushEmacsMark();
- if (data.count) {
- var str = new Array(data.count + 1).join(key);
- data.count = null;
- return {command: "insertstring", args: str};
- }
- }
-
- var modifier = eMods[hashId];
- if (modifier == "c-" || data.count) {
- var count = parseInt(key[key.length - 1]);
- if (typeof count === 'number' && !isNaN(count)) {
- data.count = Math.max(data.count, 0) || 0;
- data.count = 10 * data.count + count;
- return {command: "null"};
- }
- }
- if (modifier) key = modifier + key;
- if (data.keyChain) key = data.keyChain += " " + key;
- var command = this.commandKeyBinding[key];
- data.keyChain = command == "null" ? key : "";
- if (!command) return undefined;
- if (command === "null") return {command: "null"};
-
- if (command === "universalArgument") {
- data.count = -4;
- return {command: "null"};
- }
- var args;
- if (typeof command !== "string") {
- args = command.args;
- if (command.command) command = command.command;
- if (command === "goorselect") {
- command = editor.emacsMark() ? args[1] : args[0];
- args = null;
- }
- }
-
- if (typeof command === "string") {
- if (command === "insertstring" ||
- command === "splitline" ||
- command === "togglecomment") {
- editor.pushEmacsMark();
- }
- command = this.commands[command] || editor.commands.commands[command];
- if (!command) return undefined;
- }
-
- if (!command.readOnly && !command.isYank)
- data.lastCommand = null;
-
- if (!command.readOnly && editor.emacsMark())
- editor.setEmacsMark(null)
-
- if (data.count) {
- var count = data.count;
- data.count = 0;
- if (!command || !command.handlesCount) {
- return {
- args: args,
- command: {
- exec: function(editor, args) {
- for (var i = 0; i < count; i++)
- command.exec(editor, args);
- },
- multiSelectAction: command.multiSelectAction
- }
- };
- } else {
- if (!args) args = {};
- if (typeof args === 'object') args.count = count;
- }
- }
-
- return {command: command, args: args};
-};
-
-exports.emacsKeys = {
- "Up|C-p" : {command: "goorselect", args: ["golineup","selectup"]},
- "Down|C-n" : {command: "goorselect", args: ["golinedown","selectdown"]},
- "Left|C-b" : {command: "goorselect", args: ["gotoleft","selectleft"]},
- "Right|C-f" : {command: "goorselect", args: ["gotoright","selectright"]},
- "C-Left|M-b" : {command: "goorselect", args: ["gotowordleft","selectwordleft"]},
- "C-Right|M-f" : {command: "goorselect", args: ["gotowordright","selectwordright"]},
- "Home|C-a" : {command: "goorselect", args: ["gotolinestart","selecttolinestart"]},
- "End|C-e" : {command: "goorselect", args: ["gotolineend","selecttolineend"]},
- "C-Home|S-M-,": {command: "goorselect", args: ["gotostart","selecttostart"]},
- "C-End|S-M-." : {command: "goorselect", args: ["gotoend","selecttoend"]},
- "S-Up|S-C-p" : "selectup",
- "S-Down|S-C-n" : "selectdown",
- "S-Left|S-C-b" : "selectleft",
- "S-Right|S-C-f" : "selectright",
- "S-C-Left|S-M-b" : "selectwordleft",
- "S-C-Right|S-M-f" : "selectwordright",
- "S-Home|S-C-a" : "selecttolinestart",
- "S-End|S-C-e" : "selecttolineend",
- "S-C-Home" : "selecttostart",
- "S-C-End" : "selecttoend",
-
- "C-l" : "recenterTopBottom",
- "M-s" : "centerselection",
- "M-g": "gotoline",
- "C-x C-p": "selectall",
- "C-Down": {command: "goorselect", args: ["gotopagedown","selectpagedown"]},
- "C-Up": {command: "goorselect", args: ["gotopageup","selectpageup"]},
- "PageDown|C-v": {command: "goorselect", args: ["gotopagedown","selectpagedown"]},
- "PageUp|M-v": {command: "goorselect", args: ["gotopageup","selectpageup"]},
- "S-C-Down": "selectpagedown",
- "S-C-Up": "selectpageup",
-
- "C-s": "iSearch",
- "C-r": "iSearchBackwards",
-
- "M-C-s": "findnext",
- "M-C-r": "findprevious",
- "S-M-5": "replace",
- "Backspace": "backspace",
- "Delete|C-d": "del",
- "Return|C-m": {command: "insertstring", args: "\n"}, // "newline"
- "C-o": "splitline",
-
- "M-d|C-Delete": {command: "killWord", args: "right"},
- "C-Backspace|M-Backspace|M-Delete": {command: "killWord", args: "left"},
- "C-k": "killLine",
-
- "C-y|S-Delete": "yank",
- "M-y": "yankRotate",
- "C-g": "keyboardQuit",
-
- "C-w|C-S-W": "killRegion",
- "M-w": "killRingSave",
- "C-Space": "setMark",
- "C-x C-x": "exchangePointAndMark",
-
- "C-t": "transposeletters",
- "M-u": "touppercase", // Doesn't work
- "M-l": "tolowercase",
- "M-/": "autocomplete", // Doesn't work
- "C-u": "universalArgument",
-
- "M-;": "togglecomment",
-
- "C-/|C-x u|S-C--|C-z": "undo",
- "S-C-/|S-C-x u|C--|S-C-z": "redo", // infinite undo?
- "C-x r": "selectRectangularRegion",
- "M-x": {command: "focusCommandLine", args: "M-x "}
-};
-
-
-exports.handler.bindKeys(exports.emacsKeys);
-
-exports.handler.addCommands({
- recenterTopBottom: function(editor) {
- var renderer = editor.renderer;
- var pos = renderer.$cursorLayer.getPixelPosition();
- var h = renderer.$size.scrollerHeight - renderer.lineHeight;
- var scrollTop = renderer.scrollTop;
- if (Math.abs(pos.top - scrollTop) < 2) {
- scrollTop = pos.top - h;
- } else if (Math.abs(pos.top - scrollTop - h * 0.5) < 2) {
- scrollTop = pos.top;
- } else {
- scrollTop = pos.top - h * 0.5;
- }
- editor.session.setScrollTop(scrollTop);
- },
- selectRectangularRegion: function(editor) {
- editor.multiSelect.toggleBlockSelection();
- },
- setMark: {
- exec: function(editor, args) {
-
- if (args && args.count) {
- if (editor.inMultiSelectMode) editor.forEachSelection(moveToMark);
- else moveToMark();
- moveToMark();
- return;
- }
-
- var mark = editor.emacsMark(),
- ranges = editor.selection.getAllRanges(),
- rangePositions = ranges.map(function(r) { return {row: r.start.row, column: r.start.column}; }),
- transientMarkModeActive = true,
- hasNoSelection = ranges.every(function(range) { return range.isEmpty(); });
- if (transientMarkModeActive && (mark || !hasNoSelection)) {
- if (editor.inMultiSelectMode) editor.forEachSelection({exec: editor.clearSelection.bind(editor)});
- else editor.clearSelection();
- if (mark) editor.pushEmacsMark(null);
- return;
- }
-
- if (!mark) {
- rangePositions.forEach(function(pos) { editor.pushEmacsMark(pos); });
- editor.setEmacsMark(rangePositions[rangePositions.length-1]);
- return;
- }
-
- function moveToMark() {
- var mark = editor.popEmacsMark();
- mark && editor.moveCursorToPosition(mark);
- }
-
- },
- readOnly: true,
- handlesCount: true
- },
- exchangePointAndMark: {
- exec: function exchangePointAndMark$exec(editor, args) {
- var sel = editor.selection;
- if (!args.count && !sel.isEmpty()) { // just invert selection
- sel.setSelectionRange(sel.getRange(), !sel.isBackwards());
- return;
- }
-
- if (args.count) { // replace mark and point
- var pos = {row: sel.lead.row, column: sel.lead.column};
- sel.clearSelection();
- sel.moveCursorToPosition(editor.emacsMarkForSelection(pos));
- } else { // create selection to last mark
- sel.selectToPosition(editor.emacsMarkForSelection());
- }
- },
- readOnly: true,
- handlesCount: true,
- multiSelectAction: "forEach"
- },
- killWord: {
- exec: function(editor, dir) {
- editor.clearSelection();
- if (dir == "left")
- editor.selection.selectWordLeft();
- else
- editor.selection.selectWordRight();
-
- var range = editor.getSelectionRange();
- var text = editor.session.getTextRange(range);
- exports.killRing.add(text);
-
- editor.session.remove(range);
- editor.clearSelection();
- },
- multiSelectAction: "forEach"
- },
- killLine: function(editor) {
- editor.pushEmacsMark(null);
- editor.clearSelection();
- var range = editor.getSelectionRange();
- var line = editor.session.getLine(range.start.row);
- range.end.column = line.length;
- line = line.substr(range.start.column)
-
- var foldLine = editor.session.getFoldLine(range.start.row);
- if (foldLine && range.end.row != foldLine.end.row) {
- range.end.row = foldLine.end.row;
- line = "x";
- }
- if (/^\s*$/.test(line)) {
- range.end.row++;
- line = editor.session.getLine(range.end.row);
- range.end.column = /^\s*$/.test(line) ? line.length : 0;
- }
- var text = editor.session.getTextRange(range);
- if (editor.prevOp.command == this)
- exports.killRing.append(text);
- else
- exports.killRing.add(text);
-
- editor.session.remove(range);
- editor.clearSelection();
- },
- yank: function(editor) {
- editor.onPaste(exports.killRing.get() || '');
- editor.keyBinding.$data.lastCommand = "yank";
- },
- yankRotate: function(editor) {
- if (editor.keyBinding.$data.lastCommand != "yank")
- return;
- editor.undo();
- editor.session.$emacsMarkRing.pop(); // also undo recording mark
- editor.onPaste(exports.killRing.rotate());
- editor.keyBinding.$data.lastCommand = "yank";
- },
- killRegion: {
- exec: function(editor) {
- exports.killRing.add(editor.getCopyText());
- editor.commands.byName.cut.exec(editor);
- editor.setEmacsMark(null);
- },
- readOnly: true,
- multiSelectAction: "forEach"
- },
- killRingSave: {
- exec: function(editor) {
-
- editor.$handlesEmacsOnCopy = true;
- var marks = editor.session.$emacsMarkRing.slice(),
- deselectedMarks = [];
- exports.killRing.add(editor.getCopyText());
-
- setTimeout(function() {
- function deselect() {
- var sel = editor.selection, range = sel.getRange(),
- pos = sel.isBackwards() ? range.end : range.start;
- deselectedMarks.push({row: pos.row, column: pos.column});
- sel.clearSelection();
- }
- editor.$handlesEmacsOnCopy = false;
- if (editor.inMultiSelectMode) editor.forEachSelection({exec: deselect});
- else deselect();
- editor.session.$emacsMarkRing = marks.concat(deselectedMarks.reverse());
- }, 0);
- },
- readOnly: true
- },
- keyboardQuit: function(editor) {
- editor.selection.clearSelection();
- editor.setEmacsMark(null);
- editor.keyBinding.$data.count = null;
- },
- focusCommandLine: function(editor, arg) {
- if (editor.showCommandLine)
- editor.showCommandLine(arg);
- }
-});
-
-exports.handler.addCommands(iSearchCommandModule.iSearchStartCommands);
-
-var commands = exports.handler.commands;
-commands.yank.isYank = true;
-commands.yankRotate.isYank = true;
-
-exports.killRing = {
- $data: [],
- add: function(str) {
- str && this.$data.push(str);
- if (this.$data.length > 30)
- this.$data.shift();
- },
- append: function(str) {
- var idx = this.$data.length - 1;
- var text = this.$data[idx] || "";
- if (str) text += str;
- if (text) this.$data[idx] = text;
- },
- get: function(n) {
- n = n || 1;
- return this.$data.slice(this.$data.length-n, this.$data.length).reverse().join('\n');
- },
- pop: function() {
- if (this.$data.length > 1)
- this.$data.pop();
- return this.get();
- },
- rotate: function() {
- this.$data.unshift(this.$data.pop());
- return this.get();
- }
-};
-
-});
diff --git a/icestudio/lib/ace-builds/src-noconflict/keybinding-vim.js b/icestudio/lib/ace-builds/src-noconflict/keybinding-vim.js
deleted file mode 100644
index 0c970f5e3..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/keybinding-vim.js
+++ /dev/null
@@ -1,5580 +0,0 @@
-ace.define("ace/keyboard/vim",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/dom","ace/lib/oop","ace/lib/keys","ace/lib/event","ace/search","ace/lib/useragent","ace/search_highlight","ace/commands/multi_select_commands","ace/mode/text","ace/multi_select"], function(require, exports, module) {
- 'use strict';
-
- function log() {
- var d = "";
- function format(p) {
- if (typeof p != "object")
- return p + "";
- if ("line" in p) {
- return p.line + ":" + p.ch;
- }
- if ("anchor" in p) {
- return format(p.anchor) + "->" + format(p.head);
- }
- if (Array.isArray(p))
- return "[" + p.map(function(x) {
- return format(x);
- }) + "]";
- return JSON.stringify(p);
- }
- for (var i = 0; i < arguments.length; i++) {
- var p = arguments[i];
- var f = format(p);
- d += f + " ";
- }
- console.log(d);
- }
- var Range = require("../range").Range;
- var EventEmitter = require("../lib/event_emitter").EventEmitter;
- var dom = require("../lib/dom");
- var oop = require("../lib/oop");
- var KEYS = require("../lib/keys");
- var event = require("../lib/event");
- var Search = require("../search").Search;
- var useragent = require("../lib/useragent");
- var SearchHighlight = require("../search_highlight").SearchHighlight;
- var multiSelectCommands = require("../commands/multi_select_commands");
- var TextModeTokenRe = require("../mode/text").Mode.prototype.tokenRe;
- require("../multi_select");
-
- var CodeMirror = function(ace) {
- this.ace = ace;
- this.state = {};
- this.marks = {};
- this.$uid = 0;
- this.onChange = this.onChange.bind(this);
- this.onSelectionChange = this.onSelectionChange.bind(this);
- this.onBeforeEndOperation = this.onBeforeEndOperation.bind(this);
- this.ace.on('change', this.onChange);
- this.ace.on('changeSelection', this.onSelectionChange);
- this.ace.on('beforeEndOperation', this.onBeforeEndOperation);
- };
- CodeMirror.Pos = function(line, ch) {
- if (!(this instanceof Pos)) return new Pos(line, ch);
- this.line = line; this.ch = ch;
- };
- CodeMirror.defineOption = function(name, val, setter) {};
- CodeMirror.commands = {
- redo: function(cm) { cm.ace.redo(); },
- undo: function(cm) { cm.ace.undo(); },
- newlineAndIndent: function(cm) { cm.ace.insert("\n"); }
- };
- CodeMirror.keyMap = {};
- CodeMirror.addClass = CodeMirror.rmClass =
- CodeMirror.e_stop = function() {};
- CodeMirror.keyName = function(e) {
- if (e.key) return e.key;
- var key = (KEYS[e.keyCode] || "");
- if (key.length == 1) key = key.toUpperCase();
- key = event.getModifierString(e).replace(/(^|-)\w/g, function(m) {
- return m.toUpperCase();
- }) + key;
- return key;
- };
- CodeMirror.keyMap['default'] = function(key) {
- return function(cm) {
- var cmd = cm.ace.commands.commandKeyBinding[key.toLowerCase()];
- return cmd && cm.ace.execCommand(cmd) !== false;
- };
- };
- CodeMirror.lookupKey = function lookupKey(key, map, handle) {
- if (typeof map == "string")
- map = CodeMirror.keyMap[map];
- var found = typeof map == "function" ? map(key) : map[key];
- if (found === false) return "nothing";
- if (found === "...") return "multi";
- if (found != null && handle(found)) return "handled";
-
- if (map.fallthrough) {
- if (!Array.isArray(map.fallthrough))
- return lookupKey(key, map.fallthrough, handle);
- for (var i = 0; i < map.fallthrough.length; i++) {
- var result = lookupKey(key, map.fallthrough[i], handle);
- if (result) return result;
- }
- }
- };
-
- CodeMirror.signal = function(o, name, e) { return o._signal(name, e) };
- CodeMirror.on = event.addListener;
- CodeMirror.off = event.removeListener;
- CodeMirror.isWordChar = function(ch) {
- if (ch < "\x7f") return /^\w$/.test(ch);
- TextModeTokenRe.lastIndex = 0;
- return TextModeTokenRe.test(ch);
- };
-
-(function() {
- oop.implement(CodeMirror.prototype, EventEmitter);
-
- this.destroy = function() {
- this.ace.off('change', this.onChange);
- this.ace.off('changeSelection', this.onSelectionChange);
- this.ace.off('beforeEndOperation', this.onBeforeEndOperation);
- this.removeOverlay();
- };
- this.virtualSelectionMode = function() {
- return this.ace.inVirtualSelectionMode && this.ace.selection.index;
- };
- this.onChange = function(delta) {
- if (delta.action[0] == 'i') {
- var change = { text: delta.lines };
- var curOp = this.curOp = this.curOp || {};
- if (!curOp.changeHandlers)
- curOp.changeHandlers = this._eventRegistry["change"] && this._eventRegistry["change"].slice();
- if (this.virtualSelectionMode()) return;
- if (!curOp.lastChange) {
- curOp.lastChange = curOp.change = change;
- } else {
- curOp.lastChange.next = curOp.lastChange = change;
- }
- }
- this.$updateMarkers(delta);
- };
- this.onSelectionChange = function() {
- var curOp = this.curOp = this.curOp || {};
- if (!curOp.cursorActivityHandlers)
- curOp.cursorActivityHandlers = this._eventRegistry["cursorActivity"] && this._eventRegistry["cursorActivity"].slice();
- this.curOp.cursorActivity = true;
- if (this.ace.inMultiSelectMode) {
- this.ace.keyBinding.removeKeyboardHandler(multiSelectCommands.keyboardHandler);
- }
- };
- this.operation = function(fn, force) {
- if (!force && this.curOp || force && this.curOp && this.curOp.force) {
- return fn();
- }
- if (force || !this.ace.curOp) {
- if (this.curOp)
- this.onBeforeEndOperation();
- }
- if (!this.ace.curOp) {
- var prevOp = this.ace.prevOp;
- this.ace.startOperation({
- command: { name: "vim", scrollIntoView: "cursor" }
- });
- }
- var curOp = this.curOp = this.curOp || {};
- this.curOp.force = force;
- var result = fn();
- if (this.ace.curOp && this.ace.curOp.command.name == "vim") {
- this.ace.endOperation();
- if (!curOp.cursorActivity && !curOp.lastChange && prevOp)
- this.ace.prevOp = prevOp;
- }
- if (force || !this.ace.curOp) {
- if (this.curOp)
- this.onBeforeEndOperation();
- }
- return result;
- };
- this.onBeforeEndOperation = function() {
- var op = this.curOp;
- if (op) {
- if (op.change) { this.signal("change", op.change, op); }
- if (op && op.cursorActivity) { this.signal("cursorActivity", null, op); }
- this.curOp = null;
- }
- };
-
- this.signal = function(eventName, e, handlers) {
- var listeners = handlers ? handlers[eventName + "Handlers"]
- : (this._eventRegistry || {})[eventName];
- if (!listeners)
- return;
- listeners = listeners.slice();
- for (var i=0; i
0) {
- point.row += rowShift;
- point.column += point.row == end.row ? colShift : 0;
- continue;
- }
- if (!isInsert && cmp2 <= 0) {
- point.row = start.row;
- point.column = start.column;
- if (cmp2 === 0)
- point.bias = 1;
- }
- }
- };
- var Marker = function(cm, id, row, column) {
- this.cm = cm;
- this.id = id;
- this.row = row;
- this.column = column;
- cm.marks[this.id] = this;
- };
- Marker.prototype.clear = function() { delete this.cm.marks[this.id] };
- Marker.prototype.find = function() { return toCmPos(this) };
- this.setBookmark = function(cursor, options) {
- var bm = new Marker(this, this.$uid++, cursor.line, cursor.ch);
- if (!options || !options.insertLeft)
- bm.$insertRight = true;
- this.marks[bm.id] = bm;
- return bm;
- };
- this.moveH = function(increment, unit) {
- if (unit == 'char') {
- var sel = this.ace.selection;
- sel.clearSelection();
- sel.moveCursorBy(0, increment);
- }
- };
- this.findPosV = function(start, amount, unit, goalColumn) {
- if (unit == 'page') {
- var renderer = this.ace.renderer;
- var config = renderer.layerConfig;
- amount = amount * Math.floor(config.height / config.lineHeight);
- unit = 'line';
- }
- if (unit == 'line') {
- var screenPos = this.ace.session.documentToScreenPosition(start.line, start.ch);
- if (goalColumn != null)
- screenPos.column = goalColumn;
- screenPos.row += amount;
- screenPos.row = Math.min(Math.max(0, screenPos.row), this.ace.session.getScreenLength() - 1);
- var pos = this.ace.session.screenToDocumentPosition(screenPos.row, screenPos.column);
- return toCmPos(pos);
- } else {
- debugger;
- }
- };
- this.charCoords = function(pos, mode) {
- if (mode == 'div' || !mode) {
- var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch);
- return {left: sc.column, top: sc.row};
- }if (mode == 'local') {
- var renderer = this.ace.renderer;
- var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch);
- var lh = renderer.layerConfig.lineHeight;
- var cw = renderer.layerConfig.characterWidth;
- var top = lh * sc.row;
- return {left: sc.column * cw, top: top, bottom: top + lh};
- }
- };
- this.coordsChar = function(pos, mode) {
- var renderer = this.ace.renderer;
- if (mode == 'local') {
- var row = Math.max(0, Math.floor(pos.top / renderer.lineHeight));
- var col = Math.max(0, Math.floor(pos.left / renderer.characterWidth));
- var ch = renderer.session.screenToDocumentPosition(row, col);
- return toCmPos(ch);
- } else if (mode == 'div') {
- throw "not implemented";
- }
- };
- this.getSearchCursor = function(query, pos, caseFold) {
- var caseSensitive = false;
- var isRegexp = false;
- if (query instanceof RegExp && !query.global) {
- caseSensitive = !query.ignoreCase;
- query = query.source;
- isRegexp = true;
- }
- var search = new Search();
- if (pos.ch == undefined) pos.ch = Number.MAX_VALUE;
- var acePos = {row: pos.line, column: pos.ch};
- var cm = this;
- var last = null;
- return {
- findNext: function() { return this.find(false) },
- findPrevious: function() {return this.find(true) },
- find: function(back) {
- search.setOptions({
- needle: query,
- caseSensitive: caseSensitive,
- wrap: false,
- backwards: back,
- regExp: isRegexp,
- start: last || acePos
- });
- var range = search.find(cm.ace.session);
- if (range && range.isEmpty()) {
- if (cm.getLine(range.start.row).length == range.start.column) {
- search.$options.start = range;
- range = search.find(cm.ace.session);
- }
- }
- last = range;
- return last;
- },
- from: function() { return last && toCmPos(last.start) },
- to: function() { return last && toCmPos(last.end) },
- replace: function(text) {
- if (last) {
- last.end = cm.ace.session.doc.replace(last, text);
- }
- }
- };
- };
- this.scrollTo = function(x, y) {
- var renderer = this.ace.renderer;
- var config = renderer.layerConfig;
- var maxHeight = config.maxHeight;
- maxHeight -= (renderer.$size.scrollerHeight - renderer.lineHeight) * renderer.$scrollPastEnd;
- if (y != null) this.ace.session.setScrollTop(Math.max(0, Math.min(y, maxHeight)));
- if (x != null) this.ace.session.setScrollLeft(Math.max(0, Math.min(x, config.width)));
- };
- this.scrollInfo = function() { return 0; };
- this.scrollIntoView = function(pos, margin) {
- if (pos) {
- var renderer = this.ace.renderer;
- var viewMargin = { "top": 0, "bottom": margin };
- renderer.scrollCursorIntoView(toAcePos(pos),
- (renderer.lineHeight * 2) / renderer.$size.scrollerHeight, viewMargin);
- }
- };
- this.getLine = function(row) { return this.ace.session.getLine(row) };
- this.getRange = function(s, e) {
- return this.ace.session.getTextRange(new Range(s.line, s.ch, e.line, e.ch));
- };
- this.replaceRange = function(text, s, e) {
- if (!e) e = s;
- return this.ace.session.replace(new Range(s.line, s.ch, e.line, e.ch), text);
- };
- this.replaceSelections = function(p) {
- var sel = this.ace.selection;
- if (this.ace.inVirtualSelectionMode) {
- this.ace.session.replace(sel.getRange(), p[0] || "");
- return;
- }
- sel.inVirtualSelectionMode = true;
- var ranges = sel.rangeList.ranges;
- if (!ranges.length) ranges = [this.ace.multiSelect.getRange()];
- for (var i = ranges.length; i--;)
- this.ace.session.replace(ranges[i], p[i] || "");
- sel.inVirtualSelectionMode = false;
- };
- this.getSelection = function() {
- return this.ace.getSelectedText();
- };
- this.getSelections = function() {
- return this.listSelections().map(function(x) {
- return this.getRange(x.anchor, x.head);
- }, this);
- };
- this.getInputField = function() {
- return this.ace.textInput.getElement();
- };
- this.getWrapperElement = function() {
- return this.ace.containter;
- };
- var optMap = {
- indentWithTabs: "useSoftTabs",
- indentUnit: "tabSize",
- tabSize: "tabSize",
- firstLineNumber: "firstLineNumber",
- readOnly: "readOnly"
- };
- this.setOption = function(name, val) {
- this.state[name] = val;
- switch (name) {
- case 'indentWithTabs':
- name = optMap[name];
- val = !val;
- break;
- default:
- name = optMap[name];
- }
- if (name)
- this.ace.setOption(name, val);
- };
- this.getOption = function(name, val) {
- var aceOpt = optMap[name];
- if (aceOpt)
- val = this.ace.getOption(aceOpt);
- switch (name) {
- case 'indentWithTabs':
- name = optMap[name];
- return !val;
- }
- return aceOpt ? val : this.state[name];
- };
- this.toggleOverwrite = function(on) {
- this.state.overwrite = on;
- return this.ace.setOverwrite(on);
- };
- this.addOverlay = function(o) {
- if (!this.$searchHighlight || !this.$searchHighlight.session) {
- var highlight = new SearchHighlight(null, "ace_highlight-marker", "text");
- var marker = this.ace.session.addDynamicMarker(highlight);
- highlight.id = marker.id;
- highlight.session = this.ace.session;
- highlight.destroy = function(o) {
- highlight.session.off("change", highlight.updateOnChange);
- highlight.session.off("changeEditor", highlight.destroy);
- highlight.session.removeMarker(highlight.id);
- highlight.session = null;
- };
- highlight.updateOnChange = function(delta) {
- var row = delta.start.row;
- if (row == delta.end.row) highlight.cache[row] = undefined;
- else highlight.cache.splice(row, highlight.cache.length);
- };
- highlight.session.on("changeEditor", highlight.destroy);
- highlight.session.on("change", highlight.updateOnChange);
- }
- var re = new RegExp(o.query.source, "gmi");
- this.$searchHighlight = o.highlight = highlight;
- this.$searchHighlight.setRegexp(re);
- this.ace.renderer.updateBackMarkers();
- };
- this.removeOverlay = function(o) {
- if (this.$searchHighlight && this.$searchHighlight.session) {
- this.$searchHighlight.destroy();
- }
- };
- this.getScrollInfo = function() {
- var renderer = this.ace.renderer;
- var config = renderer.layerConfig;
- return {
- left: renderer.scrollLeft,
- top: renderer.scrollTop,
- height: config.maxHeight,
- width: config.width,
- clientHeight: config.height,
- clientWidth: config.width
- };
- };
- this.getValue = function() {
- return this.ace.getValue();
- };
- this.setValue = function(v) {
- return this.ace.setValue(v);
- };
- this.getTokenTypeAt = function(pos) {
- var token = this.ace.session.getTokenAt(pos.line, pos.ch);
- return token && /comment|string/.test(token.type) ? "string" : "";
- };
- this.findMatchingBracket = function(pos) {
- var m = this.ace.session.findMatchingBracket(toAcePos(pos));
- return {to: m && toCmPos(m)};
- };
- this.indentLine = function(line, method) {
- if (method === true)
- this.ace.session.indentRows(line, line, "\t");
- else if (method === false)
- this.ace.session.outdentRows(new Range(line, 0, line, 0));
- };
- this.indexFromPos = function(pos) {
- return this.ace.session.doc.positionToIndex(toAcePos(pos));
- };
- this.posFromIndex = function(index) {
- return toCmPos(this.ace.session.doc.indexToPosition(index));
- };
- this.focus = function(index) {
- return this.ace.focus();
- };
- this.blur = function(index) {
- return this.ace.blur();
- };
- this.defaultTextHeight = function(index) {
- return this.ace.renderer.layerConfig.lineHeight;
- };
- this.scanForBracket = function(pos, dir, _, options) {
- var re = options.bracketRegex.source;
- if (dir == 1) {
- var m = this.ace.session.$findClosingBracket(re.slice(1, 2), toAcePos(pos), /paren|text/);
- } else {
- var m = this.ace.session.$findOpeningBracket(re.slice(-2, -1), {row: pos.line, column: pos.ch + 1}, /paren|text/);
- }
- return m && {pos: toCmPos(m)};
- };
- this.refresh = function() {
- return this.ace.resize(true);
- };
- this.getMode = function() {
- return { name : this.getOption("mode") };
- }
-}).call(CodeMirror.prototype);
- function toAcePos(cmPos) {
- return {row: cmPos.line, column: cmPos.ch};
- }
- function toCmPos(acePos) {
- return new Pos(acePos.row, acePos.column);
- }
-
- var StringStream = CodeMirror.StringStream = function(string, tabSize) {
- this.pos = this.start = 0;
- this.string = string;
- this.tabSize = tabSize || 8;
- this.lastColumnPos = this.lastColumnValue = 0;
- this.lineStart = 0;
- };
-
- StringStream.prototype = {
- eol: function() {return this.pos >= this.string.length;},
- sol: function() {return this.pos == this.lineStart;},
- peek: function() {return this.string.charAt(this.pos) || undefined;},
- next: function() {
- if (this.pos < this.string.length)
- return this.string.charAt(this.pos++);
- },
- eat: function(match) {
- var ch = this.string.charAt(this.pos);
- if (typeof match == "string") var ok = ch == match;
- else var ok = ch && (match.test ? match.test(ch) : match(ch));
- if (ok) {++this.pos; return ch;}
- },
- eatWhile: function(match) {
- var start = this.pos;
- while (this.eat(match)){}
- return this.pos > start;
- },
- eatSpace: function() {
- var start = this.pos;
- while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
- return this.pos > start;
- },
- skipToEnd: function() {this.pos = this.string.length;},
- skipTo: function(ch) {
- var found = this.string.indexOf(ch, this.pos);
- if (found > -1) {this.pos = found; return true;}
- },
- backUp: function(n) {this.pos -= n;},
- column: function() {
- throw "not implemented";
- },
- indentation: function() {
- throw "not implemented";
- },
- match: function(pattern, consume, caseInsensitive) {
- if (typeof pattern == "string") {
- var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
- var substr = this.string.substr(this.pos, pattern.length);
- if (cased(substr) == cased(pattern)) {
- if (consume !== false) this.pos += pattern.length;
- return true;
- }
- } else {
- var match = this.string.slice(this.pos).match(pattern);
- if (match && match.index > 0) return null;
- if (match && consume !== false) this.pos += match[0].length;
- return match;
- }
- },
- current: function(){return this.string.slice(this.start, this.pos);},
- hideFirstChars: function(n, inner) {
- this.lineStart += n;
- try { return inner(); }
- finally { this.lineStart -= n; }
- }
- };
-CodeMirror.defineExtension = function(name, fn) {
- CodeMirror.prototype[name] = fn;
-};
-dom.importCssString(".normal-mode .ace_cursor{\
- border: 1px solid red;\
- background-color: red;\
- opacity: 0.5;\
-}\
-.normal-mode .ace_hidden-cursors .ace_cursor{\
- background-color: transparent;\
-}\
-.ace_dialog {\
- position: absolute;\
- left: 0; right: 0;\
- background: white;\
- z-index: 15;\
- padding: .1em .8em;\
- overflow: hidden;\
- color: #333;\
-}\
-.ace_dialog-top {\
- border-bottom: 1px solid #eee;\
- top: 0;\
-}\
-.ace_dialog-bottom {\
- border-top: 1px solid #eee;\
- bottom: 0;\
-}\
-.ace_dialog input {\
- border: none;\
- outline: none;\
- background: transparent;\
- width: 20em;\
- color: inherit;\
- font-family: monospace;\
-}", "vimMode");
-(function() {
- function dialogDiv(cm, template, bottom) {
- var wrap = cm.ace.container;
- var dialog;
- dialog = wrap.appendChild(document.createElement("div"));
- if (bottom)
- dialog.className = "ace_dialog ace_dialog-bottom";
- else
- dialog.className = "ace_dialog ace_dialog-top";
-
- if (typeof template == "string") {
- dialog.innerHTML = template;
- } else { // Assuming it's a detached DOM element.
- dialog.appendChild(template);
- }
- return dialog;
- }
-
- function closeNotification(cm, newVal) {
- if (cm.state.currentNotificationClose)
- cm.state.currentNotificationClose();
- cm.state.currentNotificationClose = newVal;
- }
-
- CodeMirror.defineExtension("openDialog", function(template, callback, options) {
- if (this.virtualSelectionMode()) return;
- if (!options) options = {};
-
- closeNotification(this, null);
-
- var dialog = dialogDiv(this, template, options.bottom);
- var closed = false, me = this;
- function close(newVal) {
- if (typeof newVal == 'string') {
- inp.value = newVal;
- } else {
- if (closed) return;
- closed = true;
- dialog.parentNode.removeChild(dialog);
- me.focus();
-
- if (options.onClose) options.onClose(dialog);
- }
- }
-
- var inp = dialog.getElementsByTagName("input")[0], button;
- if (inp) {
- if (options.value) {
- inp.value = options.value;
- if (options.select !== false) inp.select();
- }
-
- if (options.onInput)
- CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);});
- if (options.onKeyUp)
- CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
-
- CodeMirror.on(inp, "keydown", function(e) {
- if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
- if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) {
- inp.blur();
- CodeMirror.e_stop(e);
- close();
- }
- if (e.keyCode == 13) callback(inp.value);
- });
-
- if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close);
-
- inp.focus();
- } else if (button = dialog.getElementsByTagName("button")[0]) {
- CodeMirror.on(button, "click", function() {
- close();
- me.focus();
- });
-
- if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close);
-
- button.focus();
- }
- return close;
- });
-
- CodeMirror.defineExtension("openNotification", function(template, options) {
- if (this.virtualSelectionMode()) return;
- closeNotification(this, close);
- var dialog = dialogDiv(this, template, options && options.bottom);
- var closed = false, doneTimer;
- var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000;
-
- function close() {
- if (closed) return;
- closed = true;
- clearTimeout(doneTimer);
- dialog.parentNode.removeChild(dialog);
- }
-
- CodeMirror.on(dialog, 'click', function(e) {
- CodeMirror.e_preventDefault(e);
- close();
- });
-
- if (duration)
- doneTimer = setTimeout(close, duration);
-
- return close;
- });
-})();
-
-
- var defaultKeymap = [
- { keys: '', type: 'keyToKey', toKeys: 'h' },
- { keys: '', type: 'keyToKey', toKeys: 'l' },
- { keys: '', type: 'keyToKey', toKeys: 'k' },
- { keys: '', type: 'keyToKey', toKeys: 'j' },
- { keys: '', type: 'keyToKey', toKeys: 'l' },
- { keys: '', type: 'keyToKey', toKeys: 'h', context: 'normal'},
- { keys: '', type: 'keyToKey', toKeys: 'W' },
- { keys: '', type: 'keyToKey', toKeys: 'B', context: 'normal' },
- { keys: '', type: 'keyToKey', toKeys: 'w' },
- { keys: '', type: 'keyToKey', toKeys: 'b', context: 'normal' },
- { keys: '', type: 'keyToKey', toKeys: 'j' },
- { keys: '', type: 'keyToKey', toKeys: 'k' },
- { keys: '', type: 'keyToKey', toKeys: '' },
- { keys: '', type: 'keyToKey', toKeys: '' },
- { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' },
- { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' },
- { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' },
- { keys: 's', type: 'keyToKey', toKeys: 'xi', context: 'visual'},
- { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' },
- { keys: 'S', type: 'keyToKey', toKeys: 'dcc', context: 'visual' },
- { keys: '', type: 'keyToKey', toKeys: '0' },
- { keys: '', type: 'keyToKey', toKeys: '$' },
- { keys: '', type: 'keyToKey', toKeys: '' },
- { keys: '', type: 'keyToKey', toKeys: '' },
- { keys: '', type: 'keyToKey', toKeys: 'j^', context: 'normal' },
- { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }},
- { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }},
- { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }},
- { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }},
- { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }},
- { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }},
- { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }},
- { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }},
- { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }},
- { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }},
- { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }},
- { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }},
- { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }},
- { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }},
- { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }},
- { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }},
- { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }},
- { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }},
- { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }},
- { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }},
- { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }},
- { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }},
- { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }},
- { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
- { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
- { keys: '0', type: 'motion', motion: 'moveToStartOfLine' },
- { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' },
- { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }},
- { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }},
- { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
- { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }},
- { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }},
- { keys: 'f', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }},
- { keys: 'F', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }},
- { keys: 't', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }},
- { keys: 'T', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }},
- { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }},
- { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }},
- { keys: '\'', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}},
- { keys: '`', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}},
- { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
- { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
- { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
- { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
- { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}},
- { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}},
- { keys: ']', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}},
- { keys: '[', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}},
- { keys: '|', type: 'motion', motion: 'moveToColumn'},
- { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'},
- { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'},
- { keys: 'd', type: 'operator', operator: 'delete' },
- { keys: 'y', type: 'operator', operator: 'yank' },
- { keys: 'c', type: 'operator', operator: 'change' },
- { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }},
- { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }},
- { keys: 'g~', type: 'operator', operator: 'changeCase' },
- { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true },
- { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true },
- { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }},
- { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }},
- { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }},
- { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }},
- { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
- { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'},
- { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
- { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'},
- { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
- { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'},
- { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'},
- { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'},
- { keys: '', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' },
- { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }},
- { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }},
- { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }},
- { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }},
- { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' },
- { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' },
- { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },
- { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' },
- { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' },
- { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' },
- { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' },
- { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' },
- { keys: 'v', type: 'action', action: 'toggleVisualMode' },
- { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }},
- { keys: '', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
- { keys: 'gv', type: 'action', action: 'reselectLastSelection' },
- { keys: 'J', type: 'action', action: 'joinLines', isEdit: true },
- { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }},
- { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }},
- { keys: 'r', type: 'action', action: 'replace', isEdit: true },
- { keys: '@', type: 'action', action: 'replayMacro' },
- { keys: 'q', type: 'action', action: 'enterMacroRecordMode' },
- { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }},
- { keys: 'u', type: 'action', action: 'undo', context: 'normal' },
- { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true },
- { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true },
- { keys: '', type: 'action', action: 'redo' },
- { keys: 'm', type: 'action', action: 'setMark' },
- { keys: '"', type: 'action', action: 'setRegister' },
- { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }},
- { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
- { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }},
- { keys: 'z', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
- { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }},
- { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
- { keys: '.', type: 'action', action: 'repeatLastEdit' },
- { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}},
- { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}},
- { keys: 'a', type: 'motion', motion: 'textObjectManipulation' },
- { keys: 'i', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},
- { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
- { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
- { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
- { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
- { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
- { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
- { keys: ':', type: 'ex' }
- ];
- var defaultExCommandMap = [
- { name: 'colorscheme', shortName: 'colo' },
- { name: 'map' },
- { name: 'imap', shortName: 'im' },
- { name: 'nmap', shortName: 'nm' },
- { name: 'vmap', shortName: 'vm' },
- { name: 'unmap' },
- { name: 'write', shortName: 'w' },
- { name: 'undo', shortName: 'u' },
- { name: 'redo', shortName: 'red' },
- { name: 'set', shortName: 'se' },
- { name: 'set', shortName: 'se' },
- { name: 'setlocal', shortName: 'setl' },
- { name: 'setglobal', shortName: 'setg' },
- { name: 'sort', shortName: 'sor' },
- { name: 'substitute', shortName: 's', possiblyAsync: true },
- { name: 'nohlsearch', shortName: 'noh' },
- { name: 'delmarks', shortName: 'delm' },
- { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true },
- { name: 'global', shortName: 'g' }
- ];
-
- var Pos = CodeMirror.Pos;
-
- var Vim = function() { return vimApi; } //{
- function enterVimMode(cm) {
- cm.setOption('disableInput', true);
- cm.setOption('showCursorWhenSelecting', false);
- CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
- cm.on('cursorActivity', onCursorActivity);
- maybeInitVimState(cm);
- CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
- }
-
- function leaveVimMode(cm) {
- cm.setOption('disableInput', false);
- cm.off('cursorActivity', onCursorActivity);
- CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
- cm.state.vim = null;
- }
-
- function detachVimMap(cm, next) {
- if (this == CodeMirror.keyMap.vim)
- CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor");
-
- if (!next || next.attach != attachVimMap)
- leaveVimMode(cm, false);
- }
- function attachVimMap(cm, prev) {
- if (this == CodeMirror.keyMap.vim)
- CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor");
-
- if (!prev || prev.attach != attachVimMap)
- enterVimMode(cm);
- }
- CodeMirror.defineOption('vimMode', false, function(cm, val, prev) {
- if (val && cm.getOption("keyMap") != "vim")
- cm.setOption("keyMap", "vim");
- else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap")))
- cm.setOption("keyMap", "default");
- });
-
- function cmKey(key, cm) {
- if (!cm) { return undefined; }
- var vimKey = cmKeyToVimKey(key);
- if (!vimKey) {
- return false;
- }
- var cmd = CodeMirror.Vim.findKey(cm, vimKey);
- if (typeof cmd == 'function') {
- CodeMirror.signal(cm, 'vim-keypress', vimKey);
- }
- return cmd;
- }
-
- var modifiers = {'Shift': 'S', 'Ctrl': 'C', 'Alt': 'A', 'Cmd': 'D', 'Mod': 'A'};
- var specialKeys = {Enter:'CR',Backspace:'BS',Delete:'Del'};
- function cmKeyToVimKey(key) {
- if (key.charAt(0) == '\'') {
- return key.charAt(1);
- }
- var pieces = key.split(/-(?!$)/);
- var lastPiece = pieces[pieces.length - 1];
- if (pieces.length == 1 && pieces[0].length == 1) {
- return false;
- } else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) {
- return false;
- }
- var hasCharacter = false;
- for (var i = 0; i < pieces.length; i++) {
- var piece = pieces[i];
- if (piece in modifiers) { pieces[i] = modifiers[piece]; }
- else { hasCharacter = true; }
- if (piece in specialKeys) { pieces[i] = specialKeys[piece]; }
- }
- if (!hasCharacter) {
- return false;
- }
- if (isUpperCase(lastPiece)) {
- pieces[pieces.length - 1] = lastPiece.toLowerCase();
- }
- return '<' + pieces.join('-') + '>';
- }
-
- function getOnPasteFn(cm) {
- var vim = cm.state.vim;
- if (!vim.onPasteFn) {
- vim.onPasteFn = function() {
- if (!vim.insertMode) {
- cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
- actions.enterInsertMode(cm, {}, vim);
- }
- };
- }
- return vim.onPasteFn;
- }
-
- var numberRegex = /[\d]/;
- var wordCharTest = [CodeMirror.isWordChar, function(ch) {
- return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch);
- }], bigWordCharTest = [function(ch) {
- return /\S/.test(ch);
- }];
- function makeKeyRange(start, size) {
- var keys = [];
- for (var i = start; i < start + size; i++) {
- keys.push(String.fromCharCode(i));
- }
- return keys;
- }
- var upperCaseAlphabet = makeKeyRange(65, 26);
- var lowerCaseAlphabet = makeKeyRange(97, 26);
- var numbers = makeKeyRange(48, 10);
- var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
- var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '/']);
-
- function isLine(cm, line) {
- return line >= cm.firstLine() && line <= cm.lastLine();
- }
- function isLowerCase(k) {
- return (/^[a-z]$/).test(k);
- }
- function isMatchableSymbol(k) {
- return '()[]{}'.indexOf(k) != -1;
- }
- function isNumber(k) {
- return numberRegex.test(k);
- }
- function isUpperCase(k) {
- return (/^[A-Z]$/).test(k);
- }
- function isWhiteSpaceString(k) {
- return (/^\s*$/).test(k);
- }
- function inArray(val, arr) {
- for (var i = 0; i < arr.length; i++) {
- if (arr[i] == val) {
- return true;
- }
- }
- return false;
- }
-
- var options = {};
- function defineOption(name, defaultValue, type, aliases, callback) {
- if (defaultValue === undefined && !callback) {
- throw Error('defaultValue is required unless callback is provided');
- }
- if (!type) { type = 'string'; }
- options[name] = {
- type: type,
- defaultValue: defaultValue,
- callback: callback
- };
- if (aliases) {
- for (var i = 0; i < aliases.length; i++) {
- options[aliases[i]] = options[name];
- }
- }
- if (defaultValue) {
- setOption(name, defaultValue);
- }
- }
-
- function setOption(name, value, cm, cfg) {
- var option = options[name];
- cfg = cfg || {};
- var scope = cfg.scope;
- if (!option) {
- throw Error('Unknown option: ' + name);
- }
- if (option.type == 'boolean') {
- if (value && value !== true) {
- throw Error('Invalid argument: ' + name + '=' + value);
- } else if (value !== false) {
- value = true;
- }
- }
- if (option.callback) {
- if (scope !== 'local') {
- option.callback(value, undefined);
- }
- if (scope !== 'global' && cm) {
- option.callback(value, cm);
- }
- } else {
- if (scope !== 'local') {
- option.value = option.type == 'boolean' ? !!value : value;
- }
- if (scope !== 'global' && cm) {
- cm.state.vim.options[name] = {value: value};
- }
- }
- }
-
- function getOption(name, cm, cfg) {
- var option = options[name];
- cfg = cfg || {};
- var scope = cfg.scope;
- if (!option) {
- throw Error('Unknown option: ' + name);
- }
- if (option.callback) {
- var local = cm && option.callback(undefined, cm);
- if (scope !== 'global' && local !== undefined) {
- return local;
- }
- if (scope !== 'local') {
- return option.callback();
- }
- return;
- } else {
- var local = (scope !== 'global') && (cm && cm.state.vim.options[name]);
- return (local || (scope !== 'local') && option || {}).value;
- }
- }
-
- defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) {
- if (cm === undefined) {
- return;
- }
- if (name === undefined) {
- var mode = cm.getOption('mode');
- return mode == 'null' ? '' : mode;
- } else {
- var mode = name == '' ? 'null' : name;
- cm.setOption('mode', mode);
- }
- });
-
- var createCircularJumpList = function() {
- var size = 100;
- var pointer = -1;
- var head = 0;
- var tail = 0;
- var buffer = new Array(size);
- function add(cm, oldCur, newCur) {
- var current = pointer % size;
- var curMark = buffer[current];
- function useNextSlot(cursor) {
- var next = ++pointer % size;
- var trashMark = buffer[next];
- if (trashMark) {
- trashMark.clear();
- }
- buffer[next] = cm.setBookmark(cursor);
- }
- if (curMark) {
- var markPos = curMark.find();
- if (markPos && !cursorEqual(markPos, oldCur)) {
- useNextSlot(oldCur);
- }
- } else {
- useNextSlot(oldCur);
- }
- useNextSlot(newCur);
- head = pointer;
- tail = pointer - size + 1;
- if (tail < 0) {
- tail = 0;
- }
- }
- function move(cm, offset) {
- pointer += offset;
- if (pointer > head) {
- pointer = head;
- } else if (pointer < tail) {
- pointer = tail;
- }
- var mark = buffer[(size + pointer) % size];
- if (mark && !mark.find()) {
- var inc = offset > 0 ? 1 : -1;
- var newCur;
- var oldCur = cm.getCursor();
- do {
- pointer += inc;
- mark = buffer[(size + pointer) % size];
- if (mark &&
- (newCur = mark.find()) &&
- !cursorEqual(oldCur, newCur)) {
- break;
- }
- } while (pointer < head && pointer > tail);
- }
- return mark;
- }
- return {
- cachedCursor: undefined, //used for # and * jumps
- add: add,
- move: move
- };
- };
- var createInsertModeChanges = function(c) {
- if (c) {
- return {
- changes: c.changes,
- expectCursorActivityForChange: c.expectCursorActivityForChange
- };
- }
- return {
- changes: [],
- expectCursorActivityForChange: false
- };
- };
-
- function MacroModeState() {
- this.latestRegister = undefined;
- this.isPlaying = false;
- this.isRecording = false;
- this.replaySearchQueries = [];
- this.onRecordingDone = undefined;
- this.lastInsertModeChanges = createInsertModeChanges();
- }
- MacroModeState.prototype = {
- exitMacroRecordMode: function() {
- var macroModeState = vimGlobalState.macroModeState;
- if (macroModeState.onRecordingDone) {
- macroModeState.onRecordingDone(); // close dialog
- }
- macroModeState.onRecordingDone = undefined;
- macroModeState.isRecording = false;
- },
- enterMacroRecordMode: function(cm, registerName) {
- var register =
- vimGlobalState.registerController.getRegister(registerName);
- if (register) {
- register.clear();
- this.latestRegister = registerName;
- if (cm.openDialog) {
- this.onRecordingDone = cm.openDialog(
- '(recording)['+registerName+']', null, {bottom:true});
- }
- this.isRecording = true;
- }
- }
- };
-
- function maybeInitVimState(cm) {
- if (!cm.state.vim) {
- cm.state.vim = {
- inputState: new InputState(),
- lastEditInputState: undefined,
- lastEditActionCommand: undefined,
- lastHPos: -1,
- lastHSPos: -1,
- lastMotion: null,
- marks: {},
- fakeCursor: null,
- insertMode: false,
- insertModeRepeat: undefined,
- visualMode: false,
- visualLine: false,
- visualBlock: false,
- lastSelection: null,
- lastPastedText: null,
- sel: {},
- options: {}
- };
- }
- return cm.state.vim;
- }
- var vimGlobalState;
- function resetVimGlobalState() {
- vimGlobalState = {
- searchQuery: null,
- searchIsReversed: false,
- lastSubstituteReplacePart: undefined,
- jumpList: createCircularJumpList(),
- macroModeState: new MacroModeState,
- lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''},
- registerController: new RegisterController({}),
- searchHistoryController: new HistoryController({}),
- exCommandHistoryController : new HistoryController({})
- };
- for (var optionName in options) {
- var option = options[optionName];
- option.value = option.defaultValue;
- }
- }
-
- var lastInsertModeKeyTimer;
- var vimApi= {
- buildKeyMap: function() {
- },
- getRegisterController: function() {
- return vimGlobalState.registerController;
- },
- resetVimGlobalState_: resetVimGlobalState,
- getVimGlobalState_: function() {
- return vimGlobalState;
- },
- maybeInitVimState_: maybeInitVimState,
-
- suppressErrorLogging: false,
-
- InsertModeKey: InsertModeKey,
- map: function(lhs, rhs, ctx) {
- exCommandDispatcher.map(lhs, rhs, ctx);
- },
- unmap: function(lhs, ctx) {
- exCommandDispatcher.unmap(lhs, ctx || "normal");
- },
- setOption: setOption,
- getOption: getOption,
- defineOption: defineOption,
- defineEx: function(name, prefix, func){
- if (!prefix) {
- prefix = name;
- } else if (name.indexOf(prefix) !== 0) {
- throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
- }
- exCommands[name]=func;
- exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
- },
- handleKey: function (cm, key, origin) {
- var command = this.findKey(cm, key, origin);
- if (typeof command === 'function') {
- return command();
- }
- },
- findKey: function(cm, key, origin) {
- var vim = maybeInitVimState(cm);
- function handleMacroRecording() {
- var macroModeState = vimGlobalState.macroModeState;
- if (macroModeState.isRecording) {
- if (key == 'q') {
- macroModeState.exitMacroRecordMode();
- clearInputState(cm);
- return true;
- }
- if (origin != 'mapping') {
- logKey(macroModeState, key);
- }
- }
- }
- function handleEsc() {
- if (key == '') {
- clearInputState(cm);
- if (vim.visualMode) {
- exitVisualMode(cm);
- } else if (vim.insertMode) {
- exitInsertMode(cm);
- }
- return true;
- }
- }
- function doKeyToKey(keys) {
- var match;
- while (keys) {
- match = (/<\w+-.+?>|<\w+>|./).exec(keys);
- key = match[0];
- keys = keys.substring(match.index + key.length);
- CodeMirror.Vim.handleKey(cm, key, 'mapping');
- }
- }
-
- function handleKeyInsertMode() {
- if (handleEsc()) { return true; }
- var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
- var keysAreChars = key.length == 1;
- var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
- while (keys.length > 1 && match.type != 'full') {
- var keys = vim.inputState.keyBuffer = keys.slice(1);
- var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
- if (thisMatch.type != 'none') { match = thisMatch; }
- }
- if (match.type == 'none') { clearInputState(cm); return false; }
- else if (match.type == 'partial') {
- if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
- lastInsertModeKeyTimer = window.setTimeout(
- function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } },
- getOption('insertModeEscKeysTimeout'));
- return !keysAreChars;
- }
-
- if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
- if (keysAreChars) {
- var here = cm.getCursor();
- cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input');
- }
- clearInputState(cm);
- return match.command;
- }
-
- function handleKeyNonInsertMode() {
- if (handleMacroRecording() || handleEsc()) { return true; }
-
- var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
- if (/^[1-9]\d*$/.test(keys)) { return true; }
-
- var keysMatcher = /^(\d*)(.*)$/.exec(keys);
- if (!keysMatcher) { clearInputState(cm); return false; }
- var context = vim.visualMode ? 'visual' :
- 'normal';
- var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context);
- if (match.type == 'none') { clearInputState(cm); return false; }
- else if (match.type == 'partial') { return true; }
-
- vim.inputState.keyBuffer = '';
- var keysMatcher = /^(\d*)(.*)$/.exec(keys);
- if (keysMatcher[1] && keysMatcher[1] != '0') {
- vim.inputState.pushRepeatDigit(keysMatcher[1]);
- }
- return match.command;
- }
-
- var command;
- if (vim.insertMode) { command = handleKeyInsertMode(); }
- else { command = handleKeyNonInsertMode(); }
- if (command === false) {
- return undefined;
- } else if (command === true) {
- return function() { return true; };
- } else {
- return function() {
- if ((command.operator || command.isEdit) && cm.getOption('readOnly'))
- return; // ace_patch
- return cm.operation(function() {
- cm.curOp.isVimOp = true;
- try {
- if (command.type == 'keyToKey') {
- doKeyToKey(command.toKeys);
- } else {
- commandDispatcher.processCommand(cm, vim, command);
- }
- } catch (e) {
- cm.state.vim = undefined;
- maybeInitVimState(cm);
- if (!CodeMirror.Vim.suppressErrorLogging) {
- console['log'](e);
- }
- throw e;
- }
- return true;
- });
- };
- }
- },
- handleEx: function(cm, input) {
- exCommandDispatcher.processCommand(cm, input);
- },
-
- defineMotion: defineMotion,
- defineAction: defineAction,
- defineOperator: defineOperator,
- mapCommand: mapCommand,
- _mapCommand: _mapCommand,
-
- defineRegister: defineRegister,
-
- exitVisualMode: exitVisualMode,
- exitInsertMode: exitInsertMode
- };
- function InputState() {
- this.prefixRepeat = [];
- this.motionRepeat = [];
-
- this.operator = null;
- this.operatorArgs = null;
- this.motion = null;
- this.motionArgs = null;
- this.keyBuffer = []; // For matching multi-key commands.
- this.registerName = null; // Defaults to the unnamed register.
- }
- InputState.prototype.pushRepeatDigit = function(n) {
- if (!this.operator) {
- this.prefixRepeat = this.prefixRepeat.concat(n);
- } else {
- this.motionRepeat = this.motionRepeat.concat(n);
- }
- };
- InputState.prototype.getRepeat = function() {
- var repeat = 0;
- if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
- repeat = 1;
- if (this.prefixRepeat.length > 0) {
- repeat *= parseInt(this.prefixRepeat.join(''), 10);
- }
- if (this.motionRepeat.length > 0) {
- repeat *= parseInt(this.motionRepeat.join(''), 10);
- }
- }
- return repeat;
- };
-
- function clearInputState(cm, reason) {
- cm.state.vim.inputState = new InputState();
- CodeMirror.signal(cm, 'vim-command-done', reason);
- }
- function Register(text, linewise, blockwise) {
- this.clear();
- this.keyBuffer = [text || ''];
- this.insertModeChanges = [];
- this.searchQueries = [];
- this.linewise = !!linewise;
- this.blockwise = !!blockwise;
- }
- Register.prototype = {
- setText: function(text, linewise, blockwise) {
- this.keyBuffer = [text || ''];
- this.linewise = !!linewise;
- this.blockwise = !!blockwise;
- },
- pushText: function(text, linewise) {
- if (linewise) {
- if (!this.linewise) {
- this.keyBuffer.push('\n');
- }
- this.linewise = true;
- }
- this.keyBuffer.push(text);
- },
- pushInsertModeChanges: function(changes) {
- this.insertModeChanges.push(createInsertModeChanges(changes));
- },
- pushSearchQuery: function(query) {
- this.searchQueries.push(query);
- },
- clear: function() {
- this.keyBuffer = [];
- this.insertModeChanges = [];
- this.searchQueries = [];
- this.linewise = false;
- },
- toString: function() {
- return this.keyBuffer.join('');
- }
- };
- function defineRegister(name, register) {
- var registers = vimGlobalState.registerController.registers[name];
- if (!name || name.length != 1) {
- throw Error('Register name must be 1 character');
- }
- registers[name] = register;
- validRegisters.push(name);
- }
- function RegisterController(registers) {
- this.registers = registers;
- this.unnamedRegister = registers['"'] = new Register();
- registers['.'] = new Register();
- registers[':'] = new Register();
- registers['/'] = new Register();
- }
- RegisterController.prototype = {
- pushText: function(registerName, operator, text, linewise, blockwise) {
- if (linewise && text.charAt(0) == '\n') {
- text = text.slice(1) + '\n';
- }
- if (linewise && text.charAt(text.length - 1) !== '\n'){
- text += '\n';
- }
- var register = this.isValidRegister(registerName) ?
- this.getRegister(registerName) : null;
- if (!register) {
- switch (operator) {
- case 'yank':
- this.registers['0'] = new Register(text, linewise, blockwise);
- break;
- case 'delete':
- case 'change':
- if (text.indexOf('\n') == -1) {
- this.registers['-'] = new Register(text, linewise);
- } else {
- this.shiftNumericRegisters_();
- this.registers['1'] = new Register(text, linewise);
- }
- break;
- }
- this.unnamedRegister.setText(text, linewise, blockwise);
- return;
- }
- var append = isUpperCase(registerName);
- if (append) {
- register.pushText(text, linewise);
- } else {
- register.setText(text, linewise, blockwise);
- }
- this.unnamedRegister.setText(register.toString(), linewise);
- },
- getRegister: function(name) {
- if (!this.isValidRegister(name)) {
- return this.unnamedRegister;
- }
- name = name.toLowerCase();
- if (!this.registers[name]) {
- this.registers[name] = new Register();
- }
- return this.registers[name];
- },
- isValidRegister: function(name) {
- return name && inArray(name, validRegisters);
- },
- shiftNumericRegisters_: function() {
- for (var i = 9; i >= 2; i--) {
- this.registers[i] = this.getRegister('' + (i - 1));
- }
- }
- };
- function HistoryController() {
- this.historyBuffer = [];
- this.iterator;
- this.initialPrefix = null;
- }
- HistoryController.prototype = {
- nextMatch: function (input, up) {
- var historyBuffer = this.historyBuffer;
- var dir = up ? -1 : 1;
- if (this.initialPrefix === null) this.initialPrefix = input;
- for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) {
- var element = historyBuffer[i];
- for (var j = 0; j <= element.length; j++) {
- if (this.initialPrefix == element.substring(0, j)) {
- this.iterator = i;
- return element;
- }
- }
- }
- if (i >= historyBuffer.length) {
- this.iterator = historyBuffer.length;
- return this.initialPrefix;
- }
- if (i < 0 ) return input;
- },
- pushInput: function(input) {
- var index = this.historyBuffer.indexOf(input);
- if (index > -1) this.historyBuffer.splice(index, 1);
- if (input.length) this.historyBuffer.push(input);
- },
- reset: function() {
- this.initialPrefix = null;
- this.iterator = this.historyBuffer.length;
- }
- };
- var commandDispatcher = {
- matchCommand: function(keys, keyMap, inputState, context) {
- var matches = commandMatches(keys, keyMap, context, inputState);
- if (!matches.full && !matches.partial) {
- return {type: 'none'};
- } else if (!matches.full && matches.partial) {
- return {type: 'partial'};
- }
-
- var bestMatch;
- for (var i = 0; i < matches.full.length; i++) {
- var match = matches.full[i];
- if (!bestMatch) {
- bestMatch = match;
- }
- }
- if (bestMatch.keys.slice(-11) == '') {
- inputState.selectedCharacter = lastChar(keys);
- }
- return {type: 'full', command: bestMatch};
- },
- processCommand: function(cm, vim, command) {
- vim.inputState.repeatOverride = command.repeatOverride;
- switch (command.type) {
- case 'motion':
- this.processMotion(cm, vim, command);
- break;
- case 'operator':
- this.processOperator(cm, vim, command);
- break;
- case 'operatorMotion':
- this.processOperatorMotion(cm, vim, command);
- break;
- case 'action':
- this.processAction(cm, vim, command);
- break;
- case 'search':
- this.processSearch(cm, vim, command);
- break;
- case 'ex':
- case 'keyToEx':
- this.processEx(cm, vim, command);
- break;
- default:
- break;
- }
- },
- processMotion: function(cm, vim, command) {
- vim.inputState.motion = command.motion;
- vim.inputState.motionArgs = copyArgs(command.motionArgs);
- this.evalInput(cm, vim);
- },
- processOperator: function(cm, vim, command) {
- var inputState = vim.inputState;
- if (inputState.operator) {
- if (inputState.operator == command.operator) {
- inputState.motion = 'expandToLine';
- inputState.motionArgs = { linewise: true };
- this.evalInput(cm, vim);
- return;
- } else {
- clearInputState(cm);
- }
- }
- inputState.operator = command.operator;
- inputState.operatorArgs = copyArgs(command.operatorArgs);
- if (vim.visualMode) {
- this.evalInput(cm, vim);
- }
- },
- processOperatorMotion: function(cm, vim, command) {
- var visualMode = vim.visualMode;
- var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
- if (operatorMotionArgs) {
- if (visualMode && operatorMotionArgs.visualLine) {
- vim.visualLine = true;
- }
- }
- this.processOperator(cm, vim, command);
- if (!visualMode) {
- this.processMotion(cm, vim, command);
- }
- },
- processAction: function(cm, vim, command) {
- var inputState = vim.inputState;
- var repeat = inputState.getRepeat();
- var repeatIsExplicit = !!repeat;
- var actionArgs = copyArgs(command.actionArgs) || {};
- if (inputState.selectedCharacter) {
- actionArgs.selectedCharacter = inputState.selectedCharacter;
- }
- if (command.operator) {
- this.processOperator(cm, vim, command);
- }
- if (command.motion) {
- this.processMotion(cm, vim, command);
- }
- if (command.motion || command.operator) {
- this.evalInput(cm, vim);
- }
- actionArgs.repeat = repeat || 1;
- actionArgs.repeatIsExplicit = repeatIsExplicit;
- actionArgs.registerName = inputState.registerName;
- clearInputState(cm);
- vim.lastMotion = null;
- if (command.isEdit) {
- this.recordLastEdit(vim, inputState, command);
- }
- actions[command.action](cm, actionArgs, vim);
- },
- processSearch: function(cm, vim, command) {
- if (!cm.getSearchCursor) {
- return;
- }
- var forward = command.searchArgs.forward;
- var wholeWordOnly = command.searchArgs.wholeWordOnly;
- getSearchState(cm).setReversed(!forward);
- var promptPrefix = (forward) ? '/' : '?';
- var originalQuery = getSearchState(cm).getQuery();
- var originalScrollPos = cm.getScrollInfo();
- function handleQuery(query, ignoreCase, smartCase) {
- vimGlobalState.searchHistoryController.pushInput(query);
- vimGlobalState.searchHistoryController.reset();
- try {
- updateSearchQuery(cm, query, ignoreCase, smartCase);
- } catch (e) {
- showConfirm(cm, 'Invalid regex: ' + query);
- clearInputState(cm);
- return;
- }
- commandDispatcher.processMotion(cm, vim, {
- type: 'motion',
- motion: 'findNext',
- motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
- });
- }
- function onPromptClose(query) {
- cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
- handleQuery(query, true /** ignoreCase */, true /** smartCase */);
- var macroModeState = vimGlobalState.macroModeState;
- if (macroModeState.isRecording) {
- logSearchQuery(macroModeState, query);
- }
- }
- function onPromptKeyUp(e, query, close) {
- var keyName = CodeMirror.keyName(e), up;
- if (keyName == 'Up' || keyName == 'Down') {
- up = keyName == 'Up' ? true : false;
- query = vimGlobalState.searchHistoryController.nextMatch(query, up) || '';
- close(query);
- } else {
- if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
- vimGlobalState.searchHistoryController.reset();
- }
- var parsedQuery;
- try {
- parsedQuery = updateSearchQuery(cm, query,
- true /** ignoreCase */, true /** smartCase */);
- } catch (e) {
- }
- if (parsedQuery) {
- cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
- } else {
- clearSearchHighlight(cm);
- cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
- }
- }
- function onPromptKeyDown(e, query, close) {
- var keyName = CodeMirror.keyName(e);
- if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
- (keyName == 'Backspace' && query == '')) {
- vimGlobalState.searchHistoryController.pushInput(query);
- vimGlobalState.searchHistoryController.reset();
- updateSearchQuery(cm, originalQuery);
- clearSearchHighlight(cm);
- cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
- CodeMirror.e_stop(e);
- clearInputState(cm);
- close();
- cm.focus();
- } else if (keyName == 'Ctrl-U') {
- CodeMirror.e_stop(e);
- close('');
- }
- }
- switch (command.searchArgs.querySrc) {
- case 'prompt':
- var macroModeState = vimGlobalState.macroModeState;
- if (macroModeState.isPlaying) {
- var query = macroModeState.replaySearchQueries.shift();
- handleQuery(query, true /** ignoreCase */, false /** smartCase */);
- } else {
- showPrompt(cm, {
- onClose: onPromptClose,
- prefix: promptPrefix,
- desc: searchPromptDesc,
- onKeyUp: onPromptKeyUp,
- onKeyDown: onPromptKeyDown
- });
- }
- break;
- case 'wordUnderCursor':
- var word = expandWordUnderCursor(cm, false /** inclusive */,
- true /** forward */, false /** bigWord */,
- true /** noSymbol */);
- var isKeyword = true;
- if (!word) {
- word = expandWordUnderCursor(cm, false /** inclusive */,
- true /** forward */, false /** bigWord */,
- false /** noSymbol */);
- isKeyword = false;
- }
- if (!word) {
- return;
- }
- var query = cm.getLine(word.start.line).substring(word.start.ch,
- word.end.ch);
- if (isKeyword && wholeWordOnly) {
- query = '\\b' + query + '\\b';
- } else {
- query = escapeRegex(query);
- }
- vimGlobalState.jumpList.cachedCursor = cm.getCursor();
- cm.setCursor(word.start);
-
- handleQuery(query, true /** ignoreCase */, false /** smartCase */);
- break;
- }
- },
- processEx: function(cm, vim, command) {
- function onPromptClose(input) {
- vimGlobalState.exCommandHistoryController.pushInput(input);
- vimGlobalState.exCommandHistoryController.reset();
- exCommandDispatcher.processCommand(cm, input);
- }
- function onPromptKeyDown(e, input, close) {
- var keyName = CodeMirror.keyName(e), up;
- if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
- (keyName == 'Backspace' && input == '')) {
- vimGlobalState.exCommandHistoryController.pushInput(input);
- vimGlobalState.exCommandHistoryController.reset();
- CodeMirror.e_stop(e);
- clearInputState(cm);
- close();
- cm.focus();
- }
- if (keyName == 'Up' || keyName == 'Down') {
- up = keyName == 'Up' ? true : false;
- input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || '';
- close(input);
- } else if (keyName == 'Ctrl-U') {
- CodeMirror.e_stop(e);
- close('');
- } else {
- if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
- vimGlobalState.exCommandHistoryController.reset();
- }
- }
- if (command.type == 'keyToEx') {
- exCommandDispatcher.processCommand(cm, command.exArgs.input);
- } else {
- if (vim.visualMode) {
- showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
- onKeyDown: onPromptKeyDown});
- } else {
- showPrompt(cm, { onClose: onPromptClose, prefix: ':',
- onKeyDown: onPromptKeyDown});
- }
- }
- },
- evalInput: function(cm, vim) {
- var inputState = vim.inputState;
- var motion = inputState.motion;
- var motionArgs = inputState.motionArgs || {};
- var operator = inputState.operator;
- var operatorArgs = inputState.operatorArgs || {};
- var registerName = inputState.registerName;
- var sel = vim.sel;
- var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head'));
- var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor'));
- var oldHead = copyCursor(origHead);
- var oldAnchor = copyCursor(origAnchor);
- var newHead, newAnchor;
- var repeat;
- if (operator) {
- this.recordLastEdit(vim, inputState);
- }
- if (inputState.repeatOverride !== undefined) {
- repeat = inputState.repeatOverride;
- } else {
- repeat = inputState.getRepeat();
- }
- if (repeat > 0 && motionArgs.explicitRepeat) {
- motionArgs.repeatIsExplicit = true;
- } else if (motionArgs.noRepeat ||
- (!motionArgs.explicitRepeat && repeat === 0)) {
- repeat = 1;
- motionArgs.repeatIsExplicit = false;
- }
- if (inputState.selectedCharacter) {
- motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
- inputState.selectedCharacter;
- }
- motionArgs.repeat = repeat;
- clearInputState(cm);
- if (motion) {
- var motionResult = motions[motion](cm, origHead, motionArgs, vim);
- vim.lastMotion = motions[motion];
- if (!motionResult) {
- return;
- }
- if (motionArgs.toJumplist) {
- if (!operator && cm.ace.curOp != null)
- cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch
- var jumpList = vimGlobalState.jumpList;
- var cachedCursor = jumpList.cachedCursor;
- if (cachedCursor) {
- recordJumpPosition(cm, cachedCursor, motionResult);
- delete jumpList.cachedCursor;
- } else {
- recordJumpPosition(cm, origHead, motionResult);
- }
- }
- if (motionResult instanceof Array) {
- newAnchor = motionResult[0];
- newHead = motionResult[1];
- } else {
- newHead = motionResult;
- }
- if (!newHead) {
- newHead = copyCursor(origHead);
- }
- if (vim.visualMode) {
- if (!(vim.visualBlock && newHead.ch === Infinity)) {
- newHead = clipCursorToContent(cm, newHead, vim.visualBlock);
- }
- if (newAnchor) {
- newAnchor = clipCursorToContent(cm, newAnchor, true);
- }
- newAnchor = newAnchor || oldAnchor;
- sel.anchor = newAnchor;
- sel.head = newHead;
- updateCmSelection(cm);
- updateMark(cm, vim, '<',
- cursorIsBefore(newAnchor, newHead) ? newAnchor
- : newHead);
- updateMark(cm, vim, '>',
- cursorIsBefore(newAnchor, newHead) ? newHead
- : newAnchor);
- } else if (!operator) {
- newHead = clipCursorToContent(cm, newHead);
- cm.setCursor(newHead.line, newHead.ch);
- }
- }
- if (operator) {
- if (operatorArgs.lastSel) {
- newAnchor = oldAnchor;
- var lastSel = operatorArgs.lastSel;
- var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line);
- var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch);
- if (lastSel.visualLine) {
- newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
- } else if (lastSel.visualBlock) {
- newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset);
- } else if (lastSel.head.line == lastSel.anchor.line) {
- newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset);
- } else {
- newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
- }
- vim.visualMode = true;
- vim.visualLine = lastSel.visualLine;
- vim.visualBlock = lastSel.visualBlock;
- sel = vim.sel = {
- anchor: newAnchor,
- head: newHead
- };
- updateCmSelection(cm);
- } else if (vim.visualMode) {
- operatorArgs.lastSel = {
- anchor: copyCursor(sel.anchor),
- head: copyCursor(sel.head),
- visualBlock: vim.visualBlock,
- visualLine: vim.visualLine
- };
- }
- var curStart, curEnd, linewise, mode;
- var cmSel;
- if (vim.visualMode) {
- curStart = cursorMin(sel.head, sel.anchor);
- curEnd = cursorMax(sel.head, sel.anchor);
- linewise = vim.visualLine || operatorArgs.linewise;
- mode = vim.visualBlock ? 'block' :
- linewise ? 'line' :
- 'char';
- cmSel = makeCmSelection(cm, {
- anchor: curStart,
- head: curEnd
- }, mode);
- if (linewise) {
- var ranges = cmSel.ranges;
- if (mode == 'block') {
- for (var i = 0; i < ranges.length; i++) {
- ranges[i].head.ch = lineLength(cm, ranges[i].head.line);
- }
- } else if (mode == 'line') {
- ranges[0].head = Pos(ranges[0].head.line + 1, 0);
- }
- }
- } else {
- curStart = copyCursor(newAnchor || oldAnchor);
- curEnd = copyCursor(newHead || oldHead);
- if (cursorIsBefore(curEnd, curStart)) {
- var tmp = curStart;
- curStart = curEnd;
- curEnd = tmp;
- }
- linewise = motionArgs.linewise || operatorArgs.linewise;
- if (linewise) {
- expandSelectionToLine(cm, curStart, curEnd);
- } else if (motionArgs.forward) {
- clipToLine(cm, curStart, curEnd);
- }
- mode = 'char';
- var exclusive = !motionArgs.inclusive || linewise;
- cmSel = makeCmSelection(cm, {
- anchor: curStart,
- head: curEnd
- }, mode, exclusive);
- }
- cm.setSelections(cmSel.ranges, cmSel.primary);
- vim.lastMotion = null;
- operatorArgs.repeat = repeat; // For indent in visual mode.
- operatorArgs.registerName = registerName;
- operatorArgs.linewise = linewise;
- var operatorMoveTo = operators[operator](
- cm, operatorArgs, cmSel.ranges, oldAnchor, newHead);
- if (vim.visualMode) {
- exitVisualMode(cm, operatorMoveTo != null);
- }
- if (operatorMoveTo) {
- cm.setCursor(operatorMoveTo);
- }
- }
- },
- recordLastEdit: function(vim, inputState, actionCommand) {
- var macroModeState = vimGlobalState.macroModeState;
- if (macroModeState.isPlaying) { return; }
- vim.lastEditInputState = inputState;
- vim.lastEditActionCommand = actionCommand;
- macroModeState.lastInsertModeChanges.changes = [];
- macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
- }
- };
- var motions = {
- moveToTopLine: function(cm, _head, motionArgs) {
- var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
- return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
- },
- moveToMiddleLine: function(cm) {
- var range = getUserVisibleLines(cm);
- var line = Math.floor((range.top + range.bottom) * 0.5);
- return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
- },
- moveToBottomLine: function(cm, _head, motionArgs) {
- var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
- return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
- },
- expandToLine: function(_cm, head, motionArgs) {
- var cur = head;
- return Pos(cur.line + motionArgs.repeat - 1, Infinity);
- },
- findNext: function(cm, _head, motionArgs) {
- var state = getSearchState(cm);
- var query = state.getQuery();
- if (!query) {
- return;
- }
- var prev = !motionArgs.forward;
- prev = (state.isReversed()) ? !prev : prev;
- highlightSearchMatches(cm, query);
- return findNext(cm, prev/** prev */, query, motionArgs.repeat);
- },
- goToMark: function(cm, _head, motionArgs, vim) {
- var mark = vim.marks[motionArgs.selectedCharacter];
- if (mark) {
- var pos = mark.find();
- return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos;
- }
- return null;
- },
- moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) {
- if (vim.visualBlock && motionArgs.sameLine) {
- var sel = vim.sel;
- return [
- clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)),
- clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch))
- ];
- } else {
- return ([vim.sel.head, vim.sel.anchor]);
- }
- },
- jumpToMark: function(cm, head, motionArgs, vim) {
- var best = head;
- for (var i = 0; i < motionArgs.repeat; i++) {
- var cursor = best;
- for (var key in vim.marks) {
- if (!isLowerCase(key)) {
- continue;
- }
- var mark = vim.marks[key].find();
- var isWrongDirection = (motionArgs.forward) ?
- cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
-
- if (isWrongDirection) {
- continue;
- }
- if (motionArgs.linewise && (mark.line == cursor.line)) {
- continue;
- }
-
- var equal = cursorEqual(cursor, best);
- var between = (motionArgs.forward) ?
- cursorIsBetween(cursor, mark, best) :
- cursorIsBetween(best, mark, cursor);
-
- if (equal || between) {
- best = mark;
- }
- }
- }
-
- if (motionArgs.linewise) {
- best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)));
- }
- return best;
- },
- moveByCharacters: function(_cm, head, motionArgs) {
- var cur = head;
- var repeat = motionArgs.repeat;
- var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
- return Pos(cur.line, ch);
- },
- moveByLines: function(cm, head, motionArgs, vim) {
- var cur = head;
- var endCh = cur.ch;
- switch (vim.lastMotion) {
- case this.moveByLines:
- case this.moveByDisplayLines:
- case this.moveByScroll:
- case this.moveToColumn:
- case this.moveToEol:
- endCh = vim.lastHPos;
- break;
- default:
- vim.lastHPos = endCh;
- }
- var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
- var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
- var first = cm.firstLine();
- var last = cm.lastLine();
- if ((line < first && cur.line == first) ||
- (line > last && cur.line == last)) {
- return;
- }
- var fold = cm.ace.session.getFoldLine(line);
- if (fold) {
- if (motionArgs.forward) {
- if (line > fold.start.row)
- line = fold.end.row + 1;
- } else {
- line = fold.start.row;
- }
- }
- if (motionArgs.toFirstChar){
- endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
- vim.lastHPos = endCh;
- }
- vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left;
- return Pos(line, endCh);
- },
- moveByDisplayLines: function(cm, head, motionArgs, vim) {
- var cur = head;
- switch (vim.lastMotion) {
- case this.moveByDisplayLines:
- case this.moveByScroll:
- case this.moveByLines:
- case this.moveToColumn:
- case this.moveToEol:
- break;
- default:
- vim.lastHSPos = cm.charCoords(cur,'div').left;
- }
- var repeat = motionArgs.repeat;
- var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
- if (res.hitSide) {
- if (motionArgs.forward) {
- var lastCharCoords = cm.charCoords(res, 'div');
- var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
- var res = cm.coordsChar(goalCoords, 'div');
- } else {
- var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div');
- resCoords.left = vim.lastHSPos;
- res = cm.coordsChar(resCoords, 'div');
- }
- }
- vim.lastHPos = res.ch;
- return res;
- },
- moveByPage: function(cm, head, motionArgs) {
- var curStart = head;
- var repeat = motionArgs.repeat;
- return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');
- },
- moveByParagraph: function(cm, head, motionArgs) {
- var dir = motionArgs.forward ? 1 : -1;
- return findParagraph(cm, head, motionArgs.repeat, dir);
- },
- moveByScroll: function(cm, head, motionArgs, vim) {
- var scrollbox = cm.getScrollInfo();
- var curEnd = null;
- var repeat = motionArgs.repeat;
- if (!repeat) {
- repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
- }
- var orig = cm.charCoords(head, 'local');
- motionArgs.repeat = repeat;
- var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim);
- if (!curEnd) {
- return null;
- }
- var dest = cm.charCoords(curEnd, 'local');
- cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
- return curEnd;
- },
- moveByWords: function(cm, head, motionArgs) {
- return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward,
- !!motionArgs.wordEnd, !!motionArgs.bigWord);
- },
- moveTillCharacter: function(cm, _head, motionArgs) {
- var repeat = motionArgs.repeat;
- var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
- motionArgs.selectedCharacter);
- var increment = motionArgs.forward ? -1 : 1;
- recordLastCharacterSearch(increment, motionArgs);
- if (!curEnd) return null;
- curEnd.ch += increment;
- return curEnd;
- },
- moveToCharacter: function(cm, head, motionArgs) {
- var repeat = motionArgs.repeat;
- recordLastCharacterSearch(0, motionArgs);
- return moveToCharacter(cm, repeat, motionArgs.forward,
- motionArgs.selectedCharacter) || head;
- },
- moveToSymbol: function(cm, head, motionArgs) {
- var repeat = motionArgs.repeat;
- return findSymbol(cm, repeat, motionArgs.forward,
- motionArgs.selectedCharacter) || head;
- },
- moveToColumn: function(cm, head, motionArgs, vim) {
- var repeat = motionArgs.repeat;
- vim.lastHPos = repeat - 1;
- vim.lastHSPos = cm.charCoords(head,'div').left;
- return moveToColumn(cm, repeat);
- },
- moveToEol: function(cm, head, motionArgs, vim) {
- var cur = head;
- vim.lastHPos = Infinity;
- var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity);
- var end=cm.clipPos(retval);
- end.ch--;
- vim.lastHSPos = cm.charCoords(end,'div').left;
- return retval;
- },
- moveToFirstNonWhiteSpaceCharacter: function(cm, head) {
- var cursor = head;
- return Pos(cursor.line,
- findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
- },
- moveToMatchedSymbol: function(cm, head) {
- var cursor = head;
- var line = cursor.line;
- var ch = cursor.ch;
- var lineText = cm.getLine(line);
- var symbol;
- do {
- symbol = lineText.charAt(ch++);
- if (symbol && isMatchableSymbol(symbol)) {
- var style = cm.getTokenTypeAt(Pos(line, ch));
- if (style !== "string" && style !== "comment") {
- break;
- }
- }
- } while (symbol);
- if (symbol) {
- var matched = cm.findMatchingBracket(Pos(line, ch));
- return matched.to;
- } else {
- return cursor;
- }
- },
- moveToStartOfLine: function(_cm, head) {
- return Pos(head.line, 0);
- },
- moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) {
- var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
- if (motionArgs.repeatIsExplicit) {
- lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
- }
- return Pos(lineNum,
- findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
- },
- textObjectManipulation: function(cm, head, motionArgs, vim) {
- var mirroredPairs = {'(': ')', ')': '(',
- '{': '}', '}': '{',
- '[': ']', ']': '['};
- var selfPaired = {'\'': true, '"': true};
-
- var character = motionArgs.selectedCharacter;
- if (character == 'b') {
- character = '(';
- } else if (character == 'B') {
- character = '{';
- }
- var inclusive = !motionArgs.textObjectInner;
-
- var tmp;
- if (mirroredPairs[character]) {
- tmp = selectCompanionObject(cm, head, character, inclusive);
- } else if (selfPaired[character]) {
- tmp = findBeginningAndEnd(cm, head, character, inclusive);
- } else if (character === 'W') {
- tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
- true /** bigWord */);
- } else if (character === 'w') {
- tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
- false /** bigWord */);
- } else if (character === 'p') {
- tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive);
- motionArgs.linewise = true;
- if (vim.visualMode) {
- if (!vim.visualLine) { vim.visualLine = true; }
- } else {
- var operatorArgs = vim.inputState.operatorArgs;
- if (operatorArgs) { operatorArgs.linewise = true; }
- tmp.end.line--;
- }
- } else {
- return null;
- }
-
- if (!cm.state.vim.visualMode) {
- return [tmp.start, tmp.end];
- } else {
- return expandSelection(cm, tmp.start, tmp.end);
- }
- },
-
- repeatLastCharacterSearch: function(cm, head, motionArgs) {
- var lastSearch = vimGlobalState.lastChararacterSearch;
- var repeat = motionArgs.repeat;
- var forward = motionArgs.forward === lastSearch.forward;
- var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
- cm.moveH(-increment, 'char');
- motionArgs.inclusive = forward ? true : false;
- var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
- if (!curEnd) {
- cm.moveH(increment, 'char');
- return head;
- }
- curEnd.ch += increment;
- return curEnd;
- }
- };
-
- function defineMotion(name, fn) {
- motions[name] = fn;
- }
-
- function fillArray(val, times) {
- var arr = [];
- for (var i = 0; i < times; i++) {
- arr.push(val);
- }
- return arr;
- }
- var operators = {
- change: function(cm, args, ranges) {
- var finalHead, text;
- var vim = cm.state.vim;
- vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock = vim.visualBlock;
- if (!vim.visualMode) {
- var anchor = ranges[0].anchor,
- head = ranges[0].head;
- text = cm.getRange(anchor, head);
- var lastState = vim.lastEditInputState || {};
- if (lastState.motion == "moveByWords" && !isWhiteSpaceString(text)) {
- var match = (/\s+$/).exec(text);
- if (match && lastState.motionArgs && lastState.motionArgs.forward) {
- head = offsetCursor(head, 0, - match[0].length);
- text = text.slice(0, - match[0].length);
- }
- }
- var prevLineEnd = new Pos(anchor.line - 1, Number.MAX_VALUE);
- var wasLastLine = cm.firstLine() == cm.lastLine();
- if (head.line > cm.lastLine() && args.linewise && !wasLastLine) {
- cm.replaceRange('', prevLineEnd, head);
- } else {
- cm.replaceRange('', anchor, head);
- }
- if (args.linewise) {
- if (!wasLastLine) {
- cm.setCursor(prevLineEnd);
- CodeMirror.commands.newlineAndIndent(cm);
- }
- anchor.ch = Number.MAX_VALUE;
- }
- finalHead = anchor;
- } else {
- text = cm.getSelection();
- var replacement = fillArray('', ranges.length);
- cm.replaceSelections(replacement);
- finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
- }
- vimGlobalState.registerController.pushText(
- args.registerName, 'change', text,
- args.linewise, ranges.length > 1);
- actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim);
- },
- 'delete': function(cm, args, ranges) {
- var finalHead, text;
- var vim = cm.state.vim;
- if (!vim.visualBlock) {
- var anchor = ranges[0].anchor,
- head = ranges[0].head;
- if (args.linewise &&
- head.line != cm.firstLine() &&
- anchor.line == cm.lastLine() &&
- anchor.line == head.line - 1) {
- if (anchor.line == cm.firstLine()) {
- anchor.ch = 0;
- } else {
- anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1));
- }
- }
- text = cm.getRange(anchor, head);
- cm.replaceRange('', anchor, head);
- finalHead = anchor;
- if (args.linewise) {
- finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor);
- }
- } else {
- text = cm.getSelection();
- var replacement = fillArray('', ranges.length);
- cm.replaceSelections(replacement);
- finalHead = ranges[0].anchor;
- }
- vimGlobalState.registerController.pushText(
- args.registerName, 'delete', text,
- args.linewise, vim.visualBlock);
- return clipCursorToContent(cm, finalHead);
- },
- indent: function(cm, args, ranges) {
- var vim = cm.state.vim;
- var startLine = ranges[0].anchor.line;
- var endLine = vim.visualBlock ?
- ranges[ranges.length - 1].anchor.line :
- ranges[0].head.line;
- var repeat = (vim.visualMode) ? args.repeat : 1;
- if (args.linewise) {
- endLine--;
- }
- for (var i = startLine; i <= endLine; i++) {
- for (var j = 0; j < repeat; j++) {
- cm.indentLine(i, args.indentRight);
- }
- }
- return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
- },
- changeCase: function(cm, args, ranges, oldAnchor, newHead) {
- var selections = cm.getSelections();
- var swapped = [];
- var toLower = args.toLower;
- for (var j = 0; j < selections.length; j++) {
- var toSwap = selections[j];
- var text = '';
- if (toLower === true) {
- text = toSwap.toLowerCase();
- } else if (toLower === false) {
- text = toSwap.toUpperCase();
- } else {
- for (var i = 0; i < toSwap.length; i++) {
- var character = toSwap.charAt(i);
- text += isUpperCase(character) ? character.toLowerCase() :
- character.toUpperCase();
- }
- }
- swapped.push(text);
- }
- cm.replaceSelections(swapped);
- if (args.shouldMoveCursor){
- return newHead;
- } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) {
- return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor);
- } else if (args.linewise){
- return oldAnchor;
- } else {
- return cursorMin(ranges[0].anchor, ranges[0].head);
- }
- },
- yank: function(cm, args, ranges, oldAnchor) {
- var vim = cm.state.vim;
- var text = cm.getSelection();
- var endPos = vim.visualMode
- ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor)
- : oldAnchor;
- vimGlobalState.registerController.pushText(
- args.registerName, 'yank',
- text, args.linewise, vim.visualBlock);
- return endPos;
- }
- };
-
- function defineOperator(name, fn) {
- operators[name] = fn;
- }
-
- var actions = {
- jumpListWalk: function(cm, actionArgs, vim) {
- if (vim.visualMode) {
- return;
- }
- var repeat = actionArgs.repeat;
- var forward = actionArgs.forward;
- var jumpList = vimGlobalState.jumpList;
-
- var mark = jumpList.move(cm, forward ? repeat : -repeat);
- var markPos = mark ? mark.find() : undefined;
- markPos = markPos ? markPos : cm.getCursor();
- cm.setCursor(markPos);
- cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch
- },
- scroll: function(cm, actionArgs, vim) {
- if (vim.visualMode) {
- return;
- }
- var repeat = actionArgs.repeat || 1;
- var lineHeight = cm.defaultTextHeight();
- var top = cm.getScrollInfo().top;
- var delta = lineHeight * repeat;
- var newPos = actionArgs.forward ? top + delta : top - delta;
- var cursor = copyCursor(cm.getCursor());
- var cursorCoords = cm.charCoords(cursor, 'local');
- if (actionArgs.forward) {
- if (newPos > cursorCoords.top) {
- cursor.line += (newPos - cursorCoords.top) / lineHeight;
- cursor.line = Math.ceil(cursor.line);
- cm.setCursor(cursor);
- cursorCoords = cm.charCoords(cursor, 'local');
- cm.scrollTo(null, cursorCoords.top);
- } else {
- cm.scrollTo(null, newPos);
- }
- } else {
- var newBottom = newPos + cm.getScrollInfo().clientHeight;
- if (newBottom < cursorCoords.bottom) {
- cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
- cursor.line = Math.floor(cursor.line);
- cm.setCursor(cursor);
- cursorCoords = cm.charCoords(cursor, 'local');
- cm.scrollTo(
- null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
- } else {
- cm.scrollTo(null, newPos);
- }
- }
- },
- scrollToCursor: function(cm, actionArgs) {
- var lineNum = cm.getCursor().line;
- var charCoords = cm.charCoords(Pos(lineNum, 0), 'local');
- var height = cm.getScrollInfo().clientHeight;
- var y = charCoords.top;
- var lineHeight = charCoords.bottom - y;
- switch (actionArgs.position) {
- case 'center': y = y - (height / 2) + lineHeight;
- break;
- case 'bottom': y = y - height + lineHeight*1.4;
- break;
- case 'top': y = y + lineHeight*0.4;
- break;
- }
- cm.scrollTo(null, y);
- },
- replayMacro: function(cm, actionArgs, vim) {
- var registerName = actionArgs.selectedCharacter;
- var repeat = actionArgs.repeat;
- var macroModeState = vimGlobalState.macroModeState;
- if (registerName == '@') {
- registerName = macroModeState.latestRegister;
- }
- while(repeat--){
- executeMacroRegister(cm, vim, macroModeState, registerName);
- }
- },
- enterMacroRecordMode: function(cm, actionArgs) {
- var macroModeState = vimGlobalState.macroModeState;
- var registerName = actionArgs.selectedCharacter;
- macroModeState.enterMacroRecordMode(cm, registerName);
- },
- enterInsertMode: function(cm, actionArgs, vim) {
- if (cm.getOption('readOnly')) { return; }
- vim.insertMode = true;
- vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
- var insertAt = (actionArgs) ? actionArgs.insertAt : null;
- var sel = vim.sel;
- var head = actionArgs.head || cm.getCursor('head');
- var height = cm.listSelections().length;
- if (insertAt == 'eol') {
- head = Pos(head.line, lineLength(cm, head.line));
- } else if (insertAt == 'charAfter') {
- head = offsetCursor(head, 0, 1);
- } else if (insertAt == 'firstNonBlank') {
- head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head);
- } else if (insertAt == 'startOfSelectedArea') {
- if (!vim.visualBlock) {
- if (sel.head.line < sel.anchor.line) {
- head = sel.head;
- } else {
- head = Pos(sel.anchor.line, 0);
- }
- } else {
- head = Pos(
- Math.min(sel.head.line, sel.anchor.line),
- Math.min(sel.head.ch, sel.anchor.ch));
- height = Math.abs(sel.head.line - sel.anchor.line) + 1;
- }
- } else if (insertAt == 'endOfSelectedArea') {
- if (!vim.visualBlock) {
- if (sel.head.line >= sel.anchor.line) {
- head = offsetCursor(sel.head, 0, 1);
- } else {
- head = Pos(sel.anchor.line, 0);
- }
- } else {
- head = Pos(
- Math.min(sel.head.line, sel.anchor.line),
- Math.max(sel.head.ch + 1, sel.anchor.ch));
- height = Math.abs(sel.head.line - sel.anchor.line) + 1;
- }
- } else if (insertAt == 'inplace') {
- if (vim.visualMode){
- return;
- }
- }
- cm.setOption('keyMap', 'vim-insert');
- cm.setOption('disableInput', false);
- if (actionArgs && actionArgs.replace) {
- cm.toggleOverwrite(true);
- cm.setOption('keyMap', 'vim-replace');
- CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
- } else {
- cm.setOption('keyMap', 'vim-insert');
- CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
- }
- if (!vimGlobalState.macroModeState.isPlaying) {
- cm.on('change', onChange);
- CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
- }
- if (vim.visualMode) {
- exitVisualMode(cm);
- }
- selectForInsert(cm, head, height);
- },
- toggleVisualMode: function(cm, actionArgs, vim) {
- var repeat = actionArgs.repeat;
- var anchor = cm.getCursor();
- var head;
- if (!vim.visualMode) {
- vim.visualMode = true;
- vim.visualLine = !!actionArgs.linewise;
- vim.visualBlock = !!actionArgs.blockwise;
- head = clipCursorToContent(
- cm, Pos(anchor.line, anchor.ch + repeat - 1),
- true /** includeLineBreak */);
- vim.sel = {
- anchor: anchor,
- head: head
- };
- CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
- updateCmSelection(cm);
- updateMark(cm, vim, '<', cursorMin(anchor, head));
- updateMark(cm, vim, '>', cursorMax(anchor, head));
- } else if (vim.visualLine ^ actionArgs.linewise ||
- vim.visualBlock ^ actionArgs.blockwise) {
- vim.visualLine = !!actionArgs.linewise;
- vim.visualBlock = !!actionArgs.blockwise;
- CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
- updateCmSelection(cm);
- } else {
- exitVisualMode(cm);
- }
- },
- reselectLastSelection: function(cm, _actionArgs, vim) {
- var lastSelection = vim.lastSelection;
- if (vim.visualMode) {
- updateLastSelection(cm, vim);
- }
- if (lastSelection) {
- var anchor = lastSelection.anchorMark.find();
- var head = lastSelection.headMark.find();
- if (!anchor || !head) {
- return;
- }
- vim.sel = {
- anchor: anchor,
- head: head
- };
- vim.visualMode = true;
- vim.visualLine = lastSelection.visualLine;
- vim.visualBlock = lastSelection.visualBlock;
- updateCmSelection(cm);
- updateMark(cm, vim, '<', cursorMin(anchor, head));
- updateMark(cm, vim, '>', cursorMax(anchor, head));
- CodeMirror.signal(cm, 'vim-mode-change', {
- mode: 'visual',
- subMode: vim.visualLine ? 'linewise' :
- vim.visualBlock ? 'blockwise' : ''});
- }
- },
- joinLines: function(cm, actionArgs, vim) {
- var curStart, curEnd;
- if (vim.visualMode) {
- curStart = cm.getCursor('anchor');
- curEnd = cm.getCursor('head');
- if (cursorIsBefore(curEnd, curStart)) {
- var tmp = curEnd;
- curEnd = curStart;
- curStart = tmp;
- }
- curEnd.ch = lineLength(cm, curEnd.line) - 1;
- } else {
- var repeat = Math.max(actionArgs.repeat, 2);
- curStart = cm.getCursor();
- curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1,
- Infinity));
- }
- var finalCh = 0;
- for (var i = curStart.line; i < curEnd.line; i++) {
- finalCh = lineLength(cm, curStart.line);
- var tmp = Pos(curStart.line + 1,
- lineLength(cm, curStart.line + 1));
- var text = cm.getRange(curStart, tmp);
- text = text.replace(/\n\s*/g, ' ');
- cm.replaceRange(text, curStart, tmp);
- }
- var curFinalPos = Pos(curStart.line, finalCh);
- if (vim.visualMode) {
- exitVisualMode(cm, false);
- }
- cm.setCursor(curFinalPos);
- },
- newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
- vim.insertMode = true;
- var insertAt = copyCursor(cm.getCursor());
- if (insertAt.line === cm.firstLine() && !actionArgs.after) {
- cm.replaceRange('\n', Pos(cm.firstLine(), 0));
- cm.setCursor(cm.firstLine(), 0);
- } else {
- insertAt.line = (actionArgs.after) ? insertAt.line :
- insertAt.line - 1;
- insertAt.ch = lineLength(cm, insertAt.line);
- cm.setCursor(insertAt);
- var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
- CodeMirror.commands.newlineAndIndent;
- newlineFn(cm);
- }
- this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
- },
- paste: function(cm, actionArgs, vim) {
- var cur = copyCursor(cm.getCursor());
- var register = vimGlobalState.registerController.getRegister(
- actionArgs.registerName);
- var text = register.toString();
- if (!text) {
- return;
- }
- if (actionArgs.matchIndent) {
- var tabSize = cm.getOption("tabSize");
- var whitespaceLength = function(str) {
- var tabs = (str.split("\t").length - 1);
- var spaces = (str.split(" ").length - 1);
- return tabs * tabSize + spaces * 1;
- };
- var currentLine = cm.getLine(cm.getCursor().line);
- var indent = whitespaceLength(currentLine.match(/^\s*/)[0]);
- var chompedText = text.replace(/\n$/, '');
- var wasChomped = text !== chompedText;
- var firstIndent = whitespaceLength(text.match(/^\s*/)[0]);
- var text = chompedText.replace(/^\s*/gm, function(wspace) {
- var newIndent = indent + (whitespaceLength(wspace) - firstIndent);
- if (newIndent < 0) {
- return "";
- }
- else if (cm.getOption("indentWithTabs")) {
- var quotient = Math.floor(newIndent / tabSize);
- return Array(quotient + 1).join('\t');
- }
- else {
- return Array(newIndent + 1).join(' ');
- }
- });
- text += wasChomped ? "\n" : "";
- }
- if (actionArgs.repeat > 1) {
- var text = Array(actionArgs.repeat + 1).join(text);
- }
- var linewise = register.linewise;
- var blockwise = register.blockwise;
- if (linewise && !blockwise) {
- if(vim.visualMode) {
- text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n';
- } else if (actionArgs.after) {
- text = '\n' + text.slice(0, text.length - 1);
- cur.ch = lineLength(cm, cur.line);
- } else {
- cur.ch = 0;
- }
- } else {
- if (blockwise) {
- text = text.split('\n');
- for (var i = 0; i < text.length; i++) {
- text[i] = (text[i] == '') ? ' ' : text[i];
- }
- }
- cur.ch += actionArgs.after ? 1 : 0;
- }
- var curPosFinal;
- var idx;
- if (vim.visualMode) {
- vim.lastPastedText = text;
- var lastSelectionCurEnd;
- var selectedArea = getSelectedAreaRange(cm, vim);
- var selectionStart = selectedArea[0];
- var selectionEnd = selectedArea[1];
- var selectedText = cm.getSelection();
- var selections = cm.listSelections();
- var emptyStrings = new Array(selections.length).join('1').split('1');
- if (vim.lastSelection) {
- lastSelectionCurEnd = vim.lastSelection.headMark.find();
- }
- vimGlobalState.registerController.unnamedRegister.setText(selectedText);
- if (blockwise) {
- cm.replaceSelections(emptyStrings);
- selectionEnd = Pos(selectionStart.line + text.length-1, selectionStart.ch);
- cm.setCursor(selectionStart);
- selectBlock(cm, selectionEnd);
- cm.replaceSelections(text);
- curPosFinal = selectionStart;
- } else if (vim.visualBlock) {
- cm.replaceSelections(emptyStrings);
- cm.setCursor(selectionStart);
- cm.replaceRange(text, selectionStart, selectionStart);
- curPosFinal = selectionStart;
- } else {
- cm.replaceRange(text, selectionStart, selectionEnd);
- curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1);
- }
- if(lastSelectionCurEnd) {
- vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd);
- }
- if (linewise) {
- curPosFinal.ch=0;
- }
- } else {
- if (blockwise) {
- cm.setCursor(cur);
- for (var i = 0; i < text.length; i++) {
- var line = cur.line+i;
- if (line > cm.lastLine()) {
- cm.replaceRange('\n', Pos(line, 0));
- }
- var lastCh = lineLength(cm, line);
- if (lastCh < cur.ch) {
- extendLineToColumn(cm, line, cur.ch);
- }
- }
- cm.setCursor(cur);
- selectBlock(cm, Pos(cur.line + text.length-1, cur.ch));
- cm.replaceSelections(text);
- curPosFinal = cur;
- } else {
- cm.replaceRange(text, cur);
- if (linewise && actionArgs.after) {
- curPosFinal = Pos(
- cur.line + 1,
- findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)));
- } else if (linewise && !actionArgs.after) {
- curPosFinal = Pos(
- cur.line,
- findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)));
- } else if (!linewise && actionArgs.after) {
- idx = cm.indexFromPos(cur);
- curPosFinal = cm.posFromIndex(idx + text.length - 1);
- } else {
- idx = cm.indexFromPos(cur);
- curPosFinal = cm.posFromIndex(idx + text.length);
- }
- }
- }
- if (vim.visualMode) {
- exitVisualMode(cm, false);
- }
- cm.setCursor(curPosFinal);
- },
- undo: function(cm, actionArgs) {
- cm.operation(function() {
- repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
- cm.setCursor(cm.getCursor('anchor'));
- });
- },
- redo: function(cm, actionArgs) {
- repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
- },
- setRegister: function(_cm, actionArgs, vim) {
- vim.inputState.registerName = actionArgs.selectedCharacter;
- },
- setMark: function(cm, actionArgs, vim) {
- var markName = actionArgs.selectedCharacter;
- updateMark(cm, vim, markName, cm.getCursor());
- },
- replace: function(cm, actionArgs, vim) {
- var replaceWith = actionArgs.selectedCharacter;
- var curStart = cm.getCursor();
- var replaceTo;
- var curEnd;
- var selections = cm.listSelections();
- if (vim.visualMode) {
- curStart = cm.getCursor('start');
- curEnd = cm.getCursor('end');
- } else {
- var line = cm.getLine(curStart.line);
- replaceTo = curStart.ch + actionArgs.repeat;
- if (replaceTo > line.length) {
- replaceTo=line.length;
- }
- curEnd = Pos(curStart.line, replaceTo);
- }
- if (replaceWith=='\n') {
- if (!vim.visualMode) cm.replaceRange('', curStart, curEnd);
- (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
- } else {
- var replaceWithStr = cm.getRange(curStart, curEnd);
- replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith);
- if (vim.visualBlock) {
- var spaces = new Array(cm.getOption("tabSize")+1).join(' ');
- replaceWithStr = cm.getSelection();
- replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n');
- cm.replaceSelections(replaceWithStr);
- } else {
- cm.replaceRange(replaceWithStr, curStart, curEnd);
- }
- if (vim.visualMode) {
- curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ?
- selections[0].anchor : selections[0].head;
- cm.setCursor(curStart);
- exitVisualMode(cm, false);
- } else {
- cm.setCursor(offsetCursor(curEnd, 0, -1));
- }
- }
- },
- incrementNumberToken: function(cm, actionArgs) {
- var cur = cm.getCursor();
- var lineStr = cm.getLine(cur.line);
- var re = /-?\d+/g;
- var match;
- var start;
- var end;
- var numberStr;
- var token;
- while ((match = re.exec(lineStr)) !== null) {
- token = match[0];
- start = match.index;
- end = start + token.length;
- if (cur.ch < end)break;
- }
- if (!actionArgs.backtrack && (end <= cur.ch))return;
- if (token) {
- var increment = actionArgs.increase ? 1 : -1;
- var number = parseInt(token) + (increment * actionArgs.repeat);
- var from = Pos(cur.line, start);
- var to = Pos(cur.line, end);
- numberStr = number.toString();
- cm.replaceRange(numberStr, from, to);
- } else {
- return;
- }
- cm.setCursor(Pos(cur.line, start + numberStr.length - 1));
- },
- repeatLastEdit: function(cm, actionArgs, vim) {
- var lastEditInputState = vim.lastEditInputState;
- if (!lastEditInputState) { return; }
- var repeat = actionArgs.repeat;
- if (repeat && actionArgs.repeatIsExplicit) {
- vim.lastEditInputState.repeatOverride = repeat;
- } else {
- repeat = vim.lastEditInputState.repeatOverride || repeat;
- }
- repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
- },
- exitInsertMode: exitInsertMode
- };
-
- function defineAction(name, fn) {
- actions[name] = fn;
- }
- function clipCursorToContent(cm, cur, includeLineBreak) {
- var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
- var maxCh = lineLength(cm, line) - 1;
- maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;
- var ch = Math.min(Math.max(0, cur.ch), maxCh);
- return Pos(line, ch);
- }
- function copyArgs(args) {
- var ret = {};
- for (var prop in args) {
- if (args.hasOwnProperty(prop)) {
- ret[prop] = args[prop];
- }
- }
- return ret;
- }
- function offsetCursor(cur, offsetLine, offsetCh) {
- if (typeof offsetLine === 'object') {
- offsetCh = offsetLine.ch;
- offsetLine = offsetLine.line;
- }
- return Pos(cur.line + offsetLine, cur.ch + offsetCh);
- }
- function getOffset(anchor, head) {
- return {
- line: head.line - anchor.line,
- ch: head.line - anchor.line
- };
- }
- function commandMatches(keys, keyMap, context, inputState) {
- var match, partial = [], full = [];
- for (var i = 0; i < keyMap.length; i++) {
- var command = keyMap[i];
- if (context == 'insert' && command.context != 'insert' ||
- command.context && command.context != context ||
- inputState.operator && command.type == 'action' ||
- !(match = commandMatch(keys, command.keys))) { continue; }
- if (match == 'partial') { partial.push(command); }
- if (match == 'full') { full.push(command); }
- }
- return {
- partial: partial.length && partial,
- full: full.length && full
- };
- }
- function commandMatch(pressed, mapped) {
- if (mapped.slice(-11) == '') {
- var prefixLen = mapped.length - 11;
- var pressedPrefix = pressed.slice(0, prefixLen);
- var mappedPrefix = mapped.slice(0, prefixLen);
- return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' :
- mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false;
- } else {
- return pressed == mapped ? 'full' :
- mapped.indexOf(pressed) == 0 ? 'partial' : false;
- }
- }
- function lastChar(keys) {
- var match = /^.*(<[\w\-]+>)$/.exec(keys);
- var selectedCharacter = match ? match[1] : keys.slice(-1);
- if (selectedCharacter.length > 1){
- switch(selectedCharacter){
- case '':
- selectedCharacter='\n';
- break;
- case '':
- selectedCharacter=' ';
- break;
- default:
- break;
- }
- }
- return selectedCharacter;
- }
- function repeatFn(cm, fn, repeat) {
- return function() {
- for (var i = 0; i < repeat; i++) {
- fn(cm);
- }
- };
- }
- function copyCursor(cur) {
- return Pos(cur.line, cur.ch);
- }
- function cursorEqual(cur1, cur2) {
- return cur1.ch == cur2.ch && cur1.line == cur2.line;
- }
- function cursorIsBefore(cur1, cur2) {
- if (cur1.line < cur2.line) {
- return true;
- }
- if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
- return true;
- }
- return false;
- }
- function cursorMin(cur1, cur2) {
- if (arguments.length > 2) {
- cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1));
- }
- return cursorIsBefore(cur1, cur2) ? cur1 : cur2;
- }
- function cursorMax(cur1, cur2) {
- if (arguments.length > 2) {
- cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1));
- }
- return cursorIsBefore(cur1, cur2) ? cur2 : cur1;
- }
- function cursorIsBetween(cur1, cur2, cur3) {
- var cur1before2 = cursorIsBefore(cur1, cur2);
- var cur2before3 = cursorIsBefore(cur2, cur3);
- return cur1before2 && cur2before3;
- }
- function lineLength(cm, lineNum) {
- return cm.getLine(lineNum).length;
- }
- function trim(s) {
- if (s.trim) {
- return s.trim();
- }
- return s.replace(/^\s+|\s+$/g, '');
- }
- function escapeRegex(s) {
- return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
- }
- function extendLineToColumn(cm, lineNum, column) {
- var endCh = lineLength(cm, lineNum);
- var spaces = new Array(column-endCh+1).join(' ');
- cm.setCursor(Pos(lineNum, endCh));
- cm.replaceRange(spaces, cm.getCursor());
- }
- function selectBlock(cm, selectionEnd) {
- var selections = [], ranges = cm.listSelections();
- var head = copyCursor(cm.clipPos(selectionEnd));
- var isClipped = !cursorEqual(selectionEnd, head);
- var curHead = cm.getCursor('head');
- var primIndex = getIndex(ranges, curHead);
- var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor);
- var max = ranges.length - 1;
- var index = max - primIndex > primIndex ? max : 0;
- var base = ranges[index].anchor;
-
- var firstLine = Math.min(base.line, head.line);
- var lastLine = Math.max(base.line, head.line);
- var baseCh = base.ch, headCh = head.ch;
-
- var dir = ranges[index].head.ch - baseCh;
- var newDir = headCh - baseCh;
- if (dir > 0 && newDir <= 0) {
- baseCh++;
- if (!isClipped) { headCh--; }
- } else if (dir < 0 && newDir >= 0) {
- baseCh--;
- if (!wasClipped) { headCh++; }
- } else if (dir < 0 && newDir == -1) {
- baseCh--;
- headCh++;
- }
- for (var line = firstLine; line <= lastLine; line++) {
- var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)};
- selections.push(range);
- }
- primIndex = head.line == lastLine ? selections.length - 1 : 0;
- cm.setSelections(selections);
- selectionEnd.ch = headCh;
- base.ch = baseCh;
- return base;
- }
- function selectForInsert(cm, head, height) {
- var sel = [];
- for (var i = 0; i < height; i++) {
- var lineHead = offsetCursor(head, i, 0);
- sel.push({anchor: lineHead, head: lineHead});
- }
- cm.setSelections(sel, 0);
- }
- function getIndex(ranges, cursor, end) {
- for (var i = 0; i < ranges.length; i++) {
- var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor);
- var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor);
- if (atAnchor || atHead) {
- return i;
- }
- }
- return -1;
- }
- function getSelectedAreaRange(cm, vim) {
- var lastSelection = vim.lastSelection;
- var getCurrentSelectedAreaRange = function() {
- var selections = cm.listSelections();
- var start = selections[0];
- var end = selections[selections.length-1];
- var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;
- var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;
- return [selectionStart, selectionEnd];
- };
- var getLastSelectedAreaRange = function() {
- var selectionStart = cm.getCursor();
- var selectionEnd = cm.getCursor();
- var block = lastSelection.visualBlock;
- if (block) {
- var width = block.width;
- var height = block.height;
- selectionEnd = Pos(selectionStart.line + height, selectionStart.ch + width);
- var selections = [];
- for (var i = selectionStart.line; i < selectionEnd.line; i++) {
- var anchor = Pos(i, selectionStart.ch);
- var head = Pos(i, selectionEnd.ch);
- var range = {anchor: anchor, head: head};
- selections.push(range);
- }
- cm.setSelections(selections);
- } else {
- var start = lastSelection.anchorMark.find();
- var end = lastSelection.headMark.find();
- var line = end.line - start.line;
- var ch = end.ch - start.ch;
- selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch};
- if (lastSelection.visualLine) {
- selectionStart = Pos(selectionStart.line, 0);
- selectionEnd = Pos(selectionEnd.line, lineLength(cm, selectionEnd.line));
- }
- cm.setSelection(selectionStart, selectionEnd);
- }
- return [selectionStart, selectionEnd];
- };
- if (!vim.visualMode) {
- return getLastSelectedAreaRange();
- } else {
- return getCurrentSelectedAreaRange();
- }
- }
- function updateLastSelection(cm, vim) {
- var anchor = vim.sel.anchor;
- var head = vim.sel.head;
- if (vim.lastPastedText) {
- head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length);
- vim.lastPastedText = null;
- }
- vim.lastSelection = {'anchorMark': cm.setBookmark(anchor),
- 'headMark': cm.setBookmark(head),
- 'anchor': copyCursor(anchor),
- 'head': copyCursor(head),
- 'visualMode': vim.visualMode,
- 'visualLine': vim.visualLine,
- 'visualBlock': vim.visualBlock};
- }
- function expandSelection(cm, start, end) {
- var sel = cm.state.vim.sel;
- var head = sel.head;
- var anchor = sel.anchor;
- var tmp;
- if (cursorIsBefore(end, start)) {
- tmp = end;
- end = start;
- start = tmp;
- }
- if (cursorIsBefore(head, anchor)) {
- head = cursorMin(start, head);
- anchor = cursorMax(anchor, end);
- } else {
- anchor = cursorMin(start, anchor);
- head = cursorMax(head, end);
- head = offsetCursor(head, 0, -1);
- if (head.ch == -1 && head.line != cm.firstLine()) {
- head = Pos(head.line - 1, lineLength(cm, head.line - 1));
- }
- }
- return [anchor, head];
- }
- function updateCmSelection(cm, sel, mode) {
- var vim = cm.state.vim;
- sel = sel || vim.sel;
- var mode = mode ||
- vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char';
- var cmSel = makeCmSelection(cm, sel, mode);
- cm.setSelections(cmSel.ranges, cmSel.primary);
- updateFakeCursor(cm);
- }
- function makeCmSelection(cm, sel, mode, exclusive) {
- var head = copyCursor(sel.head);
- var anchor = copyCursor(sel.anchor);
- if (mode == 'char') {
- var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
- var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
- head = offsetCursor(sel.head, 0, headOffset);
- anchor = offsetCursor(sel.anchor, 0, anchorOffset);
- return {
- ranges: [{anchor: anchor, head: head}],
- primary: 0
- };
- } else if (mode == 'line') {
- if (!cursorIsBefore(sel.head, sel.anchor)) {
- anchor.ch = 0;
-
- var lastLine = cm.lastLine();
- if (head.line > lastLine) {
- head.line = lastLine;
- }
- head.ch = lineLength(cm, head.line);
- } else {
- head.ch = 0;
- anchor.ch = lineLength(cm, anchor.line);
- }
- return {
- ranges: [{anchor: anchor, head: head}],
- primary: 0
- };
- } else if (mode == 'block') {
- var top = Math.min(anchor.line, head.line),
- left = Math.min(anchor.ch, head.ch),
- bottom = Math.max(anchor.line, head.line),
- right = Math.max(anchor.ch, head.ch) + 1;
- var height = bottom - top + 1;
- var primary = head.line == top ? 0 : height - 1;
- var ranges = [];
- for (var i = 0; i < height; i++) {
- ranges.push({
- anchor: Pos(top + i, left),
- head: Pos(top + i, right)
- });
- }
- return {
- ranges: ranges,
- primary: primary
- };
- }
- }
- function getHead(cm) {
- var cur = cm.getCursor('head');
- if (cm.getSelection().length == 1) {
- cur = cursorMin(cur, cm.getCursor('anchor'));
- }
- return cur;
- }
- function exitVisualMode(cm, moveHead) {
- var vim = cm.state.vim;
- if (moveHead !== false) {
- cm.setCursor(clipCursorToContent(cm, vim.sel.head));
- }
- updateLastSelection(cm, vim);
- vim.visualMode = false;
- vim.visualLine = false;
- vim.visualBlock = false;
- CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
- if (vim.fakeCursor) {
- vim.fakeCursor.clear();
- }
- }
- function clipToLine(cm, curStart, curEnd) {
- var selection = cm.getRange(curStart, curEnd);
- if (/\n\s*$/.test(selection)) {
- var lines = selection.split('\n');
- lines.pop();
- var line;
- for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
- curEnd.line--;
- curEnd.ch = 0;
- }
- if (line) {
- curEnd.line--;
- curEnd.ch = lineLength(cm, curEnd.line);
- } else {
- curEnd.ch = 0;
- }
- }
- }
- function expandSelectionToLine(_cm, curStart, curEnd) {
- curStart.ch = 0;
- curEnd.ch = 0;
- curEnd.line++;
- }
-
- function findFirstNonWhiteSpaceCharacter(text) {
- if (!text) {
- return 0;
- }
- var firstNonWS = text.search(/\S/);
- return firstNonWS == -1 ? text.length : firstNonWS;
- }
-
- function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
- var cur = getHead(cm);
- var line = cm.getLine(cur.line);
- var idx = cur.ch;
- var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0];
- while (!test(line.charAt(idx))) {
- idx++;
- if (idx >= line.length) { return null; }
- }
-
- if (bigWord) {
- test = bigWordCharTest[0];
- } else {
- test = wordCharTest[0];
- if (!test(line.charAt(idx))) {
- test = wordCharTest[1];
- }
- }
-
- var end = idx, start = idx;
- while (test(line.charAt(end)) && end < line.length) { end++; }
- while (test(line.charAt(start)) && start >= 0) { start--; }
- start++;
-
- if (inclusive) {
- var wordEnd = end;
- while (/\s/.test(line.charAt(end)) && end < line.length) { end++; }
- if (wordEnd == end) {
- var wordStart = start;
- while (/\s/.test(line.charAt(start - 1)) && start > 0) { start--; }
- if (!start) { start = wordStart; }
- }
- }
- return { start: Pos(cur.line, start), end: Pos(cur.line, end) };
- }
-
- function recordJumpPosition(cm, oldCur, newCur) {
- if (!cursorEqual(oldCur, newCur)) {
- vimGlobalState.jumpList.add(cm, oldCur, newCur);
- }
- }
-
- function recordLastCharacterSearch(increment, args) {
- vimGlobalState.lastChararacterSearch.increment = increment;
- vimGlobalState.lastChararacterSearch.forward = args.forward;
- vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter;
- }
-
- var symbolToMode = {
- '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
- '[': 'section', ']': 'section',
- '*': 'comment', '/': 'comment',
- 'm': 'method', 'M': 'method',
- '#': 'preprocess'
- };
- var findSymbolModes = {
- bracket: {
- isComplete: function(state) {
- if (state.nextCh === state.symb) {
- state.depth++;
- if (state.depth >= 1)return true;
- } else if (state.nextCh === state.reverseSymb) {
- state.depth--;
- }
- return false;
- }
- },
- section: {
- init: function(state) {
- state.curMoveThrough = true;
- state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
- },
- isComplete: function(state) {
- return state.index === 0 && state.nextCh === state.symb;
- }
- },
- comment: {
- isComplete: function(state) {
- var found = state.lastCh === '*' && state.nextCh === '/';
- state.lastCh = state.nextCh;
- return found;
- }
- },
- method: {
- init: function(state) {
- state.symb = (state.symb === 'm' ? '{' : '}');
- state.reverseSymb = state.symb === '{' ? '}' : '{';
- },
- isComplete: function(state) {
- if (state.nextCh === state.symb)return true;
- return false;
- }
- },
- preprocess: {
- init: function(state) {
- state.index = 0;
- },
- isComplete: function(state) {
- if (state.nextCh === '#') {
- var token = state.lineText.match(/#(\w+)/)[1];
- if (token === 'endif') {
- if (state.forward && state.depth === 0) {
- return true;
- }
- state.depth++;
- } else if (token === 'if') {
- if (!state.forward && state.depth === 0) {
- return true;
- }
- state.depth--;
- }
- if (token === 'else' && state.depth === 0)return true;
- }
- return false;
- }
- }
- };
- function findSymbol(cm, repeat, forward, symb) {
- var cur = copyCursor(cm.getCursor());
- var increment = forward ? 1 : -1;
- var endLine = forward ? cm.lineCount() : -1;
- var curCh = cur.ch;
- var line = cur.line;
- var lineText = cm.getLine(line);
- var state = {
- lineText: lineText,
- nextCh: lineText.charAt(curCh),
- lastCh: null,
- index: curCh,
- symb: symb,
- reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
- forward: forward,
- depth: 0,
- curMoveThrough: false
- };
- var mode = symbolToMode[symb];
- if (!mode)return cur;
- var init = findSymbolModes[mode].init;
- var isComplete = findSymbolModes[mode].isComplete;
- if (init) { init(state); }
- while (line !== endLine && repeat) {
- state.index += increment;
- state.nextCh = state.lineText.charAt(state.index);
- if (!state.nextCh) {
- line += increment;
- state.lineText = cm.getLine(line) || '';
- if (increment > 0) {
- state.index = 0;
- } else {
- var lineLen = state.lineText.length;
- state.index = (lineLen > 0) ? (lineLen-1) : 0;
- }
- state.nextCh = state.lineText.charAt(state.index);
- }
- if (isComplete(state)) {
- cur.line = line;
- cur.ch = state.index;
- repeat--;
- }
- }
- if (state.nextCh || state.curMoveThrough) {
- return Pos(line, state.index);
- }
- return cur;
- }
- function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
- var lineNum = cur.line;
- var pos = cur.ch;
- var line = cm.getLine(lineNum);
- var dir = forward ? 1 : -1;
- var charTests = bigWord ? bigWordCharTest: wordCharTest;
-
- if (emptyLineIsWord && line == '') {
- lineNum += dir;
- line = cm.getLine(lineNum);
- if (!isLine(cm, lineNum)) {
- return null;
- }
- pos = (forward) ? 0 : line.length;
- }
-
- while (true) {
- if (emptyLineIsWord && line == '') {
- return { from: 0, to: 0, line: lineNum };
- }
- var stop = (dir > 0) ? line.length : -1;
- var wordStart = stop, wordEnd = stop;
- while (pos != stop) {
- var foundWord = false;
- for (var i = 0; i < charTests.length && !foundWord; ++i) {
- if (charTests[i](line.charAt(pos))) {
- wordStart = pos;
- while (pos != stop && charTests[i](line.charAt(pos))) {
- pos += dir;
- }
- wordEnd = pos;
- foundWord = wordStart != wordEnd;
- if (wordStart == cur.ch && lineNum == cur.line &&
- wordEnd == wordStart + dir) {
- continue;
- } else {
- return {
- from: Math.min(wordStart, wordEnd + 1),
- to: Math.max(wordStart, wordEnd),
- line: lineNum };
- }
- }
- }
- if (!foundWord) {
- pos += dir;
- }
- }
- lineNum += dir;
- if (!isLine(cm, lineNum)) {
- return null;
- }
- line = cm.getLine(lineNum);
- pos = (dir > 0) ? 0 : line.length;
- }
- throw new Error('The impossible happened.');
- }
- function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) {
- var curStart = copyCursor(cur);
- var words = [];
- if (forward && !wordEnd || !forward && wordEnd) {
- repeat++;
- }
- var emptyLineIsWord = !(forward && wordEnd);
- for (var i = 0; i < repeat; i++) {
- var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
- if (!word) {
- var eodCh = lineLength(cm, cm.lastLine());
- words.push(forward
- ? {line: cm.lastLine(), from: eodCh, to: eodCh}
- : {line: 0, from: 0, to: 0});
- break;
- }
- words.push(word);
- cur = Pos(word.line, forward ? (word.to - 1) : word.from);
- }
- var shortCircuit = words.length != repeat;
- var firstWord = words[0];
- var lastWord = words.pop();
- if (forward && !wordEnd) {
- if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
- lastWord = words.pop();
- }
- return Pos(lastWord.line, lastWord.from);
- } else if (forward && wordEnd) {
- return Pos(lastWord.line, lastWord.to - 1);
- } else if (!forward && wordEnd) {
- if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
- lastWord = words.pop();
- }
- return Pos(lastWord.line, lastWord.to);
- } else {
- return Pos(lastWord.line, lastWord.from);
- }
- }
-
- function moveToCharacter(cm, repeat, forward, character) {
- var cur = cm.getCursor();
- var start = cur.ch;
- var idx;
- for (var i = 0; i < repeat; i ++) {
- var line = cm.getLine(cur.line);
- idx = charIdxInLine(start, line, character, forward, true);
- if (idx == -1) {
- return null;
- }
- start = idx;
- }
- return Pos(cm.getCursor().line, idx);
- }
-
- function moveToColumn(cm, repeat) {
- var line = cm.getCursor().line;
- return clipCursorToContent(cm, Pos(line, repeat - 1));
- }
-
- function updateMark(cm, vim, markName, pos) {
- if (!inArray(markName, validMarks)) {
- return;
- }
- if (vim.marks[markName]) {
- vim.marks[markName].clear();
- }
- vim.marks[markName] = cm.setBookmark(pos);
- }
-
- function charIdxInLine(start, line, character, forward, includeChar) {
- var idx;
- if (forward) {
- idx = line.indexOf(character, start + 1);
- if (idx != -1 && !includeChar) {
- idx -= 1;
- }
- } else {
- idx = line.lastIndexOf(character, start - 1);
- if (idx != -1 && !includeChar) {
- idx += 1;
- }
- }
- return idx;
- }
-
- function findParagraph(cm, head, repeat, dir, inclusive) {
- var line = head.line;
- var min = cm.firstLine();
- var max = cm.lastLine();
- var start, end, i = line;
- function isEmpty(i) { return !/\S/.test(cm.getLine(i)); } // ace_patch
- function isBoundary(i, dir, any) {
- if (any) { return isEmpty(i) != isEmpty(i + dir); }
- return !isEmpty(i) && isEmpty(i + dir);
- }
- function skipFold(i) {
- dir = dir > 0 ? 1 : -1;
- var foldLine = cm.ace.session.getFoldLine(i);
- if (foldLine) {
- if (i + dir > foldLine.start.row && i + dir < foldLine.end.row)
- dir = (dir > 0 ? foldLine.end.row : foldLine.start.row) - i;
- }
- }
- if (dir) {
- while (min <= i && i <= max && repeat > 0) {
- skipFold(i);
- if (isBoundary(i, dir)) { repeat--; }
- i += dir;
- }
- return new Pos(i, 0);
- }
-
- var vim = cm.state.vim;
- if (vim.visualLine && isBoundary(line, 1, true)) {
- var anchor = vim.sel.anchor;
- if (isBoundary(anchor.line, -1, true)) {
- if (!inclusive || anchor.line != line) {
- line += 1;
- }
- }
- }
- var startState = isEmpty(line);
- for (i = line; i <= max && repeat; i++) {
- if (isBoundary(i, 1, true)) {
- if (!inclusive || isEmpty(i) != startState) {
- repeat--;
- }
- }
- }
- end = new Pos(i, 0);
- if (i > max && !startState) { startState = true; }
- else { inclusive = false; }
- for (i = line; i > min; i--) {
- if (!inclusive || isEmpty(i) == startState || i == line) {
- if (isBoundary(i, -1, true)) { break; }
- }
- }
- start = new Pos(i, 0);
- return { start: start, end: end };
- }
- function selectCompanionObject(cm, head, symb, inclusive) {
- var cur = head, start, end;
-
- var bracketRegexp = ({
- '(': /[()]/, ')': /[()]/,
- '[': /[[\]]/, ']': /[[\]]/,
- '{': /[{}]/, '}': /[{}]/})[symb];
- var openSym = ({
- '(': '(', ')': '(',
- '[': '[', ']': '[',
- '{': '{', '}': '{'})[symb];
- var curChar = cm.getLine(cur.line).charAt(cur.ch);
- var offset = curChar === openSym ? 1 : 0;
-
- start = cm.scanForBracket(Pos(cur.line, cur.ch + offset), -1, null, {'bracketRegex': bracketRegexp});
- end = cm.scanForBracket(Pos(cur.line, cur.ch + offset), 1, null, {'bracketRegex': bracketRegexp});
-
- if (!start || !end) {
- return { start: cur, end: cur };
- }
-
- start = start.pos;
- end = end.pos;
-
- if ((start.line == end.line && start.ch > end.ch)
- || (start.line > end.line)) {
- var tmp = start;
- start = end;
- end = tmp;
- }
-
- if (inclusive) {
- end.ch += 1;
- } else {
- start.ch += 1;
- }
-
- return { start: start, end: end };
- }
- function findBeginningAndEnd(cm, head, symb, inclusive) {
- var cur = copyCursor(head);
- var line = cm.getLine(cur.line);
- var chars = line.split('');
- var start, end, i, len;
- var firstIndex = chars.indexOf(symb);
- if (cur.ch < firstIndex) {
- cur.ch = firstIndex;
- }
- else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
- end = cur.ch; // assign end to the current cursor
- --cur.ch; // make sure to look backwards
- }
- if (chars[cur.ch] == symb && !end) {
- start = cur.ch + 1; // assign start to ahead of the cursor
- } else {
- for (i = cur.ch; i > -1 && !start; i--) {
- if (chars[i] == symb) {
- start = i + 1;
- }
- }
- }
- if (start && !end) {
- for (i = start, len = chars.length; i < len && !end; i++) {
- if (chars[i] == symb) {
- end = i;
- }
- }
- }
- if (!start || !end) {
- return { start: cur, end: cur };
- }
- if (inclusive) {
- --start; ++end;
- }
-
- return {
- start: Pos(cur.line, start),
- end: Pos(cur.line, end)
- };
- }
- defineOption('pcre', true, 'boolean');
- function SearchState() {}
- SearchState.prototype = {
- getQuery: function() {
- return vimGlobalState.query;
- },
- setQuery: function(query) {
- vimGlobalState.query = query;
- },
- getOverlay: function() {
- return this.searchOverlay;
- },
- setOverlay: function(overlay) {
- this.searchOverlay = overlay;
- },
- isReversed: function() {
- return vimGlobalState.isReversed;
- },
- setReversed: function(reversed) {
- vimGlobalState.isReversed = reversed;
- },
- getScrollbarAnnotate: function() {
- return this.annotate;
- },
- setScrollbarAnnotate: function(annotate) {
- this.annotate = annotate;
- }
- };
- function getSearchState(cm) {
- var vim = cm.state.vim;
- return vim.searchState_ || (vim.searchState_ = new SearchState());
- }
- function dialog(cm, template, shortText, onClose, options) {
- if (cm.openDialog) {
- cm.openDialog(template, onClose, { bottom: true, value: options.value,
- onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp,
- selectValueOnOpen: false});
- }
- else {
- onClose(prompt(shortText, ''));
- }
- }
- function splitBySlash(argString) {
- var slashes = findUnescapedSlashes(argString) || [];
- if (!slashes.length) return [];
- var tokens = [];
- if (slashes[0] !== 0) return;
- for (var i = 0; i < slashes.length; i++) {
- if (typeof slashes[i] == 'number')
- tokens.push(argString.substring(slashes[i] + 1, slashes[i+1]));
- }
- return tokens;
- }
-
- function findUnescapedSlashes(str) {
- var escapeNextChar = false;
- var slashes = [];
- for (var i = 0; i < str.length; i++) {
- var c = str.charAt(i);
- if (!escapeNextChar && c == '/') {
- slashes.push(i);
- }
- escapeNextChar = !escapeNextChar && (c == '\\');
- }
- return slashes;
- }
- function translateRegex(str) {
- var specials = '|(){';
- var unescape = '}';
- var escapeNextChar = false;
- var out = [];
- for (var i = -1; i < str.length; i++) {
- var c = str.charAt(i) || '';
- var n = str.charAt(i+1) || '';
- var specialComesNext = (n && specials.indexOf(n) != -1);
- if (escapeNextChar) {
- if (c !== '\\' || !specialComesNext) {
- out.push(c);
- }
- escapeNextChar = false;
- } else {
- if (c === '\\') {
- escapeNextChar = true;
- if (n && unescape.indexOf(n) != -1) {
- specialComesNext = true;
- }
- if (!specialComesNext || n === '\\') {
- out.push(c);
- }
- } else {
- out.push(c);
- if (specialComesNext && n !== '\\') {
- out.push('\\');
- }
- }
- }
- }
- return out.join('');
- }
- var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'};
- function translateRegexReplace(str) {
- var escapeNextChar = false;
- var out = [];
- for (var i = -1; i < str.length; i++) {
- var c = str.charAt(i) || '';
- var n = str.charAt(i+1) || '';
- if (charUnescapes[c + n]) {
- out.push(charUnescapes[c+n]);
- i++;
- } else if (escapeNextChar) {
- out.push(c);
- escapeNextChar = false;
- } else {
- if (c === '\\') {
- escapeNextChar = true;
- if ((isNumber(n) || n === '$')) {
- out.push('$');
- } else if (n !== '/' && n !== '\\') {
- out.push('\\');
- }
- } else {
- if (c === '$') {
- out.push('$');
- }
- out.push(c);
- if (n === '/') {
- out.push('\\');
- }
- }
- }
- }
- return out.join('');
- }
- var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t'};
- function unescapeRegexReplace(str) {
- var stream = new CodeMirror.StringStream(str);
- var output = [];
- while (!stream.eol()) {
- while (stream.peek() && stream.peek() != '\\') {
- output.push(stream.next());
- }
- var matched = false;
- for (var matcher in unescapes) {
- if (stream.match(matcher, true)) {
- matched = true;
- output.push(unescapes[matcher]);
- break;
- }
- }
- if (!matched) {
- output.push(stream.next());
- }
- }
- return output.join('');
- }
- function parseQuery(query, ignoreCase, smartCase) {
- var lastSearchRegister = vimGlobalState.registerController.getRegister('/');
- lastSearchRegister.setText(query);
- if (query instanceof RegExp) { return query; }
- var slashes = findUnescapedSlashes(query);
- var regexPart;
- var forceIgnoreCase;
- if (!slashes.length) {
- regexPart = query;
- } else {
- regexPart = query.substring(0, slashes[0]);
- var flagsPart = query.substring(slashes[0]);
- forceIgnoreCase = (flagsPart.indexOf('i') != -1);
- }
- if (!regexPart) {
- return null;
- }
- if (!getOption('pcre')) {
- regexPart = translateRegex(regexPart);
- }
- if (smartCase) {
- ignoreCase = (/^[^A-Z]*$/).test(regexPart);
- }
- var regexp = new RegExp(regexPart,
- (ignoreCase || forceIgnoreCase) ? 'i' : undefined);
- return regexp;
- }
- function showConfirm(cm, text) {
- if (cm.openNotification) {
- cm.openNotification('' + text + '',
- {bottom: true, duration: 5000});
- } else {
- alert(text);
- }
- }
- function makePrompt(prefix, desc) {
- var raw = '';
- if (prefix) {
- raw += '' + prefix + '';
- }
- raw += ' ' +
- '';
- if (desc) {
- raw += '';
- raw += desc;
- raw += '';
- }
- return raw;
- }
- var searchPromptDesc = '(Javascript regexp)';
- function showPrompt(cm, options) {
- var shortText = (options.prefix || '') + ' ' + (options.desc || '');
- var prompt = makePrompt(options.prefix, options.desc);
- dialog(cm, prompt, shortText, options.onClose, options);
- }
- function regexEqual(r1, r2) {
- if (r1 instanceof RegExp && r2 instanceof RegExp) {
- var props = ['global', 'multiline', 'ignoreCase', 'source'];
- for (var i = 0; i < props.length; i++) {
- var prop = props[i];
- if (r1[prop] !== r2[prop]) {
- return false;
- }
- }
- return true;
- }
- return false;
- }
- function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
- if (!rawQuery) {
- return;
- }
- var state = getSearchState(cm);
- var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
- if (!query) {
- return;
- }
- highlightSearchMatches(cm, query);
- if (regexEqual(query, state.getQuery())) {
- return query;
- }
- state.setQuery(query);
- return query;
- }
- function searchOverlay(query) {
- if (query.source.charAt(0) == '^') {
- var matchSol = true;
- }
- return {
- token: function(stream) {
- if (matchSol && !stream.sol()) {
- stream.skipToEnd();
- return;
- }
- var match = stream.match(query, false);
- if (match) {
- if (match[0].length == 0) {
- stream.next();
- return 'searching';
- }
- if (!stream.sol()) {
- stream.backUp(1);
- if (!query.exec(stream.next() + match[0])) {
- stream.next();
- return null;
- }
- }
- stream.match(query);
- return 'searching';
- }
- while (!stream.eol()) {
- stream.next();
- if (stream.match(query, false)) break;
- }
- },
- query: query
- };
- }
- function highlightSearchMatches(cm, query) {
- var searchState = getSearchState(cm);
- var overlay = searchState.getOverlay();
- if (!overlay || query != overlay.query) {
- if (overlay) {
- cm.removeOverlay(overlay);
- }
- overlay = searchOverlay(query);
- cm.addOverlay(overlay);
- if (cm.showMatchesOnScrollbar) {
- if (searchState.getScrollbarAnnotate()) {
- searchState.getScrollbarAnnotate().clear();
- }
- searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query));
- }
- searchState.setOverlay(overlay);
- }
- }
- function findNext(cm, prev, query, repeat) {
- if (repeat === undefined) { repeat = 1; }
- return cm.operation(function() {
- var pos = cm.getCursor();
- var cursor = cm.getSearchCursor(query, pos);
- for (var i = 0; i < repeat; i++) {
- var found = cursor.find(prev);
- if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }
- if (!found) {
- cursor = cm.getSearchCursor(query,
- (prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) );
- if (!cursor.find(prev)) {
- return;
- }
- }
- }
- return cursor.from();
- });
- }
- function clearSearchHighlight(cm) {
- var state = getSearchState(cm);
- cm.removeOverlay(getSearchState(cm).getOverlay());
- state.setOverlay(null);
- if (state.getScrollbarAnnotate()) {
- state.getScrollbarAnnotate().clear();
- state.setScrollbarAnnotate(null);
- }
- }
- function isInRange(pos, start, end) {
- if (typeof pos != 'number') {
- pos = pos.line;
- }
- if (start instanceof Array) {
- return inArray(pos, start);
- } else {
- if (end) {
- return (pos >= start && pos <= end);
- } else {
- return pos == start;
- }
- }
- }
- function getUserVisibleLines(cm) {
- var renderer = cm.ace.renderer;
- return {
- top: renderer.getFirstFullyVisibleRow(),
- bottom: renderer.getLastFullyVisibleRow()
- }
- }
-
- var ExCommandDispatcher = function() {
- this.buildCommandMap_();
- };
- ExCommandDispatcher.prototype = {
- processCommand: function(cm, input, opt_params) {
- var that = this;
- cm.operation(function () {
- cm.curOp.isVimOp = true;
- that._processCommand(cm, input, opt_params);
- });
- },
- _processCommand: function(cm, input, opt_params) {
- var vim = cm.state.vim;
- var commandHistoryRegister = vimGlobalState.registerController.getRegister(':');
- var previousCommand = commandHistoryRegister.toString();
- if (vim.visualMode) {
- exitVisualMode(cm);
- }
- var inputStream = new CodeMirror.StringStream(input);
- commandHistoryRegister.setText(input);
- var params = opt_params || {};
- params.input = input;
- try {
- this.parseInput_(cm, inputStream, params);
- } catch(e) {
- showConfirm(cm, e);
- throw e;
- }
- var command;
- var commandName;
- if (!params.commandName) {
- if (params.line !== undefined) {
- commandName = 'move';
- }
- } else {
- command = this.matchCommand_(params.commandName);
- if (command) {
- commandName = command.name;
- if (command.excludeFromCommandHistory) {
- commandHistoryRegister.setText(previousCommand);
- }
- this.parseCommandArgs_(inputStream, params, command);
- if (command.type == 'exToKey') {
- for (var i = 0; i < command.toKeys.length; i++) {
- CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping');
- }
- return;
- } else if (command.type == 'exToEx') {
- this.processCommand(cm, command.toInput);
- return;
- }
- }
- }
- if (!commandName) {
- showConfirm(cm, 'Not an editor command ":' + input + '"');
- return;
- }
- try {
- exCommands[commandName](cm, params);
- if ((!command || !command.possiblyAsync) && params.callback) {
- params.callback();
- }
- } catch(e) {
- showConfirm(cm, e);
- throw e;
- }
- },
- parseInput_: function(cm, inputStream, result) {
- inputStream.eatWhile(':');
- if (inputStream.eat('%')) {
- result.line = cm.firstLine();
- result.lineEnd = cm.lastLine();
- } else {
- result.line = this.parseLineSpec_(cm, inputStream);
- if (result.line !== undefined && inputStream.eat(',')) {
- result.lineEnd = this.parseLineSpec_(cm, inputStream);
- }
- }
- var commandMatch = inputStream.match(/^(\w+)/);
- if (commandMatch) {
- result.commandName = commandMatch[1];
- } else {
- result.commandName = inputStream.match(/.*/)[0];
- }
-
- return result;
- },
- parseLineSpec_: function(cm, inputStream) {
- var numberMatch = inputStream.match(/^(\d+)/);
- if (numberMatch) {
- return parseInt(numberMatch[1], 10) - 1;
- }
- switch (inputStream.next()) {
- case '.':
- return cm.getCursor().line;
- case '$':
- return cm.lastLine();
- case '\'':
- var mark = cm.state.vim.marks[inputStream.next()];
- if (mark && mark.find()) {
- return mark.find().line;
- }
- throw new Error('Mark not set');
- default:
- inputStream.backUp(1);
- return undefined;
- }
- },
- parseCommandArgs_: function(inputStream, params, command) {
- if (inputStream.eol()) {
- return;
- }
- params.argString = inputStream.match(/.*/)[0];
- var delim = command.argDelimiter || /\s+/;
- var args = trim(params.argString).split(delim);
- if (args.length && args[0]) {
- params.args = args;
- }
- },
- matchCommand_: function(commandName) {
- for (var i = commandName.length; i > 0; i--) {
- var prefix = commandName.substring(0, i);
- if (this.commandMap_[prefix]) {
- var command = this.commandMap_[prefix];
- if (command.name.indexOf(commandName) === 0) {
- return command;
- }
- }
- }
- return null;
- },
- buildCommandMap_: function() {
- this.commandMap_ = {};
- for (var i = 0; i < defaultExCommandMap.length; i++) {
- var command = defaultExCommandMap[i];
- var key = command.shortName || command.name;
- this.commandMap_[key] = command;
- }
- },
- map: function(lhs, rhs, ctx) {
- if (lhs != ':' && lhs.charAt(0) == ':') {
- if (ctx) { throw Error('Mode not supported for ex mappings'); }
- var commandName = lhs.substring(1);
- if (rhs != ':' && rhs.charAt(0) == ':') {
- this.commandMap_[commandName] = {
- name: commandName,
- type: 'exToEx',
- toInput: rhs.substring(1),
- user: true
- };
- } else {
- this.commandMap_[commandName] = {
- name: commandName,
- type: 'exToKey',
- toKeys: rhs,
- user: true
- };
- }
- } else {
- if (rhs != ':' && rhs.charAt(0) == ':') {
- var mapping = {
- keys: lhs,
- type: 'keyToEx',
- exArgs: { input: rhs.substring(1) },
- user: true};
- if (ctx) { mapping.context = ctx; }
- defaultKeymap.unshift(mapping);
- } else {
- var mapping = {
- keys: lhs,
- type: 'keyToKey',
- toKeys: rhs,
- user: true
- };
- if (ctx) { mapping.context = ctx; }
- defaultKeymap.unshift(mapping);
- }
- }
- },
- unmap: function(lhs, ctx) {
- if (lhs != ':' && lhs.charAt(0) == ':') {
- if (ctx) { throw Error('Mode not supported for ex mappings'); }
- var commandName = lhs.substring(1);
- if (this.commandMap_[commandName] && this.commandMap_[commandName].user) {
- delete this.commandMap_[commandName];
- return;
- }
- } else {
- var keys = lhs;
- for (var i = 0; i < defaultKeymap.length; i++) {
- if (keys == defaultKeymap[i].keys
- && defaultKeymap[i].context === ctx
- && defaultKeymap[i].user) {
- defaultKeymap.splice(i, 1);
- return;
- }
- }
- }
- throw Error('No such mapping.');
- }
- };
-
- var exCommands = {
- colorscheme: function(cm, params) {
- if (!params.args || params.args.length < 1) {
- showConfirm(cm, cm.getOption('theme'));
- return;
- }
- cm.setOption('theme', params.args[0]);
- },
- map: function(cm, params, ctx) {
- var mapArgs = params.args;
- if (!mapArgs || mapArgs.length < 2) {
- if (cm) {
- showConfirm(cm, 'Invalid mapping: ' + params.input);
- }
- return;
- }
- exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
- },
- imap: function(cm, params) { this.map(cm, params, 'insert'); },
- nmap: function(cm, params) { this.map(cm, params, 'normal'); },
- vmap: function(cm, params) { this.map(cm, params, 'visual'); },
- unmap: function(cm, params, ctx) {
- var mapArgs = params.args;
- if (!mapArgs || mapArgs.length < 1) {
- if (cm) {
- showConfirm(cm, 'No such mapping: ' + params.input);
- }
- return;
- }
- exCommandDispatcher.unmap(mapArgs[0], ctx);
- },
- move: function(cm, params) {
- commandDispatcher.processCommand(cm, cm.state.vim, {
- type: 'motion',
- motion: 'moveToLineOrEdgeOfDocument',
- motionArgs: { forward: false, explicitRepeat: true,
- linewise: true },
- repeatOverride: params.line+1});
- },
- set: function(cm, params) {
- var setArgs = params.args;
- var setCfg = params.setCfg || {};
- if (!setArgs || setArgs.length < 1) {
- if (cm) {
- showConfirm(cm, 'Invalid mapping: ' + params.input);
- }
- return;
- }
- var expr = setArgs[0].split('=');
- var optionName = expr[0];
- var value = expr[1];
- var forceGet = false;
-
- if (optionName.charAt(optionName.length - 1) == '?') {
- if (value) { throw Error('Trailing characters: ' + params.argString); }
- optionName = optionName.substring(0, optionName.length - 1);
- forceGet = true;
- }
- if (value === undefined && optionName.substring(0, 2) == 'no') {
- optionName = optionName.substring(2);
- value = false;
- }
-
- var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean';
- if (optionIsBoolean && value == undefined) {
- value = true;
- }
- if (!optionIsBoolean && value === undefined || forceGet) {
- var oldValue = getOption(optionName, cm, setCfg);
- if (oldValue === true || oldValue === false) {
- showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName);
- } else {
- showConfirm(cm, ' ' + optionName + '=' + oldValue);
- }
- } else {
- setOption(optionName, value, cm, setCfg);
- }
- },
- setlocal: function (cm, params) {
- params.setCfg = {scope: 'local'};
- this.set(cm, params);
- },
- setglobal: function (cm, params) {
- params.setCfg = {scope: 'global'};
- this.set(cm, params);
- },
- registers: function(cm, params) {
- var regArgs = params.args;
- var registers = vimGlobalState.registerController.registers;
- var regInfo = '----------Registers----------
';
- if (!regArgs) {
- for (var registerName in registers) {
- var text = registers[registerName].toString();
- if (text.length) {
- regInfo += '"' + registerName + ' ' + text + '
';
- }
- }
- } else {
- var registerName;
- regArgs = regArgs.join('');
- for (var i = 0; i < regArgs.length; i++) {
- registerName = regArgs.charAt(i);
- if (!vimGlobalState.registerController.isValidRegister(registerName)) {
- continue;
- }
- var register = registers[registerName] || new Register();
- regInfo += '"' + registerName + ' ' + register.toString() + '
';
- }
- }
- showConfirm(cm, regInfo);
- },
- sort: function(cm, params) {
- var reverse, ignoreCase, unique, number;
- function parseArgs() {
- if (params.argString) {
- var args = new CodeMirror.StringStream(params.argString);
- if (args.eat('!')) { reverse = true; }
- if (args.eol()) { return; }
- if (!args.eatSpace()) { return 'Invalid arguments'; }
- var opts = args.match(/[a-z]+/);
- if (opts) {
- opts = opts[0];
- ignoreCase = opts.indexOf('i') != -1;
- unique = opts.indexOf('u') != -1;
- var decimal = opts.indexOf('d') != -1 && 1;
- var hex = opts.indexOf('x') != -1 && 1;
- var octal = opts.indexOf('o') != -1 && 1;
- if (decimal + hex + octal > 1) { return 'Invalid arguments'; }
- number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
- }
- if (args.match(/\/.*\//)) { return 'patterns not supported'; }
- }
- }
- var err = parseArgs();
- if (err) {
- showConfirm(cm, err + ': ' + params.argString);
- return;
- }
- var lineStart = params.line || cm.firstLine();
- var lineEnd = params.lineEnd || params.line || cm.lastLine();
- if (lineStart == lineEnd) { return; }
- var curStart = Pos(lineStart, 0);
- var curEnd = Pos(lineEnd, lineLength(cm, lineEnd));
- var text = cm.getRange(curStart, curEnd).split('\n');
- var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ :
- (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
- (number == 'octal') ? /([0-7]+)/ : null;
- var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
- var numPart = [], textPart = [];
- if (number) {
- for (var i = 0; i < text.length; i++) {
- if (numberRegex.exec(text[i])) {
- numPart.push(text[i]);
- } else {
- textPart.push(text[i]);
- }
- }
- } else {
- textPart = text;
- }
- function compareFn(a, b) {
- if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
- if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
- var anum = number && numberRegex.exec(a);
- var bnum = number && numberRegex.exec(b);
- if (!anum) { return a < b ? -1 : 1; }
- anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
- bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
- return anum - bnum;
- }
- numPart.sort(compareFn);
- textPart.sort(compareFn);
- text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
- if (unique) { // Remove duplicate lines
- var textOld = text;
- var lastLine;
- text = [];
- for (var i = 0; i < textOld.length; i++) {
- if (textOld[i] != lastLine) {
- text.push(textOld[i]);
- }
- lastLine = textOld[i];
- }
- }
- cm.replaceRange(text.join('\n'), curStart, curEnd);
- },
- global: function(cm, params) {
- var argString = params.argString;
- if (!argString) {
- showConfirm(cm, 'Regular Expression missing from global');
- return;
- }
- var lineStart = (params.line !== undefined) ? params.line : cm.firstLine();
- var lineEnd = params.lineEnd || params.line || cm.lastLine();
- var tokens = splitBySlash(argString);
- var regexPart = argString, cmd;
- if (tokens.length) {
- regexPart = tokens[0];
- cmd = tokens.slice(1, tokens.length).join('/');
- }
- if (regexPart) {
- try {
- updateSearchQuery(cm, regexPart, true /** ignoreCase */,
- true /** smartCase */);
- } catch (e) {
- showConfirm(cm, 'Invalid regex: ' + regexPart);
- return;
- }
- }
- var query = getSearchState(cm).getQuery();
- var matchedLines = [], content = '';
- for (var i = lineStart; i <= lineEnd; i++) {
- var matched = query.test(cm.getLine(i));
- if (matched) {
- matchedLines.push(i+1);
- content+= cm.getLine(i) + '
';
- }
- }
- if (!cmd) {
- showConfirm(cm, content);
- return;
- }
- var index = 0;
- var nextCommand = function() {
- if (index < matchedLines.length) {
- var command = matchedLines[index] + cmd;
- exCommandDispatcher.processCommand(cm, command, {
- callback: nextCommand
- });
- }
- index++;
- };
- nextCommand();
- },
- substitute: function(cm, params) {
- if (!cm.getSearchCursor) {
- throw new Error('Search feature not available. Requires searchcursor.js or ' +
- 'any other getSearchCursor implementation.');
- }
- var argString = params.argString;
- var tokens = argString ? splitBySlash(argString) : [];
- var regexPart, replacePart = '', trailing, flagsPart, count;
- var confirm = false; // Whether to confirm each replace.
- var global = false; // True to replace all instances on a line, false to replace only 1.
- if (tokens.length) {
- regexPart = tokens[0];
- replacePart = tokens[1];
- if (replacePart !== undefined) {
- if (getOption('pcre')) {
- replacePart = unescapeRegexReplace(replacePart);
- } else {
- replacePart = translateRegexReplace(replacePart);
- }
- vimGlobalState.lastSubstituteReplacePart = replacePart;
- }
- trailing = tokens[2] ? tokens[2].split(' ') : [];
- } else {
- if (argString && argString.length) {
- showConfirm(cm, 'Substitutions should be of the form ' +
- ':s/pattern/replace/');
- return;
- }
- }
- if (trailing) {
- flagsPart = trailing[0];
- count = parseInt(trailing[1]);
- if (flagsPart) {
- if (flagsPart.indexOf('c') != -1) {
- confirm = true;
- flagsPart.replace('c', '');
- }
- if (flagsPart.indexOf('g') != -1) {
- global = true;
- flagsPart.replace('g', '');
- }
- regexPart = regexPart + '/' + flagsPart;
- }
- }
- if (regexPart) {
- try {
- updateSearchQuery(cm, regexPart, true /** ignoreCase */,
- true /** smartCase */);
- } catch (e) {
- showConfirm(cm, 'Invalid regex: ' + regexPart);
- return;
- }
- }
- replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart;
- if (replacePart === undefined) {
- showConfirm(cm, 'No previous substitute regular expression');
- return;
- }
- var state = getSearchState(cm);
- var query = state.getQuery();
- var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
- var lineEnd = params.lineEnd || lineStart;
- if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) {
- lineEnd = Infinity;
- }
- if (count) {
- lineStart = lineEnd;
- lineEnd = lineStart + count - 1;
- }
- var startPos = clipCursorToContent(cm, Pos(lineStart, 0));
- var cursor = cm.getSearchCursor(query, startPos);
- doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback);
- },
- redo: CodeMirror.commands.redo,
- undo: CodeMirror.commands.undo,
- write: function(cm) {
- if (CodeMirror.commands.save) {
- CodeMirror.commands.save(cm);
- } else {
- cm.save();
- }
- },
- nohlsearch: function(cm) {
- clearSearchHighlight(cm);
- },
- delmarks: function(cm, params) {
- if (!params.argString || !trim(params.argString)) {
- showConfirm(cm, 'Argument required');
- return;
- }
-
- var state = cm.state.vim;
- var stream = new CodeMirror.StringStream(trim(params.argString));
- while (!stream.eol()) {
- stream.eatSpace();
- var count = stream.pos;
-
- if (!stream.match(/[a-zA-Z]/, false)) {
- showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
- return;
- }
-
- var sym = stream.next();
- if (stream.match('-', true)) {
- if (!stream.match(/[a-zA-Z]/, false)) {
- showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
- return;
- }
-
- var startMark = sym;
- var finishMark = stream.next();
- if (isLowerCase(startMark) && isLowerCase(finishMark) ||
- isUpperCase(startMark) && isUpperCase(finishMark)) {
- var start = startMark.charCodeAt(0);
- var finish = finishMark.charCodeAt(0);
- if (start >= finish) {
- showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
- return;
- }
- for (var j = 0; j <= finish - start; j++) {
- var mark = String.fromCharCode(start + j);
- delete state.marks[mark];
- }
- } else {
- showConfirm(cm, 'Invalid argument: ' + startMark + '-');
- return;
- }
- } else {
- delete state.marks[sym];
- }
- }
- }
- };
-
- var exCommandDispatcher = new ExCommandDispatcher();
- function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query,
- replaceWith, callback) {
- cm.state.vim.exMode = true;
- var done = false;
- var lastPos = searchCursor.from();
- function replaceAll() {
- cm.operation(function() {
- while (!done) {
- replace();
- next();
- }
- stop();
- });
- }
- function replace() {
- var text = cm.getRange(searchCursor.from(), searchCursor.to());
- var newText = text.replace(query, replaceWith);
- searchCursor.replace(newText);
- }
- function next() {
- while(searchCursor.findNext() &&
- isInRange(searchCursor.from(), lineStart, lineEnd)) {
- if (!global && lastPos && searchCursor.from().line == lastPos.line) {
- continue;
- }
- cm.scrollIntoView(searchCursor.from(), 30);
- cm.setSelection(searchCursor.from(), searchCursor.to());
- lastPos = searchCursor.from();
- done = false;
- return;
- }
- done = true;
- }
- function stop(close) {
- if (close) { close(); }
- cm.focus();
- if (lastPos) {
- cm.setCursor(lastPos);
- var vim = cm.state.vim;
- vim.exMode = false;
- vim.lastHPos = vim.lastHSPos = lastPos.ch;
- }
- if (callback) { callback(); }
- }
- function onPromptKeyDown(e, _value, close) {
- CodeMirror.e_stop(e);
- var keyName = CodeMirror.keyName(e);
- switch (keyName) {
- case 'Y':
- replace(); next(); break;
- case 'N':
- next(); break;
- case 'A':
- var savedCallback = callback;
- callback = undefined;
- cm.operation(replaceAll);
- callback = savedCallback;
- break;
- case 'L':
- replace();
- case 'Q':
- case 'Esc':
- case 'Ctrl-C':
- case 'Ctrl-[':
- stop(close);
- break;
- }
- if (done) { stop(close); }
- return true;
- }
- next();
- if (done) {
- showConfirm(cm, 'No matches for ' + query.source);
- return;
- }
- if (!confirm) {
- replaceAll();
- if (callback) { callback(); }
- return;
- }
- showPrompt(cm, {
- prefix: 'replace with ' + replaceWith + ' (y/n/a/q/l)',
- onKeyDown: onPromptKeyDown
- });
- }
-
- CodeMirror.keyMap.vim = {
- attach: attachVimMap,
- detach: detachVimMap,
- call: cmKey
- };
-
- function exitInsertMode(cm) {
- var vim = cm.state.vim;
- var macroModeState = vimGlobalState.macroModeState;
- var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.');
- var isPlaying = macroModeState.isPlaying;
- var lastChange = macroModeState.lastInsertModeChanges;
- var text = [];
- if (!isPlaying) {
- var selLength = lastChange.inVisualBlock ? vim.lastSelection.visualBlock.height : 1;
- var changes = lastChange.changes;
- var text = [];
- var i = 0;
- while (i < changes.length) {
- text.push(changes[i]);
- if (changes[i] instanceof InsertModeKey) {
- i++;
- } else {
- i+= selLength;
- }
- }
- lastChange.changes = text;
- cm.off('change', onChange);
- CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
- }
- if (!isPlaying && vim.insertModeRepeat > 1) {
- repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
- true /** repeatForInsert */);
- vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
- }
- delete vim.insertModeRepeat;
- vim.insertMode = false;
- cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1);
- cm.setOption('keyMap', 'vim');
- cm.setOption('disableInput', true);
- cm.toggleOverwrite(false); // exit replace mode if we were in it.
- insertModeChangeRegister.setText(lastChange.changes.join(''));
- CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
- if (macroModeState.isRecording) {
- logInsertModeChange(macroModeState);
- }
- }
-
- function _mapCommand(command) {
- defaultKeymap.unshift(command);
- }
-
- function mapCommand(keys, type, name, args, extra) {
- var command = {keys: keys, type: type};
- command[type] = name;
- command[type + "Args"] = args;
- for (var key in extra)
- command[key] = extra[key];
- _mapCommand(command);
- }
- defineOption('insertModeEscKeysTimeout', 200, 'number');
-
- CodeMirror.keyMap['vim-insert'] = {
- 'Ctrl-N': 'autocomplete',
- 'Ctrl-P': 'autocomplete',
- 'Enter': function(cm) {
- var fn = CodeMirror.commands.newlineAndIndentContinueComment ||
- CodeMirror.commands.newlineAndIndent;
- fn(cm);
- },
- fallthrough: ['default'],
- attach: attachVimMap,
- detach: detachVimMap,
- call: cmKey
- };
-
- CodeMirror.keyMap['vim-replace'] = {
- 'Backspace': 'goCharLeft',
- fallthrough: ['vim-insert'],
- attach: attachVimMap,
- detach: detachVimMap,
- call: cmKey
- };
-
- function executeMacroRegister(cm, vim, macroModeState, registerName) {
- var register = vimGlobalState.registerController.getRegister(registerName);
- if (registerName == ':') {
- if (register.keyBuffer[0]) {
- exCommandDispatcher.processCommand(cm, register.keyBuffer[0]);
- }
- macroModeState.isPlaying = false;
- return;
- }
- var keyBuffer = register.keyBuffer;
- var imc = 0;
- macroModeState.isPlaying = true;
- macroModeState.replaySearchQueries = register.searchQueries.slice(0);
- for (var i = 0; i < keyBuffer.length; i++) {
- var text = keyBuffer[i];
- var match, key;
- while (text) {
- match = (/<\w+-.+?>|<\w+>|./).exec(text);
- key = match[0];
- text = text.substring(match.index + key.length);
- CodeMirror.Vim.handleKey(cm, key, 'macro');
- if (vim.insertMode) {
- var changes = register.insertModeChanges[imc++].changes;
- vimGlobalState.macroModeState.lastInsertModeChanges.changes =
- changes;
- repeatInsertModeChanges(cm, changes, 1);
- exitInsertMode(cm);
- }
- }
- }
- macroModeState.isPlaying = false;
- }
-
- function logKey(macroModeState, key) {
- if (macroModeState.isPlaying) { return; }
- var registerName = macroModeState.latestRegister;
- var register = vimGlobalState.registerController.getRegister(registerName);
- if (register) {
- register.pushText(key);
- }
- }
-
- function logInsertModeChange(macroModeState) {
- if (macroModeState.isPlaying) { return; }
- var registerName = macroModeState.latestRegister;
- var register = vimGlobalState.registerController.getRegister(registerName);
- if (register && register.pushInsertModeChanges) {
- register.pushInsertModeChanges(macroModeState.lastInsertModeChanges);
- }
- }
-
- function logSearchQuery(macroModeState, query) {
- if (macroModeState.isPlaying) { return; }
- var registerName = macroModeState.latestRegister;
- var register = vimGlobalState.registerController.getRegister(registerName);
- if (register && register.pushSearchQuery) {
- register.pushSearchQuery(query);
- }
- }
- function onChange(_cm, changeObj) {
- var macroModeState = vimGlobalState.macroModeState;
- var lastChange = macroModeState.lastInsertModeChanges;
- if (!macroModeState.isPlaying) {
- while(changeObj) {
- lastChange.expectCursorActivityForChange = true;
- if (changeObj.origin == '+input' || changeObj.origin == 'paste'
- || changeObj.origin === undefined /* only in testing */) {
- var text = changeObj.text.join('\n');
- lastChange.changes.push(text);
- }
- changeObj = changeObj.next;
- }
- }
- }
- function onCursorActivity(cm) {
- var vim = cm.state.vim;
- if (vim.insertMode) {
- var macroModeState = vimGlobalState.macroModeState;
- if (macroModeState.isPlaying) { return; }
- var lastChange = macroModeState.lastInsertModeChanges;
- if (lastChange.expectCursorActivityForChange) {
- lastChange.expectCursorActivityForChange = false;
- } else {
- lastChange.changes = [];
- }
- } else if (!cm.curOp.isVimOp) {
- handleExternalSelection(cm, vim);
- }
- if (vim.visualMode) {
- updateFakeCursor(cm);
- }
- }
- function updateFakeCursor(cm) {
- var vim = cm.state.vim;
- var from = clipCursorToContent(cm, copyCursor(vim.sel.head));
- var to = offsetCursor(from, 0, 1);
- if (vim.fakeCursor) {
- vim.fakeCursor.clear();
- }
- vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'});
- }
- function handleExternalSelection(cm, vim) {
- var anchor = cm.getCursor('anchor');
- var head = cm.getCursor('head');
- if (vim.visualMode && !cm.somethingSelected()) {
- exitVisualMode(cm, false);
- } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) {
- vim.visualMode = true;
- vim.visualLine = false;
- CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
- }
- if (vim.visualMode) {
- var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
- var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
- head = offsetCursor(head, 0, headOffset);
- anchor = offsetCursor(anchor, 0, anchorOffset);
- vim.sel = {
- anchor: anchor,
- head: head
- };
- updateMark(cm, vim, '<', cursorMin(head, anchor));
- updateMark(cm, vim, '>', cursorMax(head, anchor));
- } else if (!vim.insertMode) {
- vim.lastHPos = cm.getCursor().ch;
- }
- }
- function InsertModeKey(keyName) {
- this.keyName = keyName;
- }
- function onKeyEventTargetKeyDown(e) {
- var macroModeState = vimGlobalState.macroModeState;
- var lastChange = macroModeState.lastInsertModeChanges;
- var keyName = CodeMirror.keyName(e);
- if (!keyName) { return; }
- function onKeyFound() {
- lastChange.changes.push(new InsertModeKey(keyName));
- return true;
- }
- if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
- CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound);
- }
- }
- function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
- var macroModeState = vimGlobalState.macroModeState;
- macroModeState.isPlaying = true;
- var isAction = !!vim.lastEditActionCommand;
- var cachedInputState = vim.inputState;
- function repeatCommand() {
- if (isAction) {
- commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
- } else {
- commandDispatcher.evalInput(cm, vim);
- }
- }
- function repeatInsert(repeat) {
- if (macroModeState.lastInsertModeChanges.changes.length > 0) {
- repeat = !vim.lastEditActionCommand ? 1 : repeat;
- var changeObject = macroModeState.lastInsertModeChanges;
- repeatInsertModeChanges(cm, changeObject.changes, repeat);
- }
- }
- vim.inputState = vim.lastEditInputState;
- if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
- for (var i = 0; i < repeat; i++) {
- repeatCommand();
- repeatInsert(1);
- }
- } else {
- if (!repeatForInsert) {
- repeatCommand();
- }
- repeatInsert(repeat);
- }
- vim.inputState = cachedInputState;
- if (vim.insertMode && !repeatForInsert) {
- exitInsertMode(cm);
- }
- macroModeState.isPlaying = false;
- }
-
- function repeatInsertModeChanges(cm, changes, repeat) {
- function keyHandler(binding) {
- if (typeof binding == 'string') {
- CodeMirror.commands[binding](cm);
- } else {
- binding(cm);
- }
- return true;
- }
- var head = cm.getCursor('head');
- var inVisualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock;
- if (inVisualBlock) {
- var vim = cm.state.vim;
- var lastSel = vim.lastSelection;
- var offset = getOffset(lastSel.anchor, lastSel.head);
- selectForInsert(cm, head, offset.line + 1);
- repeat = cm.listSelections().length;
- cm.setCursor(head);
- }
- for (var i = 0; i < repeat; i++) {
- if (inVisualBlock) {
- cm.setCursor(offsetCursor(head, i, 0));
- }
- for (var j = 0; j < changes.length; j++) {
- var change = changes[j];
- if (change instanceof InsertModeKey) {
- CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler);
- } else {
- var cur = cm.getCursor();
- cm.replaceRange(change, cur, cur);
- }
- }
- }
- if (inVisualBlock) {
- cm.setCursor(offsetCursor(head, 0, 1));
- }
- }
-
- resetVimGlobalState();
- CodeMirror.Vim = Vim();
-
- Vim = CodeMirror.Vim;
-
- var specialKey = {'return':'CR',backspace:'BS','delete':'Del',esc:'Esc',
- left:'Left',right:'Right',up:'Up',down:'Down',space: 'Space',
- home:'Home',end:'End',pageup:'PageUp',pagedown:'PageDown', enter: 'CR'
- };
- function lookupKey(hashId, key, e) {
- if (key.length > 1 && key[0] == "n") {
- key = key.replace("numpad", "");
- }
- key = specialKey[key] || key;
- var name = '';
- if (e.ctrlKey) { name += 'C-'; }
- if (e.altKey) { name += 'A-'; }
- if (e.shiftKey) { name += 'S-'; }
-
- name += key;
- if (name.length > 1) { name = '<' + name + '>'; }
- return name;
- }
- var handleKey = Vim.handleKey.bind(Vim);
- Vim.handleKey = function(cm, key, origin) {
- return cm.operation(function() {
- return handleKey(cm, key, origin);
- }, true);
- }
- function cloneVimState(state) {
- var n = new state.constructor();
- Object.keys(state).forEach(function(key) {
- var o = state[key];
- if (Array.isArray(o))
- o = o.slice();
- else if (o && typeof o == "object" && o.constructor != Object)
- o = cloneVimState(o);
- n[key] = o;
- });
- if (state.sel) {
- n.sel = {
- head: state.sel.head && copyCursor(state.sel.head),
- anchor: state.sel.anchor && copyCursor(state.sel.anchor)
- };
- }
- return n;
- }
- function multiSelectHandleKey(cm, key, origin) {
- var isHandled = false;
- var vim = Vim.maybeInitVimState_(cm);
- var visualBlock = vim.visualBlock || vim.wasInVisualBlock;
- if (vim.wasInVisualBlock && !cm.ace.inMultiSelectMode) {
- vim.wasInVisualBlock = false;
- } else if (cm.ace.inMultiSelectMode && vim.visualBlock) {
- vim.wasInVisualBlock = true;
- }
-
- if (key == '' && !vim.insertMode && !vim.visualMode && cm.ace.inMultiSelectMode) {
- cm.ace.exitMultiSelectMode();
- } else if (visualBlock || !cm.ace.inMultiSelectMode || cm.ace.inVirtualSelectionMode) {
- isHandled = Vim.handleKey(cm, key, origin);
- } else {
- var old = cloneVimState(vim);
- cm.operation(function() {
- cm.ace.forEachSelection(function() {
- var sel = cm.ace.selection;
- cm.state.vim.lastHPos = sel.$desiredColumn == null ? sel.lead.column : sel.$desiredColumn;
- var head = cm.getCursor("head");
- var anchor = cm.getCursor("anchor");
- var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
- var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
- head = offsetCursor(head, 0, headOffset);
- anchor = offsetCursor(anchor, 0, anchorOffset);
- cm.state.vim.sel.head = head;
- cm.state.vim.sel.anchor = anchor;
-
- isHandled = handleKey(cm, key, origin);
- sel.$desiredColumn = cm.state.vim.lastHPos == -1 ? null : cm.state.vim.lastHPos;
- if (cm.virtualSelectionMode()) {
- cm.state.vim = cloneVimState(old);
- }
- });
- if (cm.curOp.cursorActivity && !isHandled)
- cm.curOp.cursorActivity = false;
- }, true);
- }
- return isHandled;
- }
- exports.CodeMirror = CodeMirror;
- var getVim = Vim.maybeInitVimState_;
- exports.handler = {
- $id: "ace/keyboard/vim",
- drawCursor: function(style, pixelPos, config, sel, session) {
- var vim = this.state.vim || {};
- var w = config.characterWidth;
- var h = config.lineHeight;
- var top = pixelPos.top;
- var left = pixelPos.left;
- if (!vim.insertMode) {
- var isbackwards = !sel.cursor
- ? session.selection.isBackwards() || session.selection.isEmpty()
- : Range.comparePoints(sel.cursor, sel.start) <= 0;
- if (!isbackwards && left > w)
- left -= w;
- }
- if (!vim.insertMode && vim.status) {
- h = h / 2;
- top += h;
- }
- style.left = left + "px";
- style.top = top + "px";
- style.width = w + "px";
- style.height = h + "px";
- },
- handleKeyboard: function(data, hashId, key, keyCode, e) {
- var editor = data.editor;
- var cm = editor.state.cm;
- var vim = getVim(cm);
- if (keyCode == -1) return;
-
- if (key == "c" && hashId == 1) { // key == "ctrl-c"
- if (!useragent.isMac && editor.getCopyText()) {
- editor.once("copy", function() {
- editor.selection.clearSelection();
- });
- return {command: "null", passEvent: true};
- }
- } else if (!vim.insertMode) {
- if (useragent.isMac && this.handleMacRepeat(data, hashId, key)) {
- hashId = -1;
- key = data.inputChar;
- }
- }
-
- if (hashId == -1 || hashId & 1 || hashId === 0 && key.length > 1) {
- var insertMode = vim.insertMode;
- var name = lookupKey(hashId, key, e || {});
- if (vim.status == null)
- vim.status = "";
- var isHandled = multiSelectHandleKey(cm, name, 'user');
- vim = getVim(cm); // may be changed by multiSelectHandleKey
- if (isHandled && vim.status != null)
- vim.status += name;
- else if (vim.status == null)
- vim.status = "";
- cm._signal("changeStatus");
- if (!isHandled && (hashId != -1 || insertMode))
- return;
- return {command: "null", passEvent: !isHandled};
- }
- },
- attach: function(editor) {
- if (!editor.state) editor.state = {};
- var cm = new CodeMirror(editor);
- editor.state.cm = cm;
- editor.$vimModeHandler = this;
- CodeMirror.keyMap.vim.attach(cm);
- getVim(cm).status = null;
- cm.on('vim-command-done', function() {
- if (cm.virtualSelectionMode()) return;
- getVim(cm).status = null;
- cm.ace._signal("changeStatus");
- cm.ace.session.markUndoGroup();
- });
- cm.on("changeStatus", function() {
- cm.ace.renderer.updateCursor();
- cm.ace._signal("changeStatus");
- });
- cm.on("vim-mode-change", function() {
- if (cm.virtualSelectionMode()) return;
- cm.ace.renderer.setStyle("normal-mode", !getVim(cm).insertMode);
- cm._signal("changeStatus");
- });
- cm.ace.renderer.setStyle("normal-mode", !getVim(cm).insertMode);
- editor.renderer.$cursorLayer.drawCursor = this.drawCursor.bind(cm);
- this.updateMacCompositionHandlers(editor, true);
- },
- detach: function(editor) {
- var cm = editor.state.cm;
- CodeMirror.keyMap.vim.detach(cm);
- cm.destroy();
- editor.state.cm = null;
- editor.$vimModeHandler = null;
- editor.renderer.$cursorLayer.drawCursor = null;
- editor.renderer.setStyle("normal-mode", false);
- this.updateMacCompositionHandlers(editor, false);
- },
- getStatusText: function(editor) {
- var cm = editor.state.cm;
- var vim = getVim(cm);
- if (vim.insertMode)
- return "INSERT";
- var status = "";
- if (vim.visualMode) {
- status += "VISUAL";
- if (vim.visualLine)
- status += " LINE";
- if (vim.visualBlock)
- status += " BLOCK";
- }
- if (vim.status)
- status += (status ? " " : "") + vim.status;
- return status;
- },
- handleMacRepeat: function(data, hashId, key) {
- if (hashId == -1) {
- data.inputChar = key;
- data.lastEvent = "input";
- } else if (data.inputChar && data.$lastHash == hashId && data.$lastKey == key) {
- if (data.lastEvent == "input") {
- data.lastEvent = "input1";
- } else if (data.lastEvent == "input1") {
- return true;
- }
- } else {
- data.$lastHash = hashId;
- data.$lastKey = key;
- data.lastEvent = "keypress";
- }
- },
- updateMacCompositionHandlers: function(editor, enable) {
- var onCompositionUpdateOverride = function(text) {
- var cm = editor.state.cm;
- var vim = getVim(cm);
- if (!vim.insertMode) {
- var el = this.textInput.getElement();
- el.blur();
- el.focus();
- el.value = text;
- } else {
- this.onCompositionUpdateOrig(text);
- }
- };
- var onCompositionStartOverride = function(text) {
- var cm = editor.state.cm;
- var vim = getVim(cm);
- if (!vim.insertMode) {
- this.onCompositionStartOrig(text);
- }
- };
- if (enable) {
- if (!editor.onCompositionUpdateOrig) {
- editor.onCompositionUpdateOrig = editor.onCompositionUpdate;
- editor.onCompositionUpdate = onCompositionUpdateOverride;
- editor.onCompositionStartOrig = editor.onCompositionStart;
- editor.onCompositionStart = onCompositionStartOverride;
- }
- } else {
- if (editor.onCompositionUpdateOrig) {
- editor.onCompositionUpdate = editor.onCompositionUpdateOrig;
- editor.onCompositionUpdateOrig = null;
- editor.onCompositionStart = editor.onCompositionStartOrig;
- editor.onCompositionStartOrig = null;
- }
- }
- }
- };
- var renderVirtualNumbers = {
- getText: function(session, row) {
- return (Math.abs(session.selection.lead.row - row) || (row + 1 + (row < 9? "\xb7" : "" ))) + "";
- },
- getWidth: function(session, lastLineNumber, config) {
- return session.getLength().toString().length * config.characterWidth;
- },
- update: function(e, editor) {
- editor.renderer.$loop.schedule(editor.renderer.CHANGE_GUTTER);
- },
- attach: function(editor) {
- editor.renderer.$gutterLayer.$renderer = this;
- editor.on("changeSelection", this.update);
- },
- detach: function(editor) {
- editor.renderer.$gutterLayer.$renderer = null;
- editor.off("changeSelection", this.update);
- }
- };
- Vim.defineOption({
- name: "wrap",
- set: function(value, cm) {
- if (cm) {cm.ace.setOption("wrap", value)}
- },
- type: "boolean"
- }, false);
- Vim.defineEx('write', 'w', function() {
- console.log(':write is not implemented')
- });
- defaultKeymap.push(
- { keys: 'zc', type: 'action', action: 'fold', actionArgs: { open: false } },
- { keys: 'zC', type: 'action', action: 'fold', actionArgs: { open: false, all: true } },
- { keys: 'zo', type: 'action', action: 'fold', actionArgs: { open: true } },
- { keys: 'zO', type: 'action', action: 'fold', actionArgs: { open: true, all: true } },
- { keys: 'za', type: 'action', action: 'fold', actionArgs: { toggle: true } },
- { keys: 'zA', type: 'action', action: 'fold', actionArgs: { toggle: true, all: true } },
- { keys: 'zf', type: 'action', action: 'fold', actionArgs: { open: true, all: true } },
- { keys: 'zd', type: 'action', action: 'fold', actionArgs: { open: true, all: true } },
-
- { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAbove" } },
- { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelow" } },
- { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAboveSkipCurrent" } },
- { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelowSkipCurrent" } },
- { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreBefore" } },
- { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreAfter" } },
- { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextBefore" } },
- { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextAfter" } }
- );
- actions.aceCommand = function(cm, actionArgs, vim) {
- cm.vimCmd = actionArgs;
- if (cm.ace.inVirtualSelectionMode)
- cm.ace.on("beforeEndOperation", delayedExecAceCommand);
- else
- delayedExecAceCommand(null, cm.ace);
- };
- function delayedExecAceCommand(op, ace) {
- ace.off("beforeEndOperation", delayedExecAceCommand);
- var cmd = ace.state.cm.vimCmd;
- if (cmd) {
- ace.execCommand(cmd.exec ? cmd : cmd.name, cmd.args);
- }
- ace.curOp = ace.prevOp;
- }
- actions.fold = function(cm, actionArgs, vim) {
- cm.ace.execCommand(['toggleFoldWidget', 'toggleFoldWidget', 'foldOther', 'unfoldall'
- ][(actionArgs.all ? 2 : 0) + (actionArgs.open ? 1 : 0)]);
- };
-
- exports.handler.defaultKeymap = defaultKeymap;
- exports.handler.actions = actions;
- exports.Vim = Vim;
-
- Vim.map("Y", "yy", "normal");
-});
diff --git a/icestudio/lib/ace-builds/src-noconflict/mode-verilog.js b/icestudio/lib/ace-builds/src-noconflict/mode-verilog.js
deleted file mode 100644
index 716d76770..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/mode-verilog.js
+++ /dev/null
@@ -1,103 +0,0 @@
-ace.define("ace/mode/verilog_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
-"use strict";
-
-var oop = require("../lib/oop");
-var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
-
-var VerilogHighlightRules = function() {
-var keywords = "always|and|assign|automatic|begin|buf|bufif0|bufif1|case|casex|casez|cell|cmos|config|" +
- "deassign|default|defparam|design|disable|edge|else|end|endcase|endconfig|endfunction|endgenerate|endmodule|" +
- "endprimitive|endspecify|endtable|endtask|event|for|force|forever|fork|function|generate|genvar|highz0|" +
- "highz1|if|ifnone|incdir|include|initial|inout|input|instance|integer|join|large|liblist|library|localparam|" +
- "macromodule|medium|module|nand|negedge|nmos|nor|noshowcancelled|not|notif0|notif1|or|output|parameter|pmos|" +
- "posedge|primitive|pull0|pull1|pulldown|pullup|pulsestyle_onevent|pulsestyle_ondetect|rcmos|real|realtime|" +
- "reg|release|repeat|rnmos|rpmos|rtran|rtranif0|rtranif1|scalared|showcancelled|signed|small|specify|specparam|" +
- "strong0|strong1|supply0|supply1|table|task|time|tran|tranif0|tranif1|tri|tri0|tri1|triand|trior|trireg|" +
- "unsigned|use|vectored|wait|wand|weak0|weak1|while|wire|wor|xnor|xor" +
- "begin|bufif0|bufif1|case|casex|casez|config|else|end|endcase|endconfig|endfunction|" +
- "endgenerate|endmodule|endprimitive|endspecify|endtable|endtask|for|forever|function|generate|if|ifnone|" +
- "macromodule|module|primitive|repeat|specify|table|task|while";
-
- var builtinConstants = (
- "true|false|null"
- );
-
- var builtinFunctions = (
- "count|min|max|avg|sum|rank|now|coalesce|main"
- );
-
- var keywordMapper = this.createKeywordMapper({
- "support.function": builtinFunctions,
- "keyword": keywords,
- "constant.language": builtinConstants
- }, "identifier", true);
-
- this.$rules = {
- "start" : [ {
- token : "comment",
- regex : "//.*$"
- }, {
- token : "comment.start",
- regex : "/\\*",
- next : [
- { token : "comment.end", regex : "\\*/" },
- { defaultToken : "comment" }
- ]
- }, {
- token : "string", // " string
- regex : '".*?"'
- }, {
- token : "string", // ' string
- regex : "'.*?'"
- }, {
- token : "constant.numeric", // float
- regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
- }, {
- token : keywordMapper,
- regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
- }, {
- token : "keyword.operator",
- regex : "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|="
- }, {
- token : "paren.lparen",
- regex : "[\\(]"
- }, {
- token : "paren.rparen",
- regex : "[\\)]"
- }, {
- token : "text",
- regex : "\\s+"
- } ]
- };
- this.normalizeRules();
-};
-
-oop.inherits(VerilogHighlightRules, TextHighlightRules);
-
-exports.VerilogHighlightRules = VerilogHighlightRules;
-});
-
-ace.define("ace/mode/verilog",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/verilog_highlight_rules","ace/range"], function(require, exports, module) {
-"use strict";
-
-var oop = require("../lib/oop");
-var TextMode = require("./text").Mode;
-var VerilogHighlightRules = require("./verilog_highlight_rules").VerilogHighlightRules;
-var Range = require("../range").Range;
-
-var Mode = function() {
- this.HighlightRules = VerilogHighlightRules;
-};
-oop.inherits(Mode, TextMode);
-
-(function() {
-
- this.lineCommentStart = "//";
- this.blockComment = {start: "/*", end: "*/"};
-
- this.$id = "ace/mode/verilog";
-}).call(Mode.prototype);
-
-exports.Mode = Mode;
-
-});
diff --git a/icestudio/lib/ace-builds/src-noconflict/snippets/verilog.js b/icestudio/lib/ace-builds/src-noconflict/snippets/verilog.js
deleted file mode 100644
index 8103ff6f2..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/snippets/verilog.js
+++ /dev/null
@@ -1,7 +0,0 @@
-ace.define("ace/snippets/verilog",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-exports.snippetText =undefined;
-exports.scope = "verilog";
-
-});
diff --git a/icestudio/lib/ace-builds/src-noconflict/theme-chrome.js b/icestudio/lib/ace-builds/src-noconflict/theme-chrome.js
deleted file mode 100644
index 83742aa46..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/theme-chrome.js
+++ /dev/null
@@ -1,128 +0,0 @@
-ace.define("ace/theme/chrome",["require","exports","module","ace/lib/dom"], function(require, exports, module) {
-
-exports.isDark = false;
-exports.cssClass = "ace-chrome";
-exports.cssText = ".ace-chrome .ace_gutter {\
-background: #ebebeb;\
-color: #333;\
-overflow : hidden;\
-}\
-.ace-chrome .ace_print-margin {\
-width: 1px;\
-background: #e8e8e8;\
-}\
-.ace-chrome {\
-background-color: #FFFFFF;\
-color: black;\
-}\
-.ace-chrome .ace_cursor {\
-color: black;\
-}\
-.ace-chrome .ace_invisible {\
-color: rgb(191, 191, 191);\
-}\
-.ace-chrome .ace_constant.ace_buildin {\
-color: rgb(88, 72, 246);\
-}\
-.ace-chrome .ace_constant.ace_language {\
-color: rgb(88, 92, 246);\
-}\
-.ace-chrome .ace_constant.ace_library {\
-color: rgb(6, 150, 14);\
-}\
-.ace-chrome .ace_invalid {\
-background-color: rgb(153, 0, 0);\
-color: white;\
-}\
-.ace-chrome .ace_fold {\
-}\
-.ace-chrome .ace_support.ace_function {\
-color: rgb(60, 76, 114);\
-}\
-.ace-chrome .ace_support.ace_constant {\
-color: rgb(6, 150, 14);\
-}\
-.ace-chrome .ace_support.ace_type,\
-.ace-chrome .ace_support.ace_class\
-.ace-chrome .ace_support.ace_other {\
-color: rgb(109, 121, 222);\
-}\
-.ace-chrome .ace_variable.ace_parameter {\
-font-style:italic;\
-color:#FD971F;\
-}\
-.ace-chrome .ace_keyword.ace_operator {\
-color: rgb(104, 118, 135);\
-}\
-.ace-chrome .ace_comment {\
-color: #236e24;\
-}\
-.ace-chrome .ace_comment.ace_doc {\
-color: #236e24;\
-}\
-.ace-chrome .ace_comment.ace_doc.ace_tag {\
-color: #236e24;\
-}\
-.ace-chrome .ace_constant.ace_numeric {\
-color: rgb(0, 0, 205);\
-}\
-.ace-chrome .ace_variable {\
-color: rgb(49, 132, 149);\
-}\
-.ace-chrome .ace_xml-pe {\
-color: rgb(104, 104, 91);\
-}\
-.ace-chrome .ace_entity.ace_name.ace_function {\
-color: #0000A2;\
-}\
-.ace-chrome .ace_heading {\
-color: rgb(12, 7, 255);\
-}\
-.ace-chrome .ace_list {\
-color:rgb(185, 6, 144);\
-}\
-.ace-chrome .ace_marker-layer .ace_selection {\
-background: rgb(181, 213, 255);\
-}\
-.ace-chrome .ace_marker-layer .ace_step {\
-background: rgb(252, 255, 0);\
-}\
-.ace-chrome .ace_marker-layer .ace_stack {\
-background: rgb(164, 229, 101);\
-}\
-.ace-chrome .ace_marker-layer .ace_bracket {\
-margin: -1px 0 0 -1px;\
-border: 1px solid rgb(192, 192, 192);\
-}\
-.ace-chrome .ace_marker-layer .ace_active-line {\
-background: rgba(0, 0, 0, 0.07);\
-}\
-.ace-chrome .ace_gutter-active-line {\
-background-color : #dcdcdc;\
-}\
-.ace-chrome .ace_marker-layer .ace_selected-word {\
-background: rgb(250, 250, 255);\
-border: 1px solid rgb(200, 200, 250);\
-}\
-.ace-chrome .ace_storage,\
-.ace-chrome .ace_keyword,\
-.ace-chrome .ace_meta.ace_tag {\
-color: rgb(147, 15, 128);\
-}\
-.ace-chrome .ace_string.ace_regex {\
-color: rgb(255, 0, 0)\
-}\
-.ace-chrome .ace_string {\
-color: #1A1AA6;\
-}\
-.ace-chrome .ace_entity.ace_other.ace_attribute-name {\
-color: #994409;\
-}\
-.ace-chrome .ace_indent-guide {\
-background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\
-}\
-";
-
-var dom = require("../lib/dom");
-dom.importCssString(exports.cssText, exports.cssClass);
-});
diff --git a/icestudio/lib/ace-builds/src-noconflict/worker-coffee.js b/icestudio/lib/ace-builds/src-noconflict/worker-coffee.js
deleted file mode 100644
index b3087f81c..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/worker-coffee.js
+++ /dev/null
@@ -1,2159 +0,0 @@
-"no use strict";
-;(function(window) {
-if (typeof window.window != "undefined" && window.document)
- return;
-if (window.require && window.define)
- return;
-
-if (!window.console) {
- window.console = function() {
- var msgs = Array.prototype.slice.call(arguments, 0);
- postMessage({type: "log", data: msgs});
- };
- window.console.error =
- window.console.warn =
- window.console.log =
- window.console.trace = window.console;
-}
-window.window = window;
-window.ace = window;
-
-window.onerror = function(message, file, line, col, err) {
- postMessage({type: "error", data: {
- message: message,
- data: err.data,
- file: file,
- line: line,
- col: col,
- stack: err.stack
- }});
-};
-
-window.normalizeModule = function(parentId, moduleName) {
- // normalize plugin requires
- if (moduleName.indexOf("!") !== -1) {
- var chunks = moduleName.split("!");
- return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]);
- }
- // normalize relative requires
- if (moduleName.charAt(0) == ".") {
- var base = parentId.split("/").slice(0, -1).join("/");
- moduleName = (base ? base + "/" : "") + moduleName;
-
- while (moduleName.indexOf(".") !== -1 && previous != moduleName) {
- var previous = moduleName;
- moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
- }
- }
-
- return moduleName;
-};
-
-window.require = function require(parentId, id) {
- if (!id) {
- id = parentId;
- parentId = null;
- }
- if (!id.charAt)
- throw new Error("worker.js require() accepts only (parentId, id) as arguments");
-
- id = window.normalizeModule(parentId, id);
-
- var module = window.require.modules[id];
- if (module) {
- if (!module.initialized) {
- module.initialized = true;
- module.exports = module.factory().exports;
- }
- return module.exports;
- }
-
- if (!window.require.tlns)
- return console.log("unable to load " + id);
-
- var path = resolveModuleId(id, window.require.tlns);
- if (path.slice(-3) != ".js") path += ".js";
-
- window.require.id = id;
- window.require.modules[id] = {}; // prevent infinite loop on broken modules
- importScripts(path);
- return window.require(parentId, id);
-};
-function resolveModuleId(id, paths) {
- var testPath = id, tail = "";
- while (testPath) {
- var alias = paths[testPath];
- if (typeof alias == "string") {
- return alias + tail;
- } else if (alias) {
- return alias.location.replace(/\/*$/, "/") + (tail || alias.main || alias.name);
- } else if (alias === false) {
- return "";
- }
- var i = testPath.lastIndexOf("/");
- if (i === -1) break;
- tail = testPath.substr(i) + tail;
- testPath = testPath.slice(0, i);
- }
- return id;
-}
-window.require.modules = {};
-window.require.tlns = {};
-
-window.define = function(id, deps, factory) {
- if (arguments.length == 2) {
- factory = deps;
- if (typeof id != "string") {
- deps = id;
- id = window.require.id;
- }
- } else if (arguments.length == 1) {
- factory = id;
- deps = [];
- id = window.require.id;
- }
-
- if (typeof factory != "function") {
- window.require.modules[id] = {
- exports: factory,
- initialized: true
- };
- return;
- }
-
- if (!deps.length)
- // If there is no dependencies, we inject "require", "exports" and
- // "module" as dependencies, to provide CommonJS compatibility.
- deps = ["require", "exports", "module"];
-
- var req = function(childId) {
- return window.require(id, childId);
- };
-
- window.require.modules[id] = {
- exports: {},
- factory: function() {
- var module = this;
- var returnExports = factory.apply(this, deps.map(function(dep) {
- switch (dep) {
- // Because "require", "exports" and "module" aren't actual
- // dependencies, we must handle them seperately.
- case "require": return req;
- case "exports": return module.exports;
- case "module": return module;
- // But for all other dependencies, we can just go ahead and
- // require them.
- default: return req(dep);
- }
- }));
- if (returnExports)
- module.exports = returnExports;
- return module;
- }
- };
-};
-window.define.amd = {};
-require.tlns = {};
-window.initBaseUrls = function initBaseUrls(topLevelNamespaces) {
- for (var i in topLevelNamespaces)
- require.tlns[i] = topLevelNamespaces[i];
-};
-
-window.initSender = function initSender() {
-
- var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter;
- var oop = window.require("ace/lib/oop");
-
- var Sender = function() {};
-
- (function() {
-
- oop.implement(this, EventEmitter);
-
- this.callback = function(data, callbackId) {
- postMessage({
- type: "call",
- id: callbackId,
- data: data
- });
- };
-
- this.emit = function(name, data) {
- postMessage({
- type: "event",
- name: name,
- data: data
- });
- };
-
- }).call(Sender.prototype);
-
- return new Sender();
-};
-
-var main = window.main = null;
-var sender = window.sender = null;
-
-window.onmessage = function(e) {
- var msg = e.data;
- if (msg.event && sender) {
- sender._signal(msg.event, msg.data);
- }
- else if (msg.command) {
- if (main[msg.command])
- main[msg.command].apply(main, msg.args);
- else if (window[msg.command])
- window[msg.command].apply(window, msg.args);
- else
- throw new Error("Unknown command:" + msg.command);
- }
- else if (msg.init) {
- window.initBaseUrls(msg.tlns);
- require("ace/lib/es5-shim");
- sender = window.sender = window.initSender();
- var clazz = require(msg.module)[msg.classname];
- main = window.main = new clazz(sender);
- }
-};
-})(this);
-
-ace.define("ace/lib/oop",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-exports.inherits = function(ctor, superCtor) {
- ctor.super_ = superCtor;
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
-};
-
-exports.mixin = function(obj, mixin) {
- for (var key in mixin) {
- obj[key] = mixin[key];
- }
- return obj;
-};
-
-exports.implement = function(proto, mixin) {
- exports.mixin(proto, mixin);
-};
-
-});
-
-ace.define("ace/range",["require","exports","module"], function(require, exports, module) {
-"use strict";
-var comparePoints = function(p1, p2) {
- return p1.row - p2.row || p1.column - p2.column;
-};
-var Range = function(startRow, startColumn, endRow, endColumn) {
- this.start = {
- row: startRow,
- column: startColumn
- };
-
- this.end = {
- row: endRow,
- column: endColumn
- };
-};
-
-(function() {
- this.isEqual = function(range) {
- return this.start.row === range.start.row &&
- this.end.row === range.end.row &&
- this.start.column === range.start.column &&
- this.end.column === range.end.column;
- };
- this.toString = function() {
- return ("Range: [" + this.start.row + "/" + this.start.column +
- "] -> [" + this.end.row + "/" + this.end.column + "]");
- };
-
- this.contains = function(row, column) {
- return this.compare(row, column) == 0;
- };
- this.compareRange = function(range) {
- var cmp,
- end = range.end,
- start = range.start;
-
- cmp = this.compare(end.row, end.column);
- if (cmp == 1) {
- cmp = this.compare(start.row, start.column);
- if (cmp == 1) {
- return 2;
- } else if (cmp == 0) {
- return 1;
- } else {
- return 0;
- }
- } else if (cmp == -1) {
- return -2;
- } else {
- cmp = this.compare(start.row, start.column);
- if (cmp == -1) {
- return -1;
- } else if (cmp == 1) {
- return 42;
- } else {
- return 0;
- }
- }
- };
- this.comparePoint = function(p) {
- return this.compare(p.row, p.column);
- };
- this.containsRange = function(range) {
- return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0;
- };
- this.intersects = function(range) {
- var cmp = this.compareRange(range);
- return (cmp == -1 || cmp == 0 || cmp == 1);
- };
- this.isEnd = function(row, column) {
- return this.end.row == row && this.end.column == column;
- };
- this.isStart = function(row, column) {
- return this.start.row == row && this.start.column == column;
- };
- this.setStart = function(row, column) {
- if (typeof row == "object") {
- this.start.column = row.column;
- this.start.row = row.row;
- } else {
- this.start.row = row;
- this.start.column = column;
- }
- };
- this.setEnd = function(row, column) {
- if (typeof row == "object") {
- this.end.column = row.column;
- this.end.row = row.row;
- } else {
- this.end.row = row;
- this.end.column = column;
- }
- };
- this.inside = function(row, column) {
- if (this.compare(row, column) == 0) {
- if (this.isEnd(row, column) || this.isStart(row, column)) {
- return false;
- } else {
- return true;
- }
- }
- return false;
- };
- this.insideStart = function(row, column) {
- if (this.compare(row, column) == 0) {
- if (this.isEnd(row, column)) {
- return false;
- } else {
- return true;
- }
- }
- return false;
- };
- this.insideEnd = function(row, column) {
- if (this.compare(row, column) == 0) {
- if (this.isStart(row, column)) {
- return false;
- } else {
- return true;
- }
- }
- return false;
- };
- this.compare = function(row, column) {
- if (!this.isMultiLine()) {
- if (row === this.start.row) {
- return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0);
- }
- }
-
- if (row < this.start.row)
- return -1;
-
- if (row > this.end.row)
- return 1;
-
- if (this.start.row === row)
- return column >= this.start.column ? 0 : -1;
-
- if (this.end.row === row)
- return column <= this.end.column ? 0 : 1;
-
- return 0;
- };
- this.compareStart = function(row, column) {
- if (this.start.row == row && this.start.column == column) {
- return -1;
- } else {
- return this.compare(row, column);
- }
- };
- this.compareEnd = function(row, column) {
- if (this.end.row == row && this.end.column == column) {
- return 1;
- } else {
- return this.compare(row, column);
- }
- };
- this.compareInside = function(row, column) {
- if (this.end.row == row && this.end.column == column) {
- return 1;
- } else if (this.start.row == row && this.start.column == column) {
- return -1;
- } else {
- return this.compare(row, column);
- }
- };
- this.clipRows = function(firstRow, lastRow) {
- if (this.end.row > lastRow)
- var end = {row: lastRow + 1, column: 0};
- else if (this.end.row < firstRow)
- var end = {row: firstRow, column: 0};
-
- if (this.start.row > lastRow)
- var start = {row: lastRow + 1, column: 0};
- else if (this.start.row < firstRow)
- var start = {row: firstRow, column: 0};
-
- return Range.fromPoints(start || this.start, end || this.end);
- };
- this.extend = function(row, column) {
- var cmp = this.compare(row, column);
-
- if (cmp == 0)
- return this;
- else if (cmp == -1)
- var start = {row: row, column: column};
- else
- var end = {row: row, column: column};
-
- return Range.fromPoints(start || this.start, end || this.end);
- };
-
- this.isEmpty = function() {
- return (this.start.row === this.end.row && this.start.column === this.end.column);
- };
- this.isMultiLine = function() {
- return (this.start.row !== this.end.row);
- };
- this.clone = function() {
- return Range.fromPoints(this.start, this.end);
- };
- this.collapseRows = function() {
- if (this.end.column == 0)
- return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0)
- else
- return new Range(this.start.row, 0, this.end.row, 0)
- };
- this.toScreenRange = function(session) {
- var screenPosStart = session.documentToScreenPosition(this.start);
- var screenPosEnd = session.documentToScreenPosition(this.end);
-
- return new Range(
- screenPosStart.row, screenPosStart.column,
- screenPosEnd.row, screenPosEnd.column
- );
- };
- this.moveBy = function(row, column) {
- this.start.row += row;
- this.start.column += column;
- this.end.row += row;
- this.end.column += column;
- };
-
-}).call(Range.prototype);
-Range.fromPoints = function(start, end) {
- return new Range(start.row, start.column, end.row, end.column);
-};
-Range.comparePoints = comparePoints;
-
-Range.comparePoints = function(p1, p2) {
- return p1.row - p2.row || p1.column - p2.column;
-};
-
-
-exports.Range = Range;
-});
-
-ace.define("ace/apply_delta",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-function throwDeltaError(delta, errorText){
- console.log("Invalid Delta:", delta);
- throw "Invalid Delta: " + errorText;
-}
-
-function positionInDocument(docLines, position) {
- return position.row >= 0 && position.row < docLines.length &&
- position.column >= 0 && position.column <= docLines[position.row].length;
-}
-
-function validateDelta(docLines, delta) {
- if (delta.action != "insert" && delta.action != "remove")
- throwDeltaError(delta, "delta.action must be 'insert' or 'remove'");
- if (!(delta.lines instanceof Array))
- throwDeltaError(delta, "delta.lines must be an Array");
- if (!delta.start || !delta.end)
- throwDeltaError(delta, "delta.start/end must be an present");
- var start = delta.start;
- if (!positionInDocument(docLines, delta.start))
- throwDeltaError(delta, "delta.start must be contained in document");
- var end = delta.end;
- if (delta.action == "remove" && !positionInDocument(docLines, end))
- throwDeltaError(delta, "delta.end must contained in document for 'remove' actions");
- var numRangeRows = end.row - start.row;
- var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0));
- if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars)
- throwDeltaError(delta, "delta.range must match delta lines");
-}
-
-exports.applyDelta = function(docLines, delta, doNotValidate) {
-
- var row = delta.start.row;
- var startColumn = delta.start.column;
- var line = docLines[row] || "";
- switch (delta.action) {
- case "insert":
- var lines = delta.lines;
- if (lines.length === 1) {
- docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn);
- } else {
- var args = [row, 1].concat(delta.lines);
- docLines.splice.apply(docLines, args);
- docLines[row] = line.substring(0, startColumn) + docLines[row];
- docLines[row + delta.lines.length - 1] += line.substring(startColumn);
- }
- break;
- case "remove":
- var endColumn = delta.end.column;
- var endRow = delta.end.row;
- if (row === endRow) {
- docLines[row] = line.substring(0, startColumn) + line.substring(endColumn);
- } else {
- docLines.splice(
- row, endRow - row + 1,
- line.substring(0, startColumn) + docLines[endRow].substring(endColumn)
- );
- }
- break;
- }
-}
-});
-
-ace.define("ace/lib/event_emitter",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-var EventEmitter = {};
-var stopPropagation = function() { this.propagationStopped = true; };
-var preventDefault = function() { this.defaultPrevented = true; };
-
-EventEmitter._emit =
-EventEmitter._dispatchEvent = function(eventName, e) {
- this._eventRegistry || (this._eventRegistry = {});
- this._defaultHandlers || (this._defaultHandlers = {});
-
- var listeners = this._eventRegistry[eventName] || [];
- var defaultHandler = this._defaultHandlers[eventName];
- if (!listeners.length && !defaultHandler)
- return;
-
- if (typeof e != "object" || !e)
- e = {};
-
- if (!e.type)
- e.type = eventName;
- if (!e.stopPropagation)
- e.stopPropagation = stopPropagation;
- if (!e.preventDefault)
- e.preventDefault = preventDefault;
-
- listeners = listeners.slice();
- for (var i=0; i this.row)
- return;
-
- var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight);
- this.setPosition(point.row, point.column, true);
- };
-
- function $pointsInOrder(point1, point2, equalPointsInOrder) {
- var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column;
- return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter);
- }
-
- function $getTransformedPoint(delta, point, moveIfEqual) {
- var deltaIsInsert = delta.action == "insert";
- var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row);
- var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column);
- var deltaStart = delta.start;
- var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range.
- if ($pointsInOrder(point, deltaStart, moveIfEqual)) {
- return {
- row: point.row,
- column: point.column
- };
- }
- if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) {
- return {
- row: point.row + deltaRowShift,
- column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0)
- };
- }
-
- return {
- row: deltaStart.row,
- column: deltaStart.column
- };
- }
- this.setPosition = function(row, column, noClip) {
- var pos;
- if (noClip) {
- pos = {
- row: row,
- column: column
- };
- } else {
- pos = this.$clipPositionToDocument(row, column);
- }
-
- if (this.row == pos.row && this.column == pos.column)
- return;
-
- var old = {
- row: this.row,
- column: this.column
- };
-
- this.row = pos.row;
- this.column = pos.column;
- this._signal("change", {
- old: old,
- value: pos
- });
- };
- this.detach = function() {
- this.document.removeEventListener("change", this.$onChange);
- };
- this.attach = function(doc) {
- this.document = doc || this.document;
- this.document.on("change", this.$onChange);
- };
- this.$clipPositionToDocument = function(row, column) {
- var pos = {};
-
- if (row >= this.document.getLength()) {
- pos.row = Math.max(0, this.document.getLength() - 1);
- pos.column = this.document.getLine(pos.row).length;
- }
- else if (row < 0) {
- pos.row = 0;
- pos.column = 0;
- }
- else {
- pos.row = row;
- pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column));
- }
-
- if (column < 0)
- pos.column = 0;
-
- return pos;
- };
-
-}).call(Anchor.prototype);
-
-});
-
-ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(require, exports, module) {
-"use strict";
-
-var oop = require("./lib/oop");
-var applyDelta = require("./apply_delta").applyDelta;
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-var Range = require("./range").Range;
-var Anchor = require("./anchor").Anchor;
-
-var Document = function(textOrLines) {
- this.$lines = [""];
- if (textOrLines.length === 0) {
- this.$lines = [""];
- } else if (Array.isArray(textOrLines)) {
- this.insertMergedLines({row: 0, column: 0}, textOrLines);
- } else {
- this.insert({row: 0, column:0}, textOrLines);
- }
-};
-
-(function() {
-
- oop.implement(this, EventEmitter);
- this.setValue = function(text) {
- var len = this.getLength() - 1;
- this.remove(new Range(0, 0, len, this.getLine(len).length));
- this.insert({row: 0, column: 0}, text);
- };
- this.getValue = function() {
- return this.getAllLines().join(this.getNewLineCharacter());
- };
- this.createAnchor = function(row, column) {
- return new Anchor(this, row, column);
- };
- if ("aaa".split(/a/).length === 0) {
- this.$split = function(text) {
- return text.replace(/\r\n|\r/g, "\n").split("\n");
- };
- } else {
- this.$split = function(text) {
- return text.split(/\r\n|\r|\n/);
- };
- }
-
-
- this.$detectNewLine = function(text) {
- var match = text.match(/^.*?(\r\n|\r|\n)/m);
- this.$autoNewLine = match ? match[1] : "\n";
- this._signal("changeNewLineMode");
- };
- this.getNewLineCharacter = function() {
- switch (this.$newLineMode) {
- case "windows":
- return "\r\n";
- case "unix":
- return "\n";
- default:
- return this.$autoNewLine || "\n";
- }
- };
-
- this.$autoNewLine = "";
- this.$newLineMode = "auto";
- this.setNewLineMode = function(newLineMode) {
- if (this.$newLineMode === newLineMode)
- return;
-
- this.$newLineMode = newLineMode;
- this._signal("changeNewLineMode");
- };
- this.getNewLineMode = function() {
- return this.$newLineMode;
- };
- this.isNewLine = function(text) {
- return (text == "\r\n" || text == "\r" || text == "\n");
- };
- this.getLine = function(row) {
- return this.$lines[row] || "";
- };
- this.getLines = function(firstRow, lastRow) {
- return this.$lines.slice(firstRow, lastRow + 1);
- };
- this.getAllLines = function() {
- return this.getLines(0, this.getLength());
- };
- this.getLength = function() {
- return this.$lines.length;
- };
- this.getTextRange = function(range) {
- return this.getLinesForRange(range).join(this.getNewLineCharacter());
- };
- this.getLinesForRange = function(range) {
- var lines;
- if (range.start.row === range.end.row) {
- lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)];
- } else {
- lines = this.getLines(range.start.row, range.end.row);
- lines[0] = (lines[0] || "").substring(range.start.column);
- var l = lines.length - 1;
- if (range.end.row - range.start.row == l)
- lines[l] = lines[l].substring(0, range.end.column);
- }
- return lines;
- };
- this.insertLines = function(row, lines) {
- console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead.");
- return this.insertFullLines(row, lines);
- };
- this.removeLines = function(firstRow, lastRow) {
- console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead.");
- return this.removeFullLines(firstRow, lastRow);
- };
- this.insertNewLine = function(position) {
- console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, [\'\', \'\']) instead.");
- return this.insertMergedLines(position, ["", ""]);
- };
- this.insert = function(position, text) {
- if (this.getLength() <= 1)
- this.$detectNewLine(text);
-
- return this.insertMergedLines(position, this.$split(text));
- };
- this.insertInLine = function(position, text) {
- var start = this.clippedPos(position.row, position.column);
- var end = this.pos(position.row, position.column + text.length);
-
- this.applyDelta({
- start: start,
- end: end,
- action: "insert",
- lines: [text]
- }, true);
-
- return this.clonePos(end);
- };
-
- this.clippedPos = function(row, column) {
- var length = this.getLength();
- if (row === undefined) {
- row = length;
- } else if (row < 0) {
- row = 0;
- } else if (row >= length) {
- row = length - 1;
- column = undefined;
- }
- var line = this.getLine(row);
- if (column == undefined)
- column = line.length;
- column = Math.min(Math.max(column, 0), line.length);
- return {row: row, column: column};
- };
-
- this.clonePos = function(pos) {
- return {row: pos.row, column: pos.column};
- };
-
- this.pos = function(row, column) {
- return {row: row, column: column};
- };
-
- this.$clipPosition = function(position) {
- var length = this.getLength();
- if (position.row >= length) {
- position.row = Math.max(0, length - 1);
- position.column = this.getLine(length - 1).length;
- } else {
- position.row = Math.max(0, position.row);
- position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length);
- }
- return position;
- };
- this.insertFullLines = function(row, lines) {
- row = Math.min(Math.max(row, 0), this.getLength());
- var column = 0;
- if (row < this.getLength()) {
- lines = lines.concat([""]);
- column = 0;
- } else {
- lines = [""].concat(lines);
- row--;
- column = this.$lines[row].length;
- }
- this.insertMergedLines({row: row, column: column}, lines);
- };
- this.insertMergedLines = function(position, lines) {
- var start = this.clippedPos(position.row, position.column);
- var end = {
- row: start.row + lines.length - 1,
- column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length
- };
-
- this.applyDelta({
- start: start,
- end: end,
- action: "insert",
- lines: lines
- });
-
- return this.clonePos(end);
- };
- this.remove = function(range) {
- var start = this.clippedPos(range.start.row, range.start.column);
- var end = this.clippedPos(range.end.row, range.end.column);
- this.applyDelta({
- start: start,
- end: end,
- action: "remove",
- lines: this.getLinesForRange({start: start, end: end})
- });
- return this.clonePos(start);
- };
- this.removeInLine = function(row, startColumn, endColumn) {
- var start = this.clippedPos(row, startColumn);
- var end = this.clippedPos(row, endColumn);
-
- this.applyDelta({
- start: start,
- end: end,
- action: "remove",
- lines: this.getLinesForRange({start: start, end: end})
- }, true);
-
- return this.clonePos(start);
- };
- this.removeFullLines = function(firstRow, lastRow) {
- firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1);
- lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1);
- var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0;
- var deleteLastNewLine = lastRow < this.getLength() - 1;
- var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow );
- var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 );
- var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow );
- var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length );
- var range = new Range(startRow, startCol, endRow, endCol);
- var deletedLines = this.$lines.slice(firstRow, lastRow + 1);
-
- this.applyDelta({
- start: range.start,
- end: range.end,
- action: "remove",
- lines: this.getLinesForRange(range)
- });
- return deletedLines;
- };
- this.removeNewLine = function(row) {
- if (row < this.getLength() - 1 && row >= 0) {
- this.applyDelta({
- start: this.pos(row, this.getLine(row).length),
- end: this.pos(row + 1, 0),
- action: "remove",
- lines: ["", ""]
- });
- }
- };
- this.replace = function(range, text) {
- if (!(range instanceof Range))
- range = Range.fromPoints(range.start, range.end);
- if (text.length === 0 && range.isEmpty())
- return range.start;
- if (text == this.getTextRange(range))
- return range.end;
-
- this.remove(range);
- var end;
- if (text) {
- end = this.insert(range.start, text);
- }
- else {
- end = range.start;
- }
-
- return end;
- };
- this.applyDeltas = function(deltas) {
- for (var i=0; i=0; i--) {
- this.revertDelta(deltas[i]);
- }
- };
- this.applyDelta = function(delta, doNotValidate) {
- var isInsert = delta.action == "insert";
- if (isInsert ? delta.lines.length <= 1 && !delta.lines[0]
- : !Range.comparePoints(delta.start, delta.end)) {
- return;
- }
-
- if (isInsert && delta.lines.length > 20000)
- this.$splitAndapplyLargeDelta(delta, 20000);
- applyDelta(this.$lines, delta, doNotValidate);
- this._signal("change", delta);
- };
-
- this.$splitAndapplyLargeDelta = function(delta, MAX) {
- var lines = delta.lines;
- var l = lines.length;
- var row = delta.start.row;
- var column = delta.start.column;
- var from = 0, to = 0;
- do {
- from = to;
- to += MAX - 1;
- var chunk = lines.slice(from, to);
- if (to > l) {
- delta.lines = chunk;
- delta.start.row = row + from;
- delta.start.column = column;
- break;
- }
- chunk.push("");
- this.applyDelta({
- start: this.pos(row + from, column),
- end: this.pos(row + to, column = 0),
- action: delta.action,
- lines: chunk
- }, true);
- } while(true);
- };
- this.revertDelta = function(delta) {
- this.applyDelta({
- start: this.clonePos(delta.start),
- end: this.clonePos(delta.end),
- action: (delta.action == "insert" ? "remove" : "insert"),
- lines: delta.lines.slice()
- });
- };
- this.indexToPosition = function(index, startRow) {
- var lines = this.$lines || this.getAllLines();
- var newlineLength = this.getNewLineCharacter().length;
- for (var i = startRow || 0, l = lines.length; i < l; i++) {
- index -= lines[i].length + newlineLength;
- if (index < 0)
- return {row: i, column: index + lines[i].length + newlineLength};
- }
- return {row: l-1, column: lines[l-1].length};
- };
- this.positionToIndex = function(pos, startRow) {
- var lines = this.$lines || this.getAllLines();
- var newlineLength = this.getNewLineCharacter().length;
- var index = 0;
- var row = Math.min(pos.row, lines.length);
- for (var i = startRow || 0; i < row; ++i)
- index += lines[i].length + newlineLength;
-
- return index + pos.column;
- };
-
-}).call(Document.prototype);
-
-exports.Document = Document;
-});
-
-ace.define("ace/lib/lang",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-exports.last = function(a) {
- return a[a.length - 1];
-};
-
-exports.stringReverse = function(string) {
- return string.split("").reverse().join("");
-};
-
-exports.stringRepeat = function (string, count) {
- var result = '';
- while (count > 0) {
- if (count & 1)
- result += string;
-
- if (count >>= 1)
- string += string;
- }
- return result;
-};
-
-var trimBeginRegexp = /^\s\s*/;
-var trimEndRegexp = /\s\s*$/;
-
-exports.stringTrimLeft = function (string) {
- return string.replace(trimBeginRegexp, '');
-};
-
-exports.stringTrimRight = function (string) {
- return string.replace(trimEndRegexp, '');
-};
-
-exports.copyObject = function(obj) {
- var copy = {};
- for (var key in obj) {
- copy[key] = obj[key];
- }
- return copy;
-};
-
-exports.copyArray = function(array){
- var copy = [];
- for (var i=0, l=array.length; i0;)1&t&&(n+=e),t>>>=1,e+=e;return n},e.compact=function(e){var t,n,i,r;for(r=[],t=0,i=e.length;i>t;t++)n=e[t],n&&r.push(n);return r},e.count=function(e,t){var n,i;if(n=i=0,!t.length)return 1/0;for(;i=1+e.indexOf(t,i);)n++;return n},e.merge=function(e,t){return n(n({},e),t)},n=e.extend=function(e,t){var n,i;for(n in t)i=t[n],e[n]=i;return e},e.flatten=i=function(e){var t,n,r,s;for(n=[],r=0,s=e.length;s>r;r++)t=e[r],t instanceof Array?n=n.concat(i(t)):n.push(t);return n},e.del=function(e,t){var n;return n=e[t],delete e[t],n},e.some=null!=(r=Array.prototype.some)?r:function(e){var t,n,i;for(n=0,i=this.length;i>n;n++)if(t=this[n],e(t))return!0;return!1},e.invertLiterate=function(e){var t,n,i;return i=!0,n=function(){var n,r,s,o;for(s=e.split("\n"),o=[],n=0,r=s.length;r>n;n++)t=s[n],i&&/^([ ]{4}|[ ]{0,3}\t)/.test(t)?o.push(t):(i=/^\s*$/.test(t))?o.push(t):o.push("# "+t);return o}(),n.join("\n")},t=function(e,t){return t?{first_line:e.first_line,first_column:e.first_column,last_line:t.last_line,last_column:t.last_column}:e},e.addLocationDataFn=function(e,n){return function(i){return"object"==typeof i&&i.updateLocationDataIfMissing&&i.updateLocationDataIfMissing(t(e,n)),i}},e.locationDataToString=function(e){var t;return"2"in e&&"first_line"in e[2]?t=e[2]:"first_line"in e&&(t=e),t?t.first_line+1+":"+(t.first_column+1)+"-"+(t.last_line+1+":"+(t.last_column+1)):"No location data"},e.baseFileName=function(e,t,n){var i,r;return null==t&&(t=!1),null==n&&(n=!1),r=n?/\\|\//:/\//,i=e.split(r),e=i[i.length-1],t&&e.indexOf(".")>=0?(i=e.split("."),i.pop(),"coffee"===i[i.length-1]&&i.length>1&&i.pop(),i.join(".")):e},e.isCoffee=function(e){return/\.((lit)?coffee|coffee\.md)$/.test(e)},e.isLiterate=function(e){return/\.(litcoffee|coffee\.md)$/.test(e)},e.throwSyntaxError=function(e,t){var n;throw n=new SyntaxError(e),n.location=t,n.toString=o,n.stack=""+n,n},e.updateSyntaxError=function(e,t,n){return e.toString===o&&(e.code||(e.code=t),e.filename||(e.filename=n),e.stack=""+e),e},o=function(){var e,t,n,i,r,o,a,c,h,l,u,p,d,f,m;return this.code&&this.location?(u=this.location,a=u.first_line,o=u.first_column,h=u.last_line,c=u.last_column,null==h&&(h=a),null==c&&(c=o),r=this.filename||"[stdin]",e=this.code.split("\n")[a],m=o,i=a===h?c+1:e.length,l=e.slice(0,m).replace(/[^\s]/g," ")+s("^",i-m),"undefined"!=typeof process&&null!==process&&(n=(null!=(p=process.stdout)?p.isTTY:void 0)&&!(null!=(d=process.env)?d.NODE_DISABLE_COLORS:void 0)),(null!=(f=this.colorful)?f:n)&&(t=function(e){return"[1;31m"+e+"[0m"},e=e.slice(0,m)+t(e.slice(m,i))+e.slice(i),l=t(l)),r+":"+(a+1)+":"+(o+1)+": error: "+this.message+"\n"+e+"\n"+l):Error.prototype.toString.call(this)},e.nameWhitespaceCharacter=function(e){switch(e){case" ":return"space";case"\n":return"newline";case"\r":return"carriage return";case" ":return"tab";default:return e}}}.call(this),t.exports}(),_dereq_["./rewriter"]=function(){var e={},t={exports:e};return function(){var t,n,i,r,s,o,a,c,h,l,u,p,d,f,m,g,v,y,b,k=[].indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(t in this&&this[t]===e)return t;return-1},w=[].slice;for(f=function(e,t,n){var i;return i=[e,t],i.generated=!0,n&&(i.origin=n),i},e.Rewriter=function(){function e(){}return e.prototype.rewrite=function(e){return this.tokens=e,this.removeLeadingNewlines(),this.closeOpenCalls(),this.closeOpenIndexes(),this.normalizeLines(),this.tagPostfixConditionals(),this.addImplicitBracesAndParens(),this.addLocationDataToGeneratedTokens(),this.tokens},e.prototype.scanTokens=function(e){var t,n,i;for(i=this.tokens,t=0;n=i[t];)t+=e.call(this,n,t,i);return!0},e.prototype.detectEnd=function(e,t,n){var i,o,a,c,h;for(h=this.tokens,i=0;c=h[e];){if(0===i&&t.call(this,c,e))return n.call(this,c,e);if(!c||0>i)return n.call(this,c,e-1);o=c[0],k.call(s,o)>=0?i+=1:(a=c[0],k.call(r,a)>=0&&(i-=1)),e+=1}return e-1},e.prototype.removeLeadingNewlines=function(){var e,t,n,i,r;for(i=this.tokens,e=t=0,n=i.length;n>t&&(r=i[e][0],"TERMINATOR"===r);e=++t);return e?this.tokens.splice(0,e):void 0},e.prototype.closeOpenCalls=function(){var e,t;return t=function(e,t){var n;return")"===(n=e[0])||"CALL_END"===n||"OUTDENT"===e[0]&&")"===this.tag(t-1)},e=function(e,t){return this.tokens["OUTDENT"===e[0]?t-1:t][0]="CALL_END"},this.scanTokens(function(n,i){return"CALL_START"===n[0]&&this.detectEnd(i+1,t,e),1})},e.prototype.closeOpenIndexes=function(){var e,t;return t=function(e){var t;return"]"===(t=e[0])||"INDEX_END"===t},e=function(e){return e[0]="INDEX_END"},this.scanTokens(function(n,i){return"INDEX_START"===n[0]&&this.detectEnd(i+1,t,e),1})},e.prototype.indexOfTag=function(){var e,t,n,i,r,s,o;for(t=arguments[0],r=arguments.length>=2?w.call(arguments,1):[],e=0,n=i=0,s=r.length;s>=0?s>i:i>s;n=s>=0?++i:--i){for(;"HERECOMMENT"===this.tag(t+n+e);)e+=2;if(null!=r[n]&&("string"==typeof r[n]&&(r[n]=[r[n]]),o=this.tag(t+n+e),0>k.call(r[n],o)))return-1}return t+n+e-1},e.prototype.looksObjectish=function(e){var t,n;return this.indexOfTag(e,"@",null,":")>-1||this.indexOfTag(e,null,":")>-1?!0:(n=this.indexOfTag(e,s),n>-1&&(t=null,this.detectEnd(n+1,function(e){var t;return t=e[0],k.call(r,t)>=0},function(e,n){return t=n}),":"===this.tag(t+1))?!0:!1)},e.prototype.findTagsBackwards=function(e,t){var n,i,o,a,c,h,l;for(n=[];e>=0&&(n.length||(a=this.tag(e),0>k.call(t,a)&&(c=this.tag(e),0>k.call(s,c)||this.tokens[e].generated)&&(h=this.tag(e),0>k.call(u,h))));)i=this.tag(e),k.call(r,i)>=0&&n.push(this.tag(e)),o=this.tag(e),k.call(s,o)>=0&&n.length&&n.pop(),e-=1;return l=this.tag(e),k.call(t,l)>=0},e.prototype.addImplicitBracesAndParens=function(){var e,t;return e=[],t=null,this.scanTokens(function(i,l,p){var d,m,g,v,y,b,w,T,C,E,F,N,L,x,S,D,R,A,I,_,O,$,j,M,B,V,P,U;if(U=i[0],F=(N=l>0?p[l-1]:[])[0],C=(p.length-1>l?p[l+1]:[])[0],j=function(){return e[e.length-1]},M=l,g=function(e){return l-M+e},v=function(){var e,t;return null!=(e=j())?null!=(t=e[2])?t.ours:void 0:void 0},y=function(){var e;return v()&&"("===(null!=(e=j())?e[0]:void 0)},w=function(){var e;return v()&&"{"===(null!=(e=j())?e[0]:void 0)},b=function(){var e;return v&&"CONTROL"===(null!=(e=j())?e[0]:void 0)},B=function(t){var n;return n=null!=t?t:l,e.push(["(",n,{ours:!0}]),p.splice(n,0,f("CALL_START","(")),null==t?l+=1:void 0},d=function(){return e.pop(),p.splice(l,0,f("CALL_END",")",["","end of input",i[2]])),l+=1},V=function(t,n){var r,s;return null==n&&(n=!0),r=null!=t?t:l,e.push(["{",r,{sameLine:!0,startsLine:n,ours:!0}]),s=new String("{"),s.generated=!0,p.splice(r,0,f("{",s,i)),null==t?l+=1:void 0},m=function(t){return t=null!=t?t:l,e.pop(),p.splice(t,0,f("}","}",i)),l+=1},y()&&("IF"===U||"TRY"===U||"FINALLY"===U||"CATCH"===U||"CLASS"===U||"SWITCH"===U))return e.push(["CONTROL",l,{ours:!0}]),g(1);if("INDENT"===U&&v()){if("=>"!==F&&"->"!==F&&"["!==F&&"("!==F&&","!==F&&"{"!==F&&"TRY"!==F&&"ELSE"!==F&&"="!==F)for(;y();)d();return b()&&e.pop(),e.push([U,l]),g(1)}if(k.call(s,U)>=0)return e.push([U,l]),g(1);if(k.call(r,U)>=0){for(;v();)y()?d():w()?m():e.pop();t=e.pop()}if((k.call(c,U)>=0&&i.spaced||"?"===U&&l>0&&!p[l-1].spaced)&&(k.call(o,C)>=0||k.call(h,C)>=0&&!(null!=(L=p[l+1])?L.spaced:void 0)&&!(null!=(x=p[l+1])?x.newLine:void 0)))return"?"===U&&(U=i[0]="FUNC_EXIST"),B(l+1),g(2);if(k.call(c,U)>=0&&this.indexOfTag(l+1,"INDENT")>-1&&this.looksObjectish(l+2)&&!this.findTagsBackwards(l,["CLASS","EXTENDS","IF","CATCH","SWITCH","LEADING_WHEN","FOR","WHILE","UNTIL"]))return B(l+1),e.push(["INDENT",l+2]),g(3);if(":"===U){for(I=function(){var e;switch(!1){case e=this.tag(l-1),0>k.call(r,e):return t[1];case"@"!==this.tag(l-2):return l-2;default:return l-1}}.call(this);"HERECOMMENT"===this.tag(I-2);)I-=2;return this.insideForDeclaration="FOR"===C,P=0===I||(S=this.tag(I-1),k.call(u,S)>=0)||p[I-1].newLine,j()&&(D=j(),$=D[0],O=D[1],("{"===$||"INDENT"===$&&"{"===this.tag(O-1))&&(P||","===this.tag(I-1)||"{"===this.tag(I-1)))?g(1):(V(I,!!P),g(2))}if(w()&&k.call(u,U)>=0&&(j()[2].sameLine=!1),T="OUTDENT"===F||N.newLine,k.call(a,U)>=0||k.call(n,U)>=0&&T)for(;v();)if(R=j(),$=R[0],O=R[1],A=R[2],_=A.sameLine,P=A.startsLine,y()&&","!==F)d();else if(w()&&!this.insideForDeclaration&&_&&"TERMINATOR"!==U&&":"!==F)m();else{if(!w()||"TERMINATOR"!==U||","===F||P&&this.looksObjectish(l+1))break;if("HERECOMMENT"===C)return g(1);m()}if(!(","!==U||this.looksObjectish(l+1)||!w()||this.insideForDeclaration||"TERMINATOR"===C&&this.looksObjectish(l+2)))for(E="OUTDENT"===C?1:0;w();)m(l+E);return g(1)})},e.prototype.addLocationDataToGeneratedTokens=function(){return this.scanTokens(function(e,t,n){var i,r,s,o,a,c;return e[2]?1:e.generated||e.explicit?("{"===e[0]&&(s=null!=(a=n[t+1])?a[2]:void 0)?(r=s.first_line,i=s.first_column):(o=null!=(c=n[t-1])?c[2]:void 0)?(r=o.last_line,i=o.last_column):r=i=0,e[2]={first_line:r,first_column:i,last_line:r,last_column:i},1):1})},e.prototype.normalizeLines=function(){var e,t,r,s,o;return o=r=s=null,t=function(e,t){var r,s,a,c;return";"!==e[1]&&(r=e[0],k.call(p,r)>=0)&&!("TERMINATOR"===e[0]&&(s=this.tag(t+1),k.call(i,s)>=0))&&!("ELSE"===e[0]&&"THEN"!==o)&&!!("CATCH"!==(a=e[0])&&"FINALLY"!==a||"->"!==o&&"=>"!==o)||(c=e[0],k.call(n,c)>=0&&this.tokens[t-1].newLine)},e=function(e,t){return this.tokens.splice(","===this.tag(t-1)?t-1:t,0,s)},this.scanTokens(function(n,a,c){var h,l,u,p,f,m;if(m=n[0],"TERMINATOR"===m){if("ELSE"===this.tag(a+1)&&"OUTDENT"!==this.tag(a-1))return c.splice.apply(c,[a,1].concat(w.call(this.indentation()))),1;if(u=this.tag(a+1),k.call(i,u)>=0)return c.splice(a,1),0}if("CATCH"===m)for(h=l=1;2>=l;h=++l)if("OUTDENT"===(p=this.tag(a+h))||"TERMINATOR"===p||"FINALLY"===p)return c.splice.apply(c,[a+h,0].concat(w.call(this.indentation()))),2+h;return k.call(d,m)>=0&&"INDENT"!==this.tag(a+1)&&("ELSE"!==m||"IF"!==this.tag(a+1))?(o=m,f=this.indentation(c[a]),r=f[0],s=f[1],"THEN"===o&&(r.fromThen=!0),c.splice(a+1,0,r),this.detectEnd(a+2,t,e),"THEN"===m&&c.splice(a,1),1):1})},e.prototype.tagPostfixConditionals=function(){var e,t,n;return n=null,t=function(e,t){var n,i;return i=e[0],n=this.tokens[t-1][0],"TERMINATOR"===i||"INDENT"===i&&0>k.call(d,n)},e=function(e){return"INDENT"!==e[0]||e.generated&&!e.fromThen?n[0]="POST_"+n[0]:void 0},this.scanTokens(function(i,r){return"IF"!==i[0]?1:(n=i,this.detectEnd(r+1,t,e),1)})},e.prototype.indentation=function(e){var t,n;return t=["INDENT",2],n=["OUTDENT",2],e?(t.generated=n.generated=!0,t.origin=n.origin=e):t.explicit=n.explicit=!0,[t,n]},e.prototype.generate=f,e.prototype.tag=function(e){var t;return null!=(t=this.tokens[e])?t[0]:void 0},e}(),t=[["(",")"],["[","]"],["{","}"],["INDENT","OUTDENT"],["CALL_START","CALL_END"],["PARAM_START","PARAM_END"],["INDEX_START","INDEX_END"],["STRING_START","STRING_END"],["REGEX_START","REGEX_END"]],e.INVERSES=l={},s=[],r=[],m=0,v=t.length;v>m;m++)y=t[m],g=y[0],b=y[1],s.push(l[b]=g),r.push(l[g]=b);i=["CATCH","THEN","ELSE","FINALLY"].concat(r),c=["IDENTIFIER","SUPER",")","CALL_END","]","INDEX_END","@","THIS"],o=["IDENTIFIER","NUMBER","STRING","STRING_START","JS","REGEX","REGEX_START","NEW","PARAM_START","CLASS","IF","TRY","SWITCH","THIS","BOOL","NULL","UNDEFINED","UNARY","YIELD","UNARY_MATH","SUPER","THROW","@","->","=>","[","(","{","--","++"],h=["+","-"],a=["POST_IF","FOR","WHILE","UNTIL","WHEN","BY","LOOP","TERMINATOR"],d=["ELSE","->","=>","TRY","FINALLY","THEN"],p=["TERMINATOR","CATCH","FINALLY","ELSE","OUTDENT","LEADING_WHEN"],u=["TERMINATOR","INDENT","OUTDENT"],n=[".","?.","::","?::"]}.call(this),t.exports}(),_dereq_["./lexer"]=function(){var e={},t={exports:e};return function(){var t,n,i,r,s,o,a,c,h,l,u,p,d,f,m,g,v,y,b,k,w,T,C,E,F,N,L,x,S,D,R,A,I,_,O,$,j,M,B,V,P,U,G,H,q,X,W,Y,K,z,J,Q,Z,et,tt,nt,it,rt,st,ot,at,ct,ht,lt,ut=[].indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(t in this&&this[t]===e)return t;return-1};ot=_dereq_("./rewriter"),P=ot.Rewriter,w=ot.INVERSES,at=_dereq_("./helpers"),nt=at.count,ht=at.starts,tt=at.compact,ct=at.repeat,it=at.invertLiterate,st=at.locationDataToString,lt=at.throwSyntaxError,e.Lexer=S=function(){function e(){}return e.prototype.tokenize=function(e,t){var n,i,r,s;for(null==t&&(t={}),this.literate=t.literate,this.indent=0,this.baseIndent=0,this.indebt=0,this.outdebt=0,this.indents=[],this.ends=[],this.tokens=[],this.chunkLine=t.line||0,this.chunkColumn=t.column||0,e=this.clean(e),r=0;this.chunk=e.slice(r);)if(n=this.identifierToken()||this.commentToken()||this.whitespaceToken()||this.lineToken()||this.stringToken()||this.numberToken()||this.regexToken()||this.jsToken()||this.literalToken(),s=this.getLineAndColumnFromChunk(n),this.chunkLine=s[0],this.chunkColumn=s[1],r+=n,t.untilBalanced&&0===this.ends.length)return{tokens:this.tokens,index:r};return this.closeIndentation(),(i=this.ends.pop())&&this.error("missing "+i.tag,i.origin[2]),t.rewrite===!1?this.tokens:(new P).rewrite(this.tokens)},e.prototype.clean=function(e){return e.charCodeAt(0)===t&&(e=e.slice(1)),e=e.replace(/\r/g,"").replace(z,""),et.test(e)&&(e="\n"+e,this.chunkLine--),this.literate&&(e=it(e)),e},e.prototype.identifierToken=function(){var e,t,n,i,r,c,h,l,u,p,d,f,m,g,y,b;return(l=v.exec(this.chunk))?(h=l[0],r=l[1],t=l[2],c=r.length,u=void 0,"own"===r&&"FOR"===this.tag()?(this.token("OWN",r),r.length):"from"===r&&"YIELD"===this.tag()?(this.token("FROM",r),r.length):(d=this.tokens,p=d[d.length-1],i=t||null!=p&&("."===(f=p[0])||"?."===f||"::"===f||"?::"===f||!p.spaced&&"@"===p[0]),y="IDENTIFIER",!i&&(ut.call(E,r)>=0||ut.call(a,r)>=0)&&(y=r.toUpperCase(),"WHEN"===y&&(m=this.tag(),ut.call(N,m)>=0)?y="LEADING_WHEN":"FOR"===y?this.seenFor=!0:"UNLESS"===y?y="IF":ut.call(J,y)>=0?y="UNARY":ut.call(B,y)>=0&&("INSTANCEOF"!==y&&this.seenFor?(y="FOR"+y,this.seenFor=!1):(y="RELATION","!"===this.value()&&(u=this.tokens.pop(),r="!"+r)))),ut.call(C,r)>=0&&(i?(y="IDENTIFIER",r=new String(r),r.reserved=!0):ut.call(V,r)>=0&&this.error("reserved word '"+r+"'",{length:r.length})),i||(ut.call(s,r)>=0&&(e=r,r=o[r]),y=function(){switch(r){case"!":return"UNARY";case"==":case"!=":return"COMPARE";case"&&":case"||":return"LOGIC";case"true":case"false":return"BOOL";case"break":case"continue":return"STATEMENT";default:return y}}()),b=this.token(y,r,0,c),e&&(b.origin=[y,e,b[2]]),b.variable=!i,u&&(g=[u[2].first_line,u[2].first_column],b[2].first_line=g[0],b[2].first_column=g[1]),t&&(n=h.lastIndexOf(":"),this.token(":",":",n,t.length)),h.length)):0},e.prototype.numberToken=function(){var e,t,n,i,r;return(n=I.exec(this.chunk))?(i=n[0],t=i.length,/^0[BOX]/.test(i)?this.error("radix prefix in '"+i+"' must be lowercase",{offset:1}):/E/.test(i)&&!/^0x/.test(i)?this.error("exponential notation in '"+i+"' must be indicated with a lowercase 'e'",{offset:i.indexOf("E")}):/^0\d*[89]/.test(i)?this.error("decimal literal '"+i+"' must not be prefixed with '0'",{length:t}):/^0\d+/.test(i)&&this.error("octal literal '"+i+"' must be prefixed with '0o'",{length:t}),(r=/^0o([0-7]+)/.exec(i))&&(i="0x"+parseInt(r[1],8).toString(16)),(e=/^0b([01]+)/.exec(i))&&(i="0x"+parseInt(e[1],2).toString(16)),this.token("NUMBER",i,0,t),t):0},e.prototype.stringToken=function(){var e,t,n,i,r,s,o,a,c,h,l,u,m,g,v,y;if(l=(Y.exec(this.chunk)||[])[0],!l)return 0;if(g=function(){switch(l){case"'":return W;case'"':return q;case"'''":return f;case'"""':return p}}(),s=3===l.length,u=this.matchWithInterpolations(g,l),y=u.tokens,r=u.index,e=y.length-1,n=l.charAt(0),s){for(a=null,i=function(){var e,t,n;for(n=[],o=e=0,t=y.length;t>e;o=++e)v=y[o],"NEOSTRING"===v[0]&&n.push(v[1]);return n}().join("#{}");h=d.exec(i);)t=h[1],(null===a||(m=t.length)>0&&a.length>m)&&(a=t);a&&(c=RegExp("^"+a,"gm")),this.mergeInterpolationTokens(y,{delimiter:n},function(t){return function(n,i){return n=t.formatString(n),0===i&&(n=n.replace(F,"")),i===e&&(n=n.replace(K,"")),c&&(n=n.replace(c,"")),n}}(this))}else this.mergeInterpolationTokens(y,{delimiter:n},function(t){return function(n,i){return n=t.formatString(n),n=n.replace(G,function(t,r){return 0===i&&0===r||i===e&&r+t.length===n.length?"":" "})}}(this));return r},e.prototype.commentToken=function(){var e,t,n;return(n=this.chunk.match(c))?(e=n[0],t=n[1],t&&((n=u.exec(e))&&this.error("block comments cannot contain "+n[0],{offset:n.index,length:n[0].length}),t.indexOf("\n")>=0&&(t=t.replace(RegExp("\\n"+ct(" ",this.indent),"g"),"\n")),this.token("HERECOMMENT",t,0,e.length)),e.length):0},e.prototype.jsToken=function(){var e,t;return"`"===this.chunk.charAt(0)&&(e=T.exec(this.chunk))?(this.token("JS",(t=e[0]).slice(1,-1),0,t.length),t.length):0},e.prototype.regexToken=function(){var e,t,n,r,s,o,a,c,h,l,u,p,d;switch(!1){case!(o=M.exec(this.chunk)):this.error("regular expressions cannot begin with "+o[2],{offset:o.index+o[1].length});break;case!(o=this.matchWithInterpolations(m,"///")):d=o.tokens,s=o.index;break;case!(o=$.exec(this.chunk)):if(p=o[0],e=o[1],t=o[2],this.validateEscapes(e,{isRegex:!0,offsetInChunk:1}),s=p.length,h=this.tokens,c=h[h.length-1],c)if(c.spaced&&(l=c[0],ut.call(i,l)>=0)){if(!t||O.test(p))return 0}else if(u=c[0],ut.call(A,u)>=0)return 0;t||this.error("missing / (unclosed regex)");break;default:return 0}switch(r=j.exec(this.chunk.slice(s))[0],n=s+r.length,a=this.makeToken("REGEX",null,0,n),!1){case!!Z.test(r):this.error("invalid regular expression flags "+r,{offset:s,length:r.length});break;case!(p||1===d.length):null==e&&(e=this.formatHeregex(d[0][1])),this.token("REGEX",""+this.makeDelimitedLiteral(e,{delimiter:"/"})+r,0,n,a);break;default:this.token("REGEX_START","(",0,0,a),this.token("IDENTIFIER","RegExp",0,0),this.token("CALL_START","(",0,0),this.mergeInterpolationTokens(d,{delimiter:'"',"double":!0},this.formatHeregex),r&&(this.token(",",",",s,0),this.token("STRING",'"'+r+'"',s,r.length)),this.token(")",")",n,0),this.token("REGEX_END",")",n,0)}return n},e.prototype.lineToken=function(){var e,t,n,i,r;if(!(n=R.exec(this.chunk)))return 0;if(t=n[0],this.seenFor=!1,r=t.length-1-t.lastIndexOf("\n"),i=this.unfinished(),r-this.indebt===this.indent)return i?this.suppressNewlines():this.newlineToken(0),t.length;if(r>this.indent){if(i)return this.indebt=r-this.indent,this.suppressNewlines(),t.length;if(!this.tokens.length)return this.baseIndent=this.indent=r,t.length;e=r-this.indent+this.outdebt,this.token("INDENT",e,t.length-r,r),this.indents.push(e),this.ends.push({tag:"OUTDENT"}),this.outdebt=this.indebt=0,this.indent=r}else this.baseIndent>r?this.error("missing indentation",{offset:t.length}):(this.indebt=0,this.outdentToken(this.indent-r,i,t.length));return t.length},e.prototype.outdentToken=function(e,t,n){var i,r,s,o;for(i=this.indent-e;e>0;)s=this.indents[this.indents.length-1],s?s===this.outdebt?(e-=this.outdebt,this.outdebt=0):this.outdebt>s?(this.outdebt-=s,e-=s):(r=this.indents.pop()+this.outdebt,n&&(o=this.chunk[n],ut.call(y,o)>=0)&&(i-=r-e,e=r),this.outdebt=0,this.pair("OUTDENT"),this.token("OUTDENT",e,0,n),e-=r):e=0;for(r&&(this.outdebt-=e);";"===this.value();)this.tokens.pop();return"TERMINATOR"===this.tag()||t||this.token("TERMINATOR","\n",n,0),this.indent=i,this},e.prototype.whitespaceToken=function(){var e,t,n,i;return(e=et.exec(this.chunk))||(t="\n"===this.chunk.charAt(0))?(i=this.tokens,n=i[i.length-1],n&&(n[e?"spaced":"newLine"]=!0),e?e[0].length:0):0},e.prototype.newlineToken=function(e){for(;";"===this.value();)this.tokens.pop();return"TERMINATOR"!==this.tag()&&this.token("TERMINATOR","\n",e,0),this},e.prototype.suppressNewlines=function(){return"\\"===this.value()&&this.tokens.pop(),this},e.prototype.literalToken=function(){var e,t,n,s,o,a,c,u,p,d;if((e=_.exec(this.chunk))?(d=e[0],r.test(d)&&this.tagParameters()):d=this.chunk.charAt(0),u=d,n=this.tokens,t=n[n.length-1],"="===d&&t&&(!t[1].reserved&&(s=t[1],ut.call(C,s)>=0)&&(t.origin&&(t=t.origin),this.error("reserved word '"+t[1]+"' can't be assigned",t[2])),"||"===(o=t[1])||"&&"===o))return t[0]="COMPOUND_ASSIGN",t[1]+="=",d.length;if(";"===d)this.seenFor=!1,u="TERMINATOR";else if(ut.call(D,d)>=0)u="MATH";else if(ut.call(h,d)>=0)u="COMPARE";else if(ut.call(l,d)>=0)u="COMPOUND_ASSIGN";else if(ut.call(J,d)>=0)u="UNARY";else if(ut.call(Q,d)>=0)u="UNARY_MATH";else if(ut.call(U,d)>=0)u="SHIFT";else if(ut.call(x,d)>=0||"?"===d&&(null!=t?t.spaced:void 0))u="LOGIC";else if(t&&!t.spaced)if("("===d&&(a=t[0],ut.call(i,a)>=0))"?"===t[0]&&(t[0]="FUNC_EXIST"),u="CALL_START";else if("["===d&&(c=t[0],ut.call(b,c)>=0))switch(u="INDEX_START",t[0]){case"?":t[0]="INDEX_SOAK"}switch(p=this.makeToken(u,d),d){case"(":case"{":case"[":this.ends.push({tag:w[d],origin:p});break;case")":case"}":case"]":this.pair(d)}return this.tokens.push(p),d.length},e.prototype.tagParameters=function(){var e,t,n,i;if(")"!==this.tag())return this;for(t=[],i=this.tokens,e=i.length,i[--e][0]="PARAM_END";n=i[--e];)switch(n[0]){case")":t.push(n);break;case"(":case"CALL_START":if(!t.length)return"("===n[0]?(n[0]="PARAM_START",this):this;t.pop()}return this},e.prototype.closeIndentation=function(){return this.outdentToken(this.indent)},e.prototype.matchWithInterpolations=function(t,n){var i,r,s,o,a,c,h,l,u,p,d,f,m,g,v;if(v=[],l=n.length,this.chunk.slice(0,l)!==n)return null;for(m=this.chunk.slice(l);;){if(g=t.exec(m)[0],this.validateEscapes(g,{isRegex:"/"===n.charAt(0),offsetInChunk:l}),v.push(this.makeToken("NEOSTRING",g,l)),m=m.slice(g.length),l+=g.length,"#{"!==m.slice(0,2))break;p=this.getLineAndColumnFromChunk(l+1),c=p[0],r=p[1],d=(new e).tokenize(m.slice(1),{line:c,column:r,untilBalanced:!0}),h=d.tokens,o=d.index,o+=1,u=h[0],i=h[h.length-1],u[0]=u[1]="(",i[0]=i[1]=")",i.origin=["","end of interpolation",i[2]],"TERMINATOR"===(null!=(f=h[1])?f[0]:void 0)&&h.splice(1,1),v.push(["TOKENS",h]),m=m.slice(o),l+=o}return m.slice(0,n.length)!==n&&this.error("missing "+n,{length:n.length}),s=v[0],a=v[v.length-1],s[2].first_column-=n.length,a[2].last_column+=n.length,0===a[1].length&&(a[2].last_column-=1),{tokens:v,index:l+n.length}},e.prototype.mergeInterpolationTokens=function(e,t,n){var i,r,s,o,a,c,h,l,u,p,d,f,m,g,v,y;for(e.length>1&&(u=this.token("STRING_START","(",0,0)),s=this.tokens.length,o=a=0,h=e.length;h>a;o=++a){switch(g=e[o],m=g[0],y=g[1],m){case"TOKENS":if(2===y.length)continue;l=y[0],v=y;break;case"NEOSTRING":if(i=n(g[1],o),0===i.length){if(0!==o)continue;r=this.tokens.length}2===o&&null!=r&&this.tokens.splice(r,2),g[0]="STRING",g[1]=this.makeDelimitedLiteral(i,t),l=g,v=[g]}this.tokens.length>s&&(p=this.token("+","+"),p[2]={first_line:l[2].first_line,first_column:l[2].first_column,last_line:l[2].first_line,last_column:l[2].first_column}),(d=this.tokens).push.apply(d,v)}return u?(c=e[e.length-1],u.origin=["STRING",null,{first_line:u[2].first_line,first_column:u[2].first_column,last_line:c[2].last_line,last_column:c[2].last_column}],f=this.token("STRING_END",")"),f[2]={first_line:c[2].last_line,first_column:c[2].last_column,last_line:c[2].last_line,last_column:c[2].last_column}):void 0},e.prototype.pair=function(e){var t,n,i,r,s;return i=this.ends,n=i[i.length-1],e!==(s=null!=n?n.tag:void 0)?("OUTDENT"!==s&&this.error("unmatched "+e),r=this.indents,t=r[r.length-1],this.outdentToken(t,!0),this.pair(e)):this.ends.pop()},e.prototype.getLineAndColumnFromChunk=function(e){var t,n,i,r,s;return 0===e?[this.chunkLine,this.chunkColumn]:(s=e>=this.chunk.length?this.chunk:this.chunk.slice(0,+(e-1)+1||9e9),i=nt(s,"\n"),t=this.chunkColumn,i>0?(r=s.split("\n"),n=r[r.length-1],t=n.length):t+=s.length,[this.chunkLine+i,t])},e.prototype.makeToken=function(e,t,n,i){var r,s,o,a,c;return null==n&&(n=0),null==i&&(i=t.length),s={},o=this.getLineAndColumnFromChunk(n),s.first_line=o[0],s.first_column=o[1],r=Math.max(0,i-1),a=this.getLineAndColumnFromChunk(n+r),s.last_line=a[0],s.last_column=a[1],c=[e,t,s]},e.prototype.token=function(e,t,n,i,r){var s;return s=this.makeToken(e,t,n,i),r&&(s.origin=r),this.tokens.push(s),s},e.prototype.tag=function(){var e,t;return e=this.tokens,t=e[e.length-1],null!=t?t[0]:void 0},e.prototype.value=function(){var e,t;return e=this.tokens,t=e[e.length-1],null!=t?t[1]:void 0},e.prototype.unfinished=function(){var e;return L.test(this.chunk)||"\\"===(e=this.tag())||"."===e||"?."===e||"?::"===e||"UNARY"===e||"MATH"===e||"UNARY_MATH"===e||"+"===e||"-"===e||"YIELD"===e||"**"===e||"SHIFT"===e||"RELATION"===e||"COMPARE"===e||"LOGIC"===e||"THROW"===e||"EXTENDS"===e},e.prototype.formatString=function(e){return e.replace(X,"$1")},e.prototype.formatHeregex=function(e){return e.replace(g,"$1$2")},e.prototype.validateEscapes=function(e,t){var n,i,r,s,o,a,c,h;return null==t&&(t={}),s=k.exec(e),!s||(s[0],n=s[1],a=s[2],i=s[3],h=s[4],t.isRegex&&a&&"0"!==a.charAt(0))?void 0:(o=a?"octal escape sequences are not allowed":"invalid escape sequence",r="\\"+(a||i||h),this.error(o+" "+r,{offset:(null!=(c=t.offsetInChunk)?c:0)+s.index+n.length,length:r.length}))},e.prototype.makeDelimitedLiteral=function(e,t){var n;return null==t&&(t={}),""===e&&"/"===t.delimiter&&(e="(?:)"),n=RegExp("(\\\\\\\\)|(\\\\0(?=[1-7]))|\\\\?("+t.delimiter+")|\\\\?(?:(\\n)|(\\r)|(\\u2028)|(\\u2029))|(\\\\.)","g"),e=e.replace(n,function(e,n,i,r,s,o,a,c,h){switch(!1){case!n:return t.double?n+n:n;case!i:return"\\x00";case!r:return"\\"+r;case!s:return"\\n";case!o:return"\\r";case!a:return"\\u2028";case!c:return"\\u2029";case!h:return t.double?"\\"+h:h}}),""+t.delimiter+e+t.delimiter},e.prototype.error=function(e,t){var n,i,r,s,o,a;return null==t&&(t={}),r="first_line"in t?t:(o=this.getLineAndColumnFromChunk(null!=(s=t.offset)?s:0),i=o[0],n=o[1],o,{first_line:i,first_column:n,last_column:n+(null!=(a=t.length)?a:1)-1}),lt(e,r)},e}(),E=["true","false","null","this","new","delete","typeof","in","instanceof","return","throw","break","continue","debugger","yield","if","else","switch","for","while","do","try","catch","finally","class","extends","super"],a=["undefined","then","unless","until","loop","of","by","when"],o={and:"&&",or:"||",is:"==",isnt:"!=",not:"!",yes:"true",no:"false",on:"true",off:"false"},s=function(){var e;e=[];for(rt in o)e.push(rt);return e}(),a=a.concat(s),V=["case","default","function","var","void","with","const","let","enum","export","import","native","implements","interface","package","private","protected","public","static"],H=["arguments","eval","yield*"],C=E.concat(V).concat(H),e.RESERVED=V.concat(E).concat(a).concat(H),e.STRICT_PROSCRIBED=H,t=65279,v=/^(?!\d)((?:(?!\s)[$\w\x7f-\uffff])+)([^\n\S]*:(?!:))?/,I=/^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i,_=/^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>*\/%])\2=?|\?(\.|::)|\.{2,3})/,et=/^[^\n\S]+/,c=/^###([^#][\s\S]*?)(?:###[^\n\S]*|###$)|^(?:\s*#(?!##[^#]).*)+/,r=/^[-=]>/,R=/^(?:\n[^\n\S]*)+/,T=/^`[^\\`]*(?:\\.[^\\`]*)*`/,Y=/^(?:'''|"""|'|")/,W=/^(?:[^\\']|\\[\s\S])*/,q=/^(?:[^\\"#]|\\[\s\S]|\#(?!\{))*/,f=/^(?:[^\\']|\\[\s\S]|'(?!''))*/,p=/^(?:[^\\"#]|\\[\s\S]|"(?!"")|\#(?!\{))*/,X=/((?:\\\\)+)|\\[^\S\n]*\n\s*/g,G=/\s*\n\s*/g,d=/\n+([^\n\S]*)(?=\S)/g,$=/^\/(?!\/)((?:[^[\/\n\\]|\\[^\n]|\[(?:\\[^\n]|[^\]\n\\])*\])*)(\/)?/,j=/^\w*/,Z=/^(?!.*(.).*\1)[imgy]*$/,m=/^(?:[^\\\/#]|\\[\s\S]|\/(?!\/\/)|\#(?!\{))*/,g=/((?:\\\\)+)|\\(\s)|\s+(?:#.*)?/g,M=/^(\/|\/{3}\s*)(\*)/,O=/^\/=?\s/,u=/\*\//,L=/^\s*(?:,|\??\.(?![.\d])|::)/,k=/((?:^|[^\\])(?:\\\\)*)\\(?:(0[0-7]|[1-7])|(x(?![\da-fA-F]{2}).{0,2})|(u(?![\da-fA-F]{4}).{0,4}))/,F=/^[^\n\S]*\n/,K=/\n[^\n\S]*$/,z=/\s+$/,l=["-=","+=","/=","*=","%=","||=","&&=","?=","<<=",">>=",">>>=","&=","^=","|=","**=","//=","%%="],J=["NEW","TYPEOF","DELETE","DO"],Q=["!","~"],x=["&&","||","&","|","^"],U=["<<",">>",">>>"],h=["==","!=","<",">","<=",">="],D=["*","/","%","//","%%"],B=["IN","OF","INSTANCEOF"],n=["TRUE","FALSE"],i=["IDENTIFIER",")","]","?","@","THIS","SUPER"],b=i.concat(["NUMBER","STRING","STRING_END","REGEX","REGEX_END","BOOL","NULL","UNDEFINED","}","::"]),A=b.concat(["++","--"]),N=["INDENT","OUTDENT","TERMINATOR"],y=[")","}","]"]}.call(this),t.exports}(),_dereq_["./parser"]=function(){var e={},t={exports:e},n=function(){function e(){this.yy={}}var t=function(e,t,n,i){for(n=n||{},i=e.length;i--;n[e[i]]=t);return n},n=[1,20],i=[1,75],r=[1,71],s=[1,76],o=[1,77],a=[1,73],c=[1,74],h=[1,50],l=[1,52],u=[1,53],p=[1,54],d=[1,55],f=[1,45],m=[1,46],g=[1,27],v=[1,60],y=[1,61],b=[1,70],k=[1,43],w=[1,26],T=[1,58],C=[1,59],E=[1,57],F=[1,38],N=[1,44],L=[1,56],x=[1,65],S=[1,66],D=[1,67],R=[1,68],A=[1,42],I=[1,64],_=[1,29],O=[1,30],$=[1,31],j=[1,32],M=[1,33],B=[1,34],V=[1,35],P=[1,78],U=[1,6,26,34,108],G=[1,88],H=[1,81],q=[1,80],X=[1,79],W=[1,82],Y=[1,83],K=[1,84],z=[1,85],J=[1,86],Q=[1,87],Z=[1,91],et=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],tt=[1,97],nt=[1,98],it=[1,99],rt=[1,100],st=[1,102],ot=[1,103],at=[1,96],ct=[2,112],ht=[1,6,25,26,34,55,60,63,72,73,74,75,77,79,80,84,90,91,92,97,99,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],lt=[2,79],ut=[1,108],pt=[2,58],dt=[1,112],ft=[1,117],mt=[1,118],gt=[1,120],vt=[1,6,25,26,34,46,55,60,63,72,73,74,75,77,79,80,84,90,91,92,97,99,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],yt=[2,76],bt=[1,6,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],kt=[1,155],wt=[1,157],Tt=[1,152],Ct=[1,6,25,26,34,46,55,60,63,72,73,74,75,77,79,80,84,86,90,91,92,97,99,108,110,111,112,116,117,132,135,136,139,140,141,142,143,144,145,146,147,148],Et=[2,95],Ft=[1,6,25,26,34,49,55,60,63,72,73,74,75,77,79,80,84,90,91,92,97,99,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],Nt=[1,6,25,26,34,46,49,55,60,63,72,73,74,75,77,79,80,84,86,90,91,92,97,99,108,110,111,112,116,117,123,124,132,135,136,139,140,141,142,143,144,145,146,147,148],Lt=[1,206],xt=[1,205],St=[1,6,25,26,34,38,55,60,63,72,73,74,75,77,79,80,84,90,91,92,97,99,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],Dt=[2,56],Rt=[1,216],At=[6,25,26,55,60],It=[6,25,26,46,55,60,63],_t=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132,135,136,142,144,145,146,147],Ot=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132],$t=[72,73,74,75,77,80,90,91],jt=[1,235],Mt=[2,133],Bt=[1,6,25,26,34,46,55,60,63,72,73,74,75,77,79,80,84,90,91,92,97,99,108,110,111,112,116,117,123,124,132,135,136,141,142,143,144,145,146,147],Vt=[1,244],Pt=[6,25,26,60,92,97],Ut=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,117,132],Gt=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,111,117,132],Ht=[123,124],qt=[60,123,124],Xt=[1,255],Wt=[6,25,26,60,84],Yt=[6,25,26,49,60,84],Kt=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132,135,136,144,145,146,147],zt=[11,28,30,32,33,36,37,40,41,42,43,44,51,52,53,57,58,79,82,85,89,94,95,96,102,106,107,110,112,114,116,125,131,133,134,135,136,137,139,140],Jt=[2,122],Qt=[6,25,26],Zt=[2,57],en=[1,268],tn=[1,269],nn=[1,6,25,26,34,55,60,63,79,84,92,97,99,104,105,108,110,111,112,116,117,127,129,132,135,136,141,142,143,144,145,146,147],rn=[26,127,129],sn=[1,6,26,34,55,60,63,79,84,92,97,99,108,111,117,132],on=[2,71],an=[1,291],cn=[1,292],hn=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,127,132,135,136,141,142,143,144,145,146,147],ln=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,112,116,117,132],un=[1,303],pn=[1,304],dn=[6,25,26,60],fn=[1,6,25,26,34,55,60,63,79,84,92,97,99,104,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],mn=[25,60],gn={trace:function(){},yy:{},symbols_:{error:2,Root:3,Body:4,Line:5,TERMINATOR:6,Expression:7,Statement:8,Return:9,Comment:10,STATEMENT:11,Value:12,Invocation:13,Code:14,Operation:15,Assign:16,If:17,Try:18,While:19,For:20,Switch:21,Class:22,Throw:23,Block:24,INDENT:25,OUTDENT:26,Identifier:27,IDENTIFIER:28,AlphaNumeric:29,NUMBER:30,String:31,STRING:32,STRING_START:33,STRING_END:34,Regex:35,REGEX:36,REGEX_START:37,REGEX_END:38,Literal:39,JS:40,DEBUGGER:41,UNDEFINED:42,NULL:43,BOOL:44,Assignable:45,"=":46,AssignObj:47,ObjAssignable:48,":":49,ThisProperty:50,RETURN:51,HERECOMMENT:52,PARAM_START:53,ParamList:54,PARAM_END:55,FuncGlyph:56,"->":57,"=>":58,OptComma:59,",":60,Param:61,ParamVar:62,"...":63,Array:64,Object:65,Splat:66,SimpleAssignable:67,Accessor:68,Parenthetical:69,Range:70,This:71,".":72,"?.":73,"::":74,"?::":75,Index:76,INDEX_START:77,IndexValue:78,INDEX_END:79,INDEX_SOAK:80,Slice:81,"{":82,AssignList:83,"}":84,CLASS:85,EXTENDS:86,OptFuncExist:87,Arguments:88,SUPER:89,FUNC_EXIST:90,CALL_START:91,CALL_END:92,ArgList:93,THIS:94,"@":95,"[":96,"]":97,RangeDots:98,"..":99,Arg:100,SimpleArgs:101,TRY:102,Catch:103,FINALLY:104,CATCH:105,THROW:106,"(":107,")":108,WhileSource:109,WHILE:110,WHEN:111,UNTIL:112,Loop:113,LOOP:114,ForBody:115,FOR:116,BY:117,ForStart:118,ForSource:119,ForVariables:120,OWN:121,ForValue:122,FORIN:123,FOROF:124,SWITCH:125,Whens:126,ELSE:127,When:128,LEADING_WHEN:129,IfBlock:130,IF:131,POST_IF:132,UNARY:133,UNARY_MATH:134,"-":135,"+":136,YIELD:137,FROM:138,"--":139,"++":140,"?":141,MATH:142,"**":143,SHIFT:144,COMPARE:145,LOGIC:146,RELATION:147,COMPOUND_ASSIGN:148,$accept:0,$end:1},terminals_:{2:"error",6:"TERMINATOR",11:"STATEMENT",25:"INDENT",26:"OUTDENT",28:"IDENTIFIER",30:"NUMBER",32:"STRING",33:"STRING_START",34:"STRING_END",36:"REGEX",37:"REGEX_START",38:"REGEX_END",40:"JS",41:"DEBUGGER",42:"UNDEFINED",43:"NULL",44:"BOOL",46:"=",49:":",51:"RETURN",52:"HERECOMMENT",53:"PARAM_START",55:"PARAM_END",57:"->",58:"=>",60:",",63:"...",72:".",73:"?.",74:"::",75:"?::",77:"INDEX_START",79:"INDEX_END",80:"INDEX_SOAK",82:"{",84:"}",85:"CLASS",86:"EXTENDS",89:"SUPER",90:"FUNC_EXIST",91:"CALL_START",92:"CALL_END",94:"THIS",95:"@",96:"[",97:"]",99:"..",102:"TRY",104:"FINALLY",105:"CATCH",106:"THROW",107:"(",108:")",110:"WHILE",111:"WHEN",112:"UNTIL",114:"LOOP",116:"FOR",117:"BY",121:"OWN",123:"FORIN",124:"FOROF",125:"SWITCH",127:"ELSE",129:"LEADING_WHEN",131:"IF",132:"POST_IF",133:"UNARY",134:"UNARY_MATH",135:"-",136:"+",137:"YIELD",138:"FROM",139:"--",140:"++",141:"?",142:"MATH",143:"**",144:"SHIFT",145:"COMPARE",146:"LOGIC",147:"RELATION",148:"COMPOUND_ASSIGN"},productions_:[0,[3,0],[3,1],[4,1],[4,3],[4,2],[5,1],[5,1],[8,1],[8,1],[8,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[24,2],[24,3],[27,1],[29,1],[29,1],[31,1],[31,3],[35,1],[35,3],[39,1],[39,1],[39,1],[39,1],[39,1],[39,1],[39,1],[16,3],[16,4],[16,5],[47,1],[47,3],[47,5],[47,1],[48,1],[48,1],[48,1],[9,2],[9,1],[10,1],[14,5],[14,2],[56,1],[56,1],[59,0],[59,1],[54,0],[54,1],[54,3],[54,4],[54,6],[61,1],[61,2],[61,3],[61,1],[62,1],[62,1],[62,1],[62,1],[66,2],[67,1],[67,2],[67,2],[67,1],[45,1],[45,1],[45,1],[12,1],[12,1],[12,1],[12,1],[12,1],[68,2],[68,2],[68,2],[68,2],[68,1],[68,1],[76,3],[76,2],[78,1],[78,1],[65,4],[83,0],[83,1],[83,3],[83,4],[83,6],[22,1],[22,2],[22,3],[22,4],[22,2],[22,3],[22,4],[22,5],[13,3],[13,3],[13,1],[13,2],[87,0],[87,1],[88,2],[88,4],[71,1],[71,1],[50,2],[64,2],[64,4],[98,1],[98,1],[70,5],[81,3],[81,2],[81,2],[81,1],[93,1],[93,3],[93,4],[93,4],[93,6],[100,1],[100,1],[100,1],[101,1],[101,3],[18,2],[18,3],[18,4],[18,5],[103,3],[103,3],[103,2],[23,2],[69,3],[69,5],[109,2],[109,4],[109,2],[109,4],[19,2],[19,2],[19,2],[19,1],[113,2],[113,2],[20,2],[20,2],[20,2],[115,2],[115,4],[115,2],[118,2],[118,3],[122,1],[122,1],[122,1],[122,1],[120,1],[120,3],[119,2],[119,2],[119,4],[119,4],[119,4],[119,6],[119,6],[21,5],[21,7],[21,4],[21,6],[126,1],[126,2],[128,3],[128,4],[130,3],[130,5],[17,1],[17,3],[17,3],[17,3],[15,2],[15,2],[15,2],[15,2],[15,2],[15,2],[15,3],[15,2],[15,2],[15,2],[15,2],[15,2],[15,3],[15,3],[15,3],[15,3],[15,3],[15,3],[15,3],[15,3],[15,3],[15,5],[15,4],[15,3]],performAction:function(e,t,n,i,r,s,o){var a=s.length-1;
-switch(r){case 1:return this.$=i.addLocationDataFn(o[a],o[a])(new i.Block);case 2:return this.$=s[a];case 3:this.$=i.addLocationDataFn(o[a],o[a])(i.Block.wrap([s[a]]));break;case 4:this.$=i.addLocationDataFn(o[a-2],o[a])(s[a-2].push(s[a]));break;case 5:this.$=s[a-1];break;case 6:case 7:case 8:case 9:case 11:case 12:case 13:case 14:case 15:case 16:case 17:case 18:case 19:case 20:case 21:case 22:case 27:case 32:case 34:case 45:case 46:case 47:case 48:case 56:case 57:case 67:case 68:case 69:case 70:case 75:case 76:case 79:case 83:case 89:case 133:case 134:case 136:case 166:case 167:case 183:case 189:this.$=s[a];break;case 10:case 25:case 26:case 28:case 30:case 33:case 35:this.$=i.addLocationDataFn(o[a],o[a])(new i.Literal(s[a]));break;case 23:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Block);break;case 24:case 31:case 90:this.$=i.addLocationDataFn(o[a-2],o[a])(s[a-1]);break;case 29:case 146:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.Parens(s[a-1]));break;case 36:this.$=i.addLocationDataFn(o[a],o[a])(new i.Undefined);break;case 37:this.$=i.addLocationDataFn(o[a],o[a])(new i.Null);break;case 38:this.$=i.addLocationDataFn(o[a],o[a])(new i.Bool(s[a]));break;case 39:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.Assign(s[a-2],s[a]));break;case 40:this.$=i.addLocationDataFn(o[a-3],o[a])(new i.Assign(s[a-3],s[a]));break;case 41:this.$=i.addLocationDataFn(o[a-4],o[a])(new i.Assign(s[a-4],s[a-1]));break;case 42:case 72:case 77:case 78:case 80:case 81:case 82:case 168:case 169:this.$=i.addLocationDataFn(o[a],o[a])(new i.Value(s[a]));break;case 43:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.Assign(i.addLocationDataFn(o[a-2])(new i.Value(s[a-2])),s[a],"object"));break;case 44:this.$=i.addLocationDataFn(o[a-4],o[a])(new i.Assign(i.addLocationDataFn(o[a-4])(new i.Value(s[a-4])),s[a-1],"object"));break;case 49:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Return(s[a]));break;case 50:this.$=i.addLocationDataFn(o[a],o[a])(new i.Return);break;case 51:this.$=i.addLocationDataFn(o[a],o[a])(new i.Comment(s[a]));break;case 52:this.$=i.addLocationDataFn(o[a-4],o[a])(new i.Code(s[a-3],s[a],s[a-1]));break;case 53:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Code([],s[a],s[a-1]));break;case 54:this.$=i.addLocationDataFn(o[a],o[a])("func");break;case 55:this.$=i.addLocationDataFn(o[a],o[a])("boundfunc");break;case 58:case 95:this.$=i.addLocationDataFn(o[a],o[a])([]);break;case 59:case 96:case 128:case 170:this.$=i.addLocationDataFn(o[a],o[a])([s[a]]);break;case 60:case 97:case 129:this.$=i.addLocationDataFn(o[a-2],o[a])(s[a-2].concat(s[a]));break;case 61:case 98:case 130:this.$=i.addLocationDataFn(o[a-3],o[a])(s[a-3].concat(s[a]));break;case 62:case 99:case 132:this.$=i.addLocationDataFn(o[a-5],o[a])(s[a-5].concat(s[a-2]));break;case 63:this.$=i.addLocationDataFn(o[a],o[a])(new i.Param(s[a]));break;case 64:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Param(s[a-1],null,!0));break;case 65:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.Param(s[a-2],s[a]));break;case 66:case 135:this.$=i.addLocationDataFn(o[a],o[a])(new i.Expansion);break;case 71:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Splat(s[a-1]));break;case 73:this.$=i.addLocationDataFn(o[a-1],o[a])(s[a-1].add(s[a]));break;case 74:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Value(s[a-1],[].concat(s[a])));break;case 84:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Access(s[a]));break;case 85:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Access(s[a],"soak"));break;case 86:this.$=i.addLocationDataFn(o[a-1],o[a])([i.addLocationDataFn(o[a-1])(new i.Access(new i.Literal("prototype"))),i.addLocationDataFn(o[a])(new i.Access(s[a]))]);break;case 87:this.$=i.addLocationDataFn(o[a-1],o[a])([i.addLocationDataFn(o[a-1])(new i.Access(new i.Literal("prototype"),"soak")),i.addLocationDataFn(o[a])(new i.Access(s[a]))]);break;case 88:this.$=i.addLocationDataFn(o[a],o[a])(new i.Access(new i.Literal("prototype")));break;case 91:this.$=i.addLocationDataFn(o[a-1],o[a])(i.extend(s[a],{soak:!0}));break;case 92:this.$=i.addLocationDataFn(o[a],o[a])(new i.Index(s[a]));break;case 93:this.$=i.addLocationDataFn(o[a],o[a])(new i.Slice(s[a]));break;case 94:this.$=i.addLocationDataFn(o[a-3],o[a])(new i.Obj(s[a-2],s[a-3].generated));break;case 100:this.$=i.addLocationDataFn(o[a],o[a])(new i.Class);break;case 101:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Class(null,null,s[a]));break;case 102:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.Class(null,s[a]));break;case 103:this.$=i.addLocationDataFn(o[a-3],o[a])(new i.Class(null,s[a-1],s[a]));break;case 104:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Class(s[a]));break;case 105:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.Class(s[a-1],null,s[a]));break;case 106:this.$=i.addLocationDataFn(o[a-3],o[a])(new i.Class(s[a-2],s[a]));break;case 107:this.$=i.addLocationDataFn(o[a-4],o[a])(new i.Class(s[a-3],s[a-1],s[a]));break;case 108:case 109:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.Call(s[a-2],s[a],s[a-1]));break;case 110:this.$=i.addLocationDataFn(o[a],o[a])(new i.Call("super",[new i.Splat(new i.Literal("arguments"))]));break;case 111:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Call("super",s[a]));break;case 112:this.$=i.addLocationDataFn(o[a],o[a])(!1);break;case 113:this.$=i.addLocationDataFn(o[a],o[a])(!0);break;case 114:this.$=i.addLocationDataFn(o[a-1],o[a])([]);break;case 115:case 131:this.$=i.addLocationDataFn(o[a-3],o[a])(s[a-2]);break;case 116:case 117:this.$=i.addLocationDataFn(o[a],o[a])(new i.Value(new i.Literal("this")));break;case 118:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Value(i.addLocationDataFn(o[a-1])(new i.Literal("this")),[i.addLocationDataFn(o[a])(new i.Access(s[a]))],"this"));break;case 119:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Arr([]));break;case 120:this.$=i.addLocationDataFn(o[a-3],o[a])(new i.Arr(s[a-2]));break;case 121:this.$=i.addLocationDataFn(o[a],o[a])("inclusive");break;case 122:this.$=i.addLocationDataFn(o[a],o[a])("exclusive");break;case 123:this.$=i.addLocationDataFn(o[a-4],o[a])(new i.Range(s[a-3],s[a-1],s[a-2]));break;case 124:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.Range(s[a-2],s[a],s[a-1]));break;case 125:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Range(s[a-1],null,s[a]));break;case 126:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Range(null,s[a],s[a-1]));break;case 127:this.$=i.addLocationDataFn(o[a],o[a])(new i.Range(null,null,s[a]));break;case 137:this.$=i.addLocationDataFn(o[a-2],o[a])([].concat(s[a-2],s[a]));break;case 138:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Try(s[a]));break;case 139:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.Try(s[a-1],s[a][0],s[a][1]));break;case 140:this.$=i.addLocationDataFn(o[a-3],o[a])(new i.Try(s[a-2],null,null,s[a]));break;case 141:this.$=i.addLocationDataFn(o[a-4],o[a])(new i.Try(s[a-3],s[a-2][0],s[a-2][1],s[a]));break;case 142:this.$=i.addLocationDataFn(o[a-2],o[a])([s[a-1],s[a]]);break;case 143:this.$=i.addLocationDataFn(o[a-2],o[a])([i.addLocationDataFn(o[a-1])(new i.Value(s[a-1])),s[a]]);break;case 144:this.$=i.addLocationDataFn(o[a-1],o[a])([null,s[a]]);break;case 145:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Throw(s[a]));break;case 147:this.$=i.addLocationDataFn(o[a-4],o[a])(new i.Parens(s[a-2]));break;case 148:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.While(s[a]));break;case 149:this.$=i.addLocationDataFn(o[a-3],o[a])(new i.While(s[a-2],{guard:s[a]}));break;case 150:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.While(s[a],{invert:!0}));break;case 151:this.$=i.addLocationDataFn(o[a-3],o[a])(new i.While(s[a-2],{invert:!0,guard:s[a]}));break;case 152:this.$=i.addLocationDataFn(o[a-1],o[a])(s[a-1].addBody(s[a]));break;case 153:case 154:this.$=i.addLocationDataFn(o[a-1],o[a])(s[a].addBody(i.addLocationDataFn(o[a-1])(i.Block.wrap([s[a-1]]))));break;case 155:this.$=i.addLocationDataFn(o[a],o[a])(s[a]);break;case 156:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.While(i.addLocationDataFn(o[a-1])(new i.Literal("true"))).addBody(s[a]));break;case 157:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.While(i.addLocationDataFn(o[a-1])(new i.Literal("true"))).addBody(i.addLocationDataFn(o[a])(i.Block.wrap([s[a]]))));break;case 158:case 159:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.For(s[a-1],s[a]));break;case 160:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.For(s[a],s[a-1]));break;case 161:this.$=i.addLocationDataFn(o[a-1],o[a])({source:i.addLocationDataFn(o[a])(new i.Value(s[a]))});break;case 162:this.$=i.addLocationDataFn(o[a-3],o[a])({source:i.addLocationDataFn(o[a-2])(new i.Value(s[a-2])),step:s[a]});break;case 163:this.$=i.addLocationDataFn(o[a-1],o[a])(function(){return s[a].own=s[a-1].own,s[a].name=s[a-1][0],s[a].index=s[a-1][1],s[a]}());break;case 164:this.$=i.addLocationDataFn(o[a-1],o[a])(s[a]);break;case 165:this.$=i.addLocationDataFn(o[a-2],o[a])(function(){return s[a].own=!0,s[a]}());break;case 171:this.$=i.addLocationDataFn(o[a-2],o[a])([s[a-2],s[a]]);break;case 172:this.$=i.addLocationDataFn(o[a-1],o[a])({source:s[a]});break;case 173:this.$=i.addLocationDataFn(o[a-1],o[a])({source:s[a],object:!0});break;case 174:this.$=i.addLocationDataFn(o[a-3],o[a])({source:s[a-2],guard:s[a]});break;case 175:this.$=i.addLocationDataFn(o[a-3],o[a])({source:s[a-2],guard:s[a],object:!0});break;case 176:this.$=i.addLocationDataFn(o[a-3],o[a])({source:s[a-2],step:s[a]});break;case 177:this.$=i.addLocationDataFn(o[a-5],o[a])({source:s[a-4],guard:s[a-2],step:s[a]});break;case 178:this.$=i.addLocationDataFn(o[a-5],o[a])({source:s[a-4],step:s[a-2],guard:s[a]});break;case 179:this.$=i.addLocationDataFn(o[a-4],o[a])(new i.Switch(s[a-3],s[a-1]));break;case 180:this.$=i.addLocationDataFn(o[a-6],o[a])(new i.Switch(s[a-5],s[a-3],s[a-1]));break;case 181:this.$=i.addLocationDataFn(o[a-3],o[a])(new i.Switch(null,s[a-1]));break;case 182:this.$=i.addLocationDataFn(o[a-5],o[a])(new i.Switch(null,s[a-3],s[a-1]));break;case 184:this.$=i.addLocationDataFn(o[a-1],o[a])(s[a-1].concat(s[a]));break;case 185:this.$=i.addLocationDataFn(o[a-2],o[a])([[s[a-1],s[a]]]);break;case 186:this.$=i.addLocationDataFn(o[a-3],o[a])([[s[a-2],s[a-1]]]);break;case 187:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.If(s[a-1],s[a],{type:s[a-2]}));break;case 188:this.$=i.addLocationDataFn(o[a-4],o[a])(s[a-4].addElse(i.addLocationDataFn(o[a-2],o[a])(new i.If(s[a-1],s[a],{type:s[a-2]}))));break;case 190:this.$=i.addLocationDataFn(o[a-2],o[a])(s[a-2].addElse(s[a]));break;case 191:case 192:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.If(s[a],i.addLocationDataFn(o[a-2])(i.Block.wrap([s[a-2]])),{type:s[a-1],statement:!0}));break;case 193:case 194:case 197:case 198:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Op(s[a-1],s[a]));break;case 195:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Op("-",s[a]));break;case 196:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Op("+",s[a]));break;case 199:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.Op(s[a-2].concat(s[a-1]),s[a]));break;case 200:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Op("--",s[a]));break;case 201:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Op("++",s[a]));break;case 202:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Op("--",s[a-1],null,!0));break;case 203:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Op("++",s[a-1],null,!0));break;case 204:this.$=i.addLocationDataFn(o[a-1],o[a])(new i.Existence(s[a-1]));break;case 205:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.Op("+",s[a-2],s[a]));break;case 206:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.Op("-",s[a-2],s[a]));break;case 207:case 208:case 209:case 210:case 211:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.Op(s[a-1],s[a-2],s[a]));break;case 212:this.$=i.addLocationDataFn(o[a-2],o[a])(function(){return"!"===s[a-1].charAt(0)?new i.Op(s[a-1].slice(1),s[a-2],s[a]).invert():new i.Op(s[a-1],s[a-2],s[a])}());break;case 213:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.Assign(s[a-2],s[a],s[a-1]));break;case 214:this.$=i.addLocationDataFn(o[a-4],o[a])(new i.Assign(s[a-4],s[a-1],s[a-3]));break;case 215:this.$=i.addLocationDataFn(o[a-3],o[a])(new i.Assign(s[a-3],s[a],s[a-2]));break;case 216:this.$=i.addLocationDataFn(o[a-2],o[a])(new i.Extends(s[a-2],s[a]))}},table:[{1:[2,1],3:1,4:2,5:3,7:4,8:5,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{1:[3]},{1:[2,2],6:P},t(U,[2,3]),t(U,[2,6],{118:69,109:89,115:90,110:x,112:S,116:R,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(U,[2,7],{118:69,109:92,115:93,110:x,112:S,116:R,132:Z}),t(et,[2,11],{87:94,68:95,76:101,72:tt,73:nt,74:it,75:rt,77:st,80:ot,90:at,91:ct}),t(et,[2,12],{76:101,87:104,68:105,72:tt,73:nt,74:it,75:rt,77:st,80:ot,90:at,91:ct}),t(et,[2,13]),t(et,[2,14]),t(et,[2,15]),t(et,[2,16]),t(et,[2,17]),t(et,[2,18]),t(et,[2,19]),t(et,[2,20]),t(et,[2,21]),t(et,[2,22]),t(et,[2,8]),t(et,[2,9]),t(et,[2,10]),t(ht,lt,{46:[1,106]}),t(ht,[2,80]),t(ht,[2,81]),t(ht,[2,82]),t(ht,[2,83]),t([1,6,25,26,34,38,55,60,63,72,73,74,75,77,79,80,84,90,92,97,99,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],[2,110],{88:107,91:ut}),t([6,25,55,60],pt,{54:109,61:110,62:111,27:113,50:114,64:115,65:116,28:i,63:dt,82:b,95:ft,96:mt}),{24:119,25:gt},{7:121,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:123,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:124,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:125,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:127,8:126,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,138:[1,128],139:B,140:V},{12:130,13:131,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:132,50:63,64:47,65:48,67:129,69:23,70:24,71:25,82:b,89:w,94:T,95:C,96:E,107:L},{12:130,13:131,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:132,50:63,64:47,65:48,67:133,69:23,70:24,71:25,82:b,89:w,94:T,95:C,96:E,107:L},t(vt,yt,{86:[1,137],139:[1,134],140:[1,135],148:[1,136]}),t(et,[2,189],{127:[1,138]}),{24:139,25:gt},{24:140,25:gt},t(et,[2,155]),{24:141,25:gt},{7:142,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:[1,143],27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(bt,[2,100],{39:22,69:23,70:24,71:25,64:47,65:48,29:49,35:51,27:62,50:63,31:72,12:130,13:131,45:132,24:144,67:146,25:gt,28:i,30:r,32:s,33:o,36:a,37:c,40:h,41:l,42:u,43:p,44:d,82:b,86:[1,145],89:w,94:T,95:C,96:E,107:L}),{7:147,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t([1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132,141,142,143,144,145,146,147],[2,50],{12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,9:18,10:19,45:21,39:22,69:23,70:24,71:25,56:28,67:36,130:37,109:39,113:40,115:41,64:47,65:48,29:49,35:51,27:62,50:63,118:69,31:72,8:122,7:148,11:n,28:i,30:r,32:s,33:o,36:a,37:c,40:h,41:l,42:u,43:p,44:d,51:f,52:m,53:g,57:v,58:y,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,114:D,125:A,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V}),t(et,[2,51]),t(vt,[2,77]),t(vt,[2,78]),t(ht,[2,32]),t(ht,[2,33]),t(ht,[2,34]),t(ht,[2,35]),t(ht,[2,36]),t(ht,[2,37]),t(ht,[2,38]),{4:149,5:3,7:4,8:5,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:[1,150],27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:151,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:kt,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,63:wt,64:47,65:48,66:156,67:36,69:23,70:24,71:25,82:b,85:k,89:w,93:153,94:T,95:C,96:E,97:Tt,100:154,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(ht,[2,116]),t(ht,[2,117],{27:158,28:i}),{25:[2,54]},{25:[2,55]},t(Ct,[2,72]),t(Ct,[2,75]),{7:159,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:160,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:161,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:163,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:162,25:gt,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{27:168,28:i,50:169,64:170,65:171,70:164,82:b,95:ft,96:E,120:165,121:[1,166],122:167},{119:172,123:[1,173],124:[1,174]},t([6,25,60,84],Et,{31:72,83:175,47:176,48:177,10:178,27:179,29:180,50:181,28:i,30:r,32:s,33:o,52:m,95:ft}),t(Ft,[2,26]),t(Ft,[2,27]),t(ht,[2,30]),{12:130,13:182,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:132,50:63,64:47,65:48,67:183,69:23,70:24,71:25,82:b,89:w,94:T,95:C,96:E,107:L},t(Nt,[2,25]),t(Ft,[2,28]),{4:184,5:3,7:4,8:5,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(U,[2,5],{7:4,8:5,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,9:18,10:19,45:21,39:22,69:23,70:24,71:25,56:28,67:36,130:37,109:39,113:40,115:41,64:47,65:48,29:49,35:51,27:62,50:63,118:69,31:72,5:185,11:n,28:i,30:r,32:s,33:o,36:a,37:c,40:h,41:l,42:u,43:p,44:d,51:f,52:m,53:g,57:v,58:y,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,110:x,112:S,114:D,116:R,125:A,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V}),t(et,[2,204]),{7:186,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:187,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:188,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:189,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:190,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:191,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:192,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:193,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:194,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(et,[2,154]),t(et,[2,159]),{7:195,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(et,[2,153]),t(et,[2,158]),{88:196,91:ut},t(Ct,[2,73]),{91:[2,113]},{27:197,28:i},{27:198,28:i},t(Ct,[2,88],{27:199,28:i}),{27:200,28:i},t(Ct,[2,89]),{7:202,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,63:Lt,64:47,65:48,67:36,69:23,70:24,71:25,78:201,81:203,82:b,85:k,89:w,94:T,95:C,96:E,98:204,99:xt,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{76:207,77:st,80:ot},{88:208,91:ut},t(Ct,[2,74]),{6:[1,210],7:209,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:[1,211],27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(St,[2,111]),{7:214,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:kt,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,63:wt,64:47,65:48,66:156,67:36,69:23,70:24,71:25,82:b,85:k,89:w,92:[1,212],93:213,94:T,95:C,96:E,100:154,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t([6,25],Dt,{59:217,55:[1,215],60:Rt}),t(At,[2,59]),t(At,[2,63],{46:[1,219],63:[1,218]}),t(At,[2,66]),t(It,[2,67]),t(It,[2,68]),t(It,[2,69]),t(It,[2,70]),{27:158,28:i},{7:214,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:kt,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,63:wt,64:47,65:48,66:156,67:36,69:23,70:24,71:25,82:b,85:k,89:w,93:153,94:T,95:C,96:E,97:Tt,100:154,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(et,[2,53]),{4:221,5:3,7:4,8:5,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,26:[1,220],27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t([1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132,135,136,142,143,144,145,146,147],[2,193],{118:69,109:89,115:90,141:X}),{109:92,110:x,112:S,115:93,116:R,118:69,132:Z},t(_t,[2,194],{118:69,109:89,115:90,141:X,143:Y}),t(_t,[2,195],{118:69,109:89,115:90,141:X,143:Y}),t(_t,[2,196],{118:69,109:89,115:90,141:X,143:Y}),t(et,[2,197],{118:69,109:92,115:93}),t(Ot,[2,198],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),{7:222,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(et,[2,200],{72:yt,73:yt,74:yt,75:yt,77:yt,80:yt,90:yt,91:yt}),{68:95,72:tt,73:nt,74:it,75:rt,76:101,77:st,80:ot,87:94,90:at,91:ct},{68:105,72:tt,73:nt,74:it,75:rt,76:101,77:st,80:ot,87:104,90:at,91:ct},t($t,lt),t(et,[2,201],{72:yt,73:yt,74:yt,75:yt,77:yt,80:yt,90:yt,91:yt}),t(et,[2,202]),t(et,[2,203]),{6:[1,225],7:223,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:[1,224],27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:226,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{24:227,25:gt,131:[1,228]},t(et,[2,138],{103:229,104:[1,230],105:[1,231]}),t(et,[2,152]),t(et,[2,160]),{25:[1,232],109:89,110:x,112:S,115:90,116:R,118:69,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q},{126:233,128:234,129:jt},t(et,[2,101]),{7:236,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(bt,[2,104],{24:237,25:gt,72:yt,73:yt,74:yt,75:yt,77:yt,80:yt,90:yt,91:yt,86:[1,238]}),t(Ot,[2,145],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(Ot,[2,49],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),{6:P,108:[1,239]},{4:240,5:3,7:4,8:5,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t([6,25,60,97],Mt,{118:69,109:89,115:90,98:241,63:[1,242],99:xt,110:x,112:S,116:R,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(Bt,[2,119]),t([6,25,97],Dt,{59:243,60:Vt}),t(Pt,[2,128]),{7:214,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:kt,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,63:wt,64:47,65:48,66:156,67:36,69:23,70:24,71:25,82:b,85:k,89:w,93:245,94:T,95:C,96:E,100:154,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(Pt,[2,134]),t(Pt,[2,135]),t(Nt,[2,118]),{24:246,25:gt,109:89,110:x,112:S,115:90,116:R,118:69,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q},t(Ut,[2,148],{118:69,109:89,115:90,110:x,111:[1,247],112:S,116:R,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(Ut,[2,150],{118:69,109:89,115:90,110:x,111:[1,248],112:S,116:R,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(et,[2,156]),t(Gt,[2,157],{118:69,109:89,115:90,110:x,112:S,116:R,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t([1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,132,135,136,141,142,143,144,145,146,147],[2,161],{117:[1,249]}),t(Ht,[2,164]),{27:168,28:i,50:169,64:170,65:171,82:b,95:ft,96:mt,120:250,122:167},t(Ht,[2,170],{60:[1,251]}),t(qt,[2,166]),t(qt,[2,167]),t(qt,[2,168]),t(qt,[2,169]),t(et,[2,163]),{7:252,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:253,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t([6,25,84],Dt,{59:254,60:Xt}),t(Wt,[2,96]),t(Wt,[2,42],{49:[1,256]}),t(Wt,[2,45]),t(Yt,[2,46]),t(Yt,[2,47]),t(Yt,[2,48]),{38:[1,257],68:105,72:tt,73:nt,74:it,75:rt,76:101,77:st,80:ot,87:104,90:at,91:ct},t($t,yt),{6:P,34:[1,258]},t(U,[2,4]),t(Kt,[2,205],{118:69,109:89,115:90,141:X,142:W,143:Y}),t(Kt,[2,206],{118:69,109:89,115:90,141:X,142:W,143:Y}),t(_t,[2,207],{118:69,109:89,115:90,141:X,143:Y}),t(_t,[2,208],{118:69,109:89,115:90,141:X,143:Y}),t([1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132,144,145,146,147],[2,209],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y}),t([1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132,145,146],[2,210],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y,144:K,147:Q}),t([1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132,146],[2,211],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,147:Q}),t([1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132,145,146,147],[2,212],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y,144:K}),t(Gt,[2,192],{118:69,109:89,115:90,110:x,112:S,116:R,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(Gt,[2,191],{118:69,109:89,115:90,110:x,112:S,116:R,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(St,[2,108]),t(Ct,[2,84]),t(Ct,[2,85]),t(Ct,[2,86]),t(Ct,[2,87]),{79:[1,259]},{63:Lt,79:[2,92],98:260,99:xt,109:89,110:x,112:S,115:90,116:R,118:69,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q},{79:[2,93]},{7:261,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,79:[2,127],82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(zt,[2,121]),t(zt,Jt),t(Ct,[2,91]),t(St,[2,109]),t(Ot,[2,39],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),{7:262,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:263,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(St,[2,114]),t([6,25,92],Dt,{59:264,60:Vt}),t(Pt,Mt,{118:69,109:89,115:90,63:[1,265],110:x,112:S,116:R,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),{56:266,57:v,58:y},t(Qt,Zt,{62:111,27:113,50:114,64:115,65:116,61:267,28:i,63:dt,82:b,95:ft,96:mt}),{6:en,25:tn},t(At,[2,64]),{7:270,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(nn,[2,23]),{6:P,26:[1,271]},t(Ot,[2,199],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(Ot,[2,213],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),{7:272,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:273,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(Ot,[2,216],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(et,[2,190]),{7:274,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(et,[2,139],{104:[1,275]}),{24:276,25:gt},{24:279,25:gt,27:277,28:i,65:278,82:b},{126:280,128:234,129:jt},{26:[1,281],127:[1,282],128:283,129:jt},t(rn,[2,183]),{7:285,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,101:284,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(sn,[2,102],{118:69,109:89,115:90,24:286,25:gt,110:x,112:S,116:R,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(et,[2,105]),{7:287,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(ht,[2,146]),{6:P,26:[1,288]},{7:289,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t([11,28,30,32,33,36,37,40,41,42,43,44,51,52,53,57,58,82,85,89,94,95,96,102,106,107,110,112,114,116,125,131,133,134,135,136,137,139,140],Jt,{6:on,25:on,60:on,97:on}),{6:an,25:cn,97:[1,290]},t([6,25,26,92,97],Zt,{12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,9:18,10:19,45:21,39:22,69:23,70:24,71:25,56:28,67:36,130:37,109:39,113:40,115:41,64:47,65:48,29:49,35:51,27:62,50:63,118:69,31:72,8:122,66:156,7:214,100:293,11:n,28:i,30:r,32:s,33:o,36:a,37:c,40:h,41:l,42:u,43:p,44:d,51:f,52:m,53:g,57:v,58:y,63:wt,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,110:x,112:S,114:D,116:R,125:A,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V}),t(Qt,Dt,{59:294,60:Vt}),t(hn,[2,187]),{7:295,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:296,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:297,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(Ht,[2,165]),{27:168,28:i,50:169,64:170,65:171,82:b,95:ft,96:mt,122:298},t([1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,112,116,132],[2,172],{118:69,109:89,115:90,111:[1,299],117:[1,300],135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(ln,[2,173],{118:69,109:89,115:90,111:[1,301],135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),{6:un,25:pn,84:[1,302]},t([6,25,26,84],Zt,{31:72,48:177,10:178,27:179,29:180,50:181,47:305,28:i,30:r,32:s,33:o,52:m,95:ft}),{7:306,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:[1,307],27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(ht,[2,31]),t(Ft,[2,29]),t(Ct,[2,90]),{7:308,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,79:[2,125],82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{79:[2,126],109:89,110:x,112:S,115:90,116:R,118:69,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q},t(Ot,[2,40],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),{26:[1,309],109:89,110:x,112:S,115:90,116:R,118:69,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q},{6:an,25:cn,92:[1,310]},t(Pt,on),{24:311,25:gt},t(At,[2,60]),{27:113,28:i,50:114,61:312,62:111,63:dt,64:115,65:116,82:b,95:ft,96:mt},t(dn,pt,{61:110,62:111,27:113,50:114,64:115,65:116,54:313,28:i,63:dt,82:b,95:ft,96:mt}),t(At,[2,65],{118:69,109:89,115:90,110:x,112:S,116:R,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(nn,[2,24]),{26:[1,314],109:89,110:x,112:S,115:90,116:R,118:69,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q},t(Ot,[2,215],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),{24:315,25:gt,109:89,110:x,112:S,115:90,116:R,118:69,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q},{24:316,25:gt},t(et,[2,140]),{24:317,25:gt},{24:318,25:gt},t(fn,[2,144]),{26:[1,319],127:[1,320],128:283,129:jt},t(et,[2,181]),{24:321,25:gt},t(rn,[2,184]),{24:322,25:gt,60:[1,323]},t(mn,[2,136],{118:69,109:89,115:90,110:x,112:S,116:R,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(et,[2,103]),t(sn,[2,106],{118:69,109:89,115:90,24:324,25:gt,110:x,112:S,116:R,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),{108:[1,325]},{97:[1,326],109:89,110:x,112:S,115:90,116:R,118:69,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q},t(Bt,[2,120]),{7:214,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,63:wt,64:47,65:48,66:156,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,100:327,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:214,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:kt,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,63:wt,64:47,65:48,66:156,67:36,69:23,70:24,71:25,82:b,85:k,89:w,93:328,94:T,95:C,96:E,100:154,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(Pt,[2,129]),{6:an,25:cn,26:[1,329]},t(Gt,[2,149],{118:69,109:89,115:90,110:x,112:S,116:R,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(Gt,[2,151],{118:69,109:89,115:90,110:x,112:S,116:R,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(Gt,[2,162],{118:69,109:89,115:90,110:x,112:S,116:R,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(Ht,[2,171]),{7:330,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:331,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:332,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(Bt,[2,94]),{10:178,27:179,28:i,29:180,30:r,31:72,32:s,33:o,47:333,48:177,50:181,52:m,95:ft},t(dn,Et,{31:72,47:176,48:177,10:178,27:179,29:180,50:181,83:334,28:i,30:r,32:s,33:o,52:m,95:ft}),t(Wt,[2,97]),t(Wt,[2,43],{118:69,109:89,115:90,110:x,112:S,116:R,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),{7:335,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{79:[2,124],109:89,110:x,112:S,115:90,116:R,118:69,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q},t(et,[2,41]),t(St,[2,115]),t(et,[2,52]),t(At,[2,61]),t(Qt,Dt,{59:336,60:Rt}),t(et,[2,214]),t(hn,[2,188]),t(et,[2,141]),t(fn,[2,142]),t(fn,[2,143]),t(et,[2,179]),{24:337,25:gt},{26:[1,338]},t(rn,[2,185],{6:[1,339]}),{7:340,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},t(et,[2,107]),t(ht,[2,147]),t(ht,[2,123]),t(Pt,[2,130]),t(Qt,Dt,{59:341,60:Vt}),t(Pt,[2,131]),t([1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,132],[2,174],{118:69,109:89,115:90,117:[1,342],135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(ln,[2,176],{118:69,109:89,115:90,111:[1,343],135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(Ot,[2,175],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(Wt,[2,98]),t(Qt,Dt,{59:344,60:Xt}),{26:[1,345],109:89,110:x,112:S,115:90,116:R,118:69,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q},{6:en,25:tn,26:[1,346]},{26:[1,347]},t(et,[2,182]),t(rn,[2,186]),t(mn,[2,137],{118:69,109:89,115:90,110:x,112:S,116:R,132:G,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),{6:an,25:cn,26:[1,348]},{7:349,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{7:350,8:122,9:18,10:19,11:n,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:i,29:49,30:r,31:72,32:s,33:o,35:51,36:a,37:c,39:22,40:h,41:l,42:u,43:p,44:d,45:21,50:63,51:f,52:m,53:g,56:28,57:v,58:y,64:47,65:48,67:36,69:23,70:24,71:25,82:b,85:k,89:w,94:T,95:C,96:E,102:F,106:N,107:L,109:39,110:x,112:S,113:40,114:D,115:41,116:R,118:69,125:A,130:37,131:I,133:_,134:O,135:$,136:j,137:M,139:B,140:V},{6:un,25:pn,26:[1,351]},t(Wt,[2,44]),t(At,[2,62]),t(et,[2,180]),t(Pt,[2,132]),t(Ot,[2,177],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(Ot,[2,178],{118:69,109:89,115:90,135:H,136:q,141:X,142:W,143:Y,144:K,145:z,146:J,147:Q}),t(Wt,[2,99])],defaultActions:{60:[2,54],61:[2,55],96:[2,113],203:[2,93]},parseError:function(e,t){if(!t.recoverable)throw Error(e);
-this.trace(e)},parse:function(e){function t(){var e;return e=f.lex()||p,"number"!=typeof e&&(e=n.symbols_[e]||e),e}var n=this,i=[0],r=[null],s=[],o=this.table,a="",c=0,h=0,l=0,u=2,p=1,d=s.slice.call(arguments,1),f=Object.create(this.lexer),m={yy:{}};for(var g in this.yy)Object.prototype.hasOwnProperty.call(this.yy,g)&&(m.yy[g]=this.yy[g]);f.setInput(e,m.yy),m.yy.lexer=f,m.yy.parser=this,f.yylloc===void 0&&(f.yylloc={});var v=f.yylloc;s.push(v);var y=f.options&&f.options.ranges;this.parseError="function"==typeof m.yy.parseError?m.yy.parseError:Object.getPrototypeOf(this).parseError;for(var b,k,w,T,C,E,F,N,L,x={};;){if(w=i[i.length-1],this.defaultActions[w]?T=this.defaultActions[w]:((null===b||b===void 0)&&(b=t()),T=o[w]&&o[w][b]),T===void 0||!T.length||!T[0]){var S="";L=[];for(E in o[w])this.terminals_[E]&&E>u&&L.push("'"+this.terminals_[E]+"'");S=f.showPosition?"Parse error on line "+(c+1)+":\n"+f.showPosition()+"\nExpecting "+L.join(", ")+", got '"+(this.terminals_[b]||b)+"'":"Parse error on line "+(c+1)+": Unexpected "+(b==p?"end of input":"'"+(this.terminals_[b]||b)+"'"),this.parseError(S,{text:f.match,token:this.terminals_[b]||b,line:f.yylineno,loc:v,expected:L})}if(T[0]instanceof Array&&T.length>1)throw Error("Parse Error: multiple actions possible at state: "+w+", token: "+b);switch(T[0]){case 1:i.push(b),r.push(f.yytext),s.push(f.yylloc),i.push(T[1]),b=null,k?(b=k,k=null):(h=f.yyleng,a=f.yytext,c=f.yylineno,v=f.yylloc,l>0&&l--);break;case 2:if(F=this.productions_[T[1]][1],x.$=r[r.length-F],x._$={first_line:s[s.length-(F||1)].first_line,last_line:s[s.length-1].last_line,first_column:s[s.length-(F||1)].first_column,last_column:s[s.length-1].last_column},y&&(x._$.range=[s[s.length-(F||1)].range[0],s[s.length-1].range[1]]),C=this.performAction.apply(x,[a,h,c,m.yy,T[1],r,s].concat(d)),C!==void 0)return C;F&&(i=i.slice(0,2*-1*F),r=r.slice(0,-1*F),s=s.slice(0,-1*F)),i.push(this.productions_[T[1]][0]),r.push(x.$),s.push(x._$),N=o[i[i.length-2]][i[i.length-1]],i.push(N);break;case 3:return!0}}return!0}};return e.prototype=gn,gn.Parser=e,new e}();return _dereq_!==void 0&&e!==void 0&&(e.parser=n,e.Parser=n.Parser,e.parse=function(){return n.parse.apply(n,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var n=_dereq_("fs").readFileSync(_dereq_("path").normalize(t[1]),"utf8");return e.parser.parse(n)},t!==void 0&&_dereq_.main===t&&e.main(process.argv.slice(1))),t.exports}(),_dereq_["./scope"]=function(){var e={},t={exports:e};return function(){var t,n=[].indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(t in this&&this[t]===e)return t;return-1};e.Scope=t=function(){function e(e,t,n,i){var r,s;this.parent=e,this.expressions=t,this.method=n,this.referencedVars=i,this.variables=[{name:"arguments",type:"arguments"}],this.positions={},this.parent||(this.utilities={}),this.root=null!=(r=null!=(s=this.parent)?s.root:void 0)?r:this}return e.prototype.add=function(e,t,n){return this.shared&&!n?this.parent.add(e,t,n):Object.prototype.hasOwnProperty.call(this.positions,e)?this.variables[this.positions[e]].type=t:this.positions[e]=this.variables.push({name:e,type:t})-1},e.prototype.namedMethod=function(){var e;return(null!=(e=this.method)?e.name:void 0)||!this.parent?this.method:this.parent.namedMethod()},e.prototype.find=function(e){return this.check(e)?!0:(this.add(e,"var"),!1)},e.prototype.parameter=function(e){return this.shared&&this.parent.check(e,!0)?void 0:this.add(e,"param")},e.prototype.check=function(e){var t;return!!(this.type(e)||(null!=(t=this.parent)?t.check(e):void 0))},e.prototype.temporary=function(e,t,n){return null==n&&(n=!1),n?(t+parseInt(e,36)).toString(36).replace(/\d/g,"a"):e+(t||"")},e.prototype.type=function(e){var t,n,i,r;for(i=this.variables,t=0,n=i.length;n>t;t++)if(r=i[t],r.name===e)return r.type;return null},e.prototype.freeVariable=function(e,t){var i,r,s;for(null==t&&(t={}),i=0;;){if(s=this.temporary(e,i,t.single),!(this.check(s)||n.call(this.root.referencedVars,s)>=0))break;i++}return(null!=(r=t.reserve)?r:!0)&&this.add(s,"var",!0),s},e.prototype.assign=function(e,t){return this.add(e,{value:t,assigned:!0},!0),this.hasAssignments=!0},e.prototype.hasDeclarations=function(){return!!this.declaredVariables().length},e.prototype.declaredVariables=function(){var e;return function(){var t,n,i,r;for(i=this.variables,r=[],t=0,n=i.length;n>t;t++)e=i[t],"var"===e.type&&r.push(e.name);return r}.call(this).sort()},e.prototype.assignedVariables=function(){var e,t,n,i,r;for(n=this.variables,i=[],e=0,t=n.length;t>e;e++)r=n[e],r.type.assigned&&i.push(r.name+" = "+r.type.value);return i},e}()}.call(this),t.exports}(),_dereq_["./nodes"]=function(){var e={},t={exports:e};return function(){var t,n,i,r,s,o,a,c,h,l,u,p,d,f,m,g,v,y,b,k,w,T,C,E,F,N,L,x,S,D,R,A,I,_,O,$,j,M,B,V,P,U,G,H,q,X,W,Y,K,z,J,Q,Z,et,tt,nt,it,rt,st,ot,at,ct,ht,lt,ut,pt,dt,ft,mt,gt,vt,yt,bt,kt=function(e,t){function n(){this.constructor=e}for(var i in t)wt.call(t,i)&&(e[i]=t[i]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},wt={}.hasOwnProperty,Tt=[].indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(t in this&&this[t]===e)return t;return-1},Ct=[].slice;Error.stackTraceLimit=1/0,P=_dereq_("./scope").Scope,dt=_dereq_("./lexer"),$=dt.RESERVED,V=dt.STRICT_PROSCRIBED,ft=_dereq_("./helpers"),et=ft.compact,rt=ft.flatten,it=ft.extend,lt=ft.merge,tt=ft.del,gt=ft.starts,nt=ft.ends,mt=ft.some,Z=ft.addLocationDataFn,ht=ft.locationDataToString,vt=ft.throwSyntaxError,e.extend=it,e.addLocationDataFn=Z,Q=function(){return!0},D=function(){return!1},X=function(){return this},S=function(){return this.negated=!this.negated,this},e.CodeFragment=h=function(){function e(e,t){var n;this.code=""+t,this.locationData=null!=e?e.locationData:void 0,this.type=(null!=e?null!=(n=e.constructor)?n.name:void 0:void 0)||"unknown"}return e.prototype.toString=function(){return""+this.code+(this.locationData?": "+ht(this.locationData):"")},e}(),st=function(e){var t;return function(){var n,i,r;for(r=[],n=0,i=e.length;i>n;n++)t=e[n],r.push(t.code);return r}().join("")},e.Base=r=function(){function e(){}return e.prototype.compile=function(e,t){return st(this.compileToFragments(e,t))},e.prototype.compileToFragments=function(e,t){var n;return e=it({},e),t&&(e.level=t),n=this.unfoldSoak(e)||this,n.tab=e.indent,e.level!==L&&n.isStatement(e)?n.compileClosure(e):n.compileNode(e)},e.prototype.compileClosure=function(e){var n,i,r,a,h,l,u;return(a=this.jumps())&&a.error("cannot use a pure statement in an expression"),e.sharedScope=!0,r=new c([],s.wrap([this])),n=[],((i=this.contains(at))||this.contains(ct))&&(n=[new x("this")],i?(h="apply",n.push(new x("arguments"))):h="call",r=new z(r,[new t(new x(h))])),l=new o(r,n).compileNode(e),(r.isGenerator||(null!=(u=r.base)?u.isGenerator:void 0))&&(l.unshift(this.makeCode("(yield* ")),l.push(this.makeCode(")"))),l},e.prototype.cache=function(e,t,n){var r,s,o;return r=null!=n?n(this):this.isComplex(),r?(s=new x(e.scope.freeVariable("ref")),o=new i(s,this),t?[o.compileToFragments(e,t),[this.makeCode(s.value)]]:[o,s]):(s=t?this.compileToFragments(e,t):this,[s,s])},e.prototype.cacheToCodeFragments=function(e){return[st(e[0]),st(e[1])]},e.prototype.makeReturn=function(e){var t;return t=this.unwrapAll(),e?new o(new x(e+".push"),[t]):new M(t)},e.prototype.contains=function(e){var t;return t=void 0,this.traverseChildren(!1,function(n){return e(n)?(t=n,!1):void 0}),t},e.prototype.lastNonComment=function(e){var t;for(t=e.length;t--;)if(!(e[t]instanceof l))return e[t];return null},e.prototype.toString=function(e,t){var n;return null==e&&(e=""),null==t&&(t=this.constructor.name),n="\n"+e+t,this.soak&&(n+="?"),this.eachChild(function(t){return n+=t.toString(e+q)}),n},e.prototype.eachChild=function(e){var t,n,i,r,s,o,a,c;if(!this.children)return this;for(a=this.children,i=0,s=a.length;s>i;i++)if(t=a[i],this[t])for(c=rt([this[t]]),r=0,o=c.length;o>r;r++)if(n=c[r],e(n)===!1)return this;return this},e.prototype.traverseChildren=function(e,t){return this.eachChild(function(n){var i;return i=t(n),i!==!1?n.traverseChildren(e,t):void 0})},e.prototype.invert=function(){return new I("!",this)},e.prototype.unwrapAll=function(){var e;for(e=this;e!==(e=e.unwrap()););return e},e.prototype.children=[],e.prototype.isStatement=D,e.prototype.jumps=D,e.prototype.isComplex=Q,e.prototype.isChainable=D,e.prototype.isAssignable=D,e.prototype.unwrap=X,e.prototype.unfoldSoak=D,e.prototype.assigns=D,e.prototype.updateLocationDataIfMissing=function(e){return this.locationData?this:(this.locationData=e,this.eachChild(function(t){return t.updateLocationDataIfMissing(e)}))},e.prototype.error=function(e){return vt(e,this.locationData)},e.prototype.makeCode=function(e){return new h(this,e)},e.prototype.wrapInBraces=function(e){return[].concat(this.makeCode("("),e,this.makeCode(")"))},e.prototype.joinFragmentArrays=function(e,t){var n,i,r,s,o;for(n=[],r=s=0,o=e.length;o>s;r=++s)i=e[r],r&&n.push(this.makeCode(t)),n=n.concat(i);return n},e}(),e.Block=s=function(e){function t(e){this.expressions=et(rt(e||[]))}return kt(t,e),t.prototype.children=["expressions"],t.prototype.push=function(e){return this.expressions.push(e),this},t.prototype.pop=function(){return this.expressions.pop()},t.prototype.unshift=function(e){return this.expressions.unshift(e),this},t.prototype.unwrap=function(){return 1===this.expressions.length?this.expressions[0]:this},t.prototype.isEmpty=function(){return!this.expressions.length},t.prototype.isStatement=function(e){var t,n,i,r;for(r=this.expressions,n=0,i=r.length;i>n;n++)if(t=r[n],t.isStatement(e))return!0;return!1},t.prototype.jumps=function(e){var t,n,i,r,s;for(s=this.expressions,n=0,r=s.length;r>n;n++)if(t=s[n],i=t.jumps(e))return i},t.prototype.makeReturn=function(e){var t,n;for(n=this.expressions.length;n--;)if(t=this.expressions[n],!(t instanceof l)){this.expressions[n]=t.makeReturn(e),t instanceof M&&!t.expression&&this.expressions.splice(n,1);break}return this},t.prototype.compileToFragments=function(e,n){return null==e&&(e={}),e.scope?t.__super__.compileToFragments.call(this,e,n):this.compileRoot(e)},t.prototype.compileNode=function(e){var n,i,r,s,o,a,c,h,l;for(this.tab=e.indent,l=e.level===L,i=[],h=this.expressions,s=o=0,a=h.length;a>o;s=++o)c=h[s],c=c.unwrapAll(),c=c.unfoldSoak(e)||c,c instanceof t?i.push(c.compileNode(e)):l?(c.front=!0,r=c.compileToFragments(e),c.isStatement(e)||(r.unshift(this.makeCode(""+this.tab)),r.push(this.makeCode(";"))),i.push(r)):i.push(c.compileToFragments(e,E));return l?this.spaced?[].concat(this.joinFragmentArrays(i,"\n\n"),this.makeCode("\n")):this.joinFragmentArrays(i,"\n"):(n=i.length?this.joinFragmentArrays(i,", "):[this.makeCode("void 0")],i.length>1&&e.level>=E?this.wrapInBraces(n):n)},t.prototype.compileRoot=function(e){var t,n,i,r,s,o,a,c,h,u,p;for(e.indent=e.bare?"":q,e.level=L,this.spaced=!0,e.scope=new P(null,this,null,null!=(h=e.referencedVars)?h:[]),u=e.locals||[],r=0,s=u.length;s>r;r++)o=u[r],e.scope.parameter(o);return a=[],e.bare||(c=function(){var e,n,r,s;for(r=this.expressions,s=[],i=e=0,n=r.length;n>e&&(t=r[i],t.unwrap()instanceof l);i=++e)s.push(t);return s}.call(this),p=this.expressions.slice(c.length),this.expressions=c,c.length&&(a=this.compileNode(lt(e,{indent:""})),a.push(this.makeCode("\n"))),this.expressions=p),n=this.compileWithDeclarations(e),e.bare?n:[].concat(a,this.makeCode("(function() {\n"),n,this.makeCode("\n}).call(this);\n"))},t.prototype.compileWithDeclarations=function(e){var t,n,i,r,s,o,a,c,h,u,p,d,f,m;for(r=[],c=[],h=this.expressions,s=o=0,a=h.length;a>o&&(i=h[s],i=i.unwrap(),i instanceof l||i instanceof x);s=++o);return e=lt(e,{level:L}),s&&(d=this.expressions.splice(s,9e9),u=[this.spaced,!1],m=u[0],this.spaced=u[1],p=[this.compileNode(e),m],r=p[0],this.spaced=p[1],this.expressions=d),c=this.compileNode(e),f=e.scope,f.expressions===this&&(n=e.scope.hasDeclarations(),t=f.hasAssignments,n||t?(s&&r.push(this.makeCode("\n")),r.push(this.makeCode(this.tab+"var ")),n&&r.push(this.makeCode(f.declaredVariables().join(", "))),t&&(n&&r.push(this.makeCode(",\n"+(this.tab+q))),r.push(this.makeCode(f.assignedVariables().join(",\n"+(this.tab+q))))),r.push(this.makeCode(";\n"+(this.spaced?"\n":"")))):r.length&&c.length&&r.push(this.makeCode("\n"))),r.concat(c)},t.wrap=function(e){return 1===e.length&&e[0]instanceof t?e[0]:new t(e)},t}(r),e.Literal=x=function(e){function t(e){this.value=e}return kt(t,e),t.prototype.makeReturn=function(){return this.isStatement()?this:t.__super__.makeReturn.apply(this,arguments)},t.prototype.isAssignable=function(){return g.test(this.value)},t.prototype.isStatement=function(){var e;return"break"===(e=this.value)||"continue"===e||"debugger"===e},t.prototype.isComplex=D,t.prototype.assigns=function(e){return e===this.value},t.prototype.jumps=function(e){return"break"!==this.value||(null!=e?e.loop:void 0)||(null!=e?e.block:void 0)?"continue"!==this.value||(null!=e?e.loop:void 0)?void 0:this:this},t.prototype.compileNode=function(e){var t,n,i;return n="this"===this.value?(null!=(i=e.scope.method)?i.bound:void 0)?e.scope.method.context:this.value:this.value.reserved?'"'+this.value+'"':this.value,t=this.isStatement()?""+this.tab+n+";":n,[this.makeCode(t)]},t.prototype.toString=function(){return' "'+this.value+'"'},t}(r),e.Undefined=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return kt(t,e),t.prototype.isAssignable=D,t.prototype.isComplex=D,t.prototype.compileNode=function(e){return[this.makeCode(e.level>=T?"(void 0)":"void 0")]},t}(r),e.Null=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return kt(t,e),t.prototype.isAssignable=D,t.prototype.isComplex=D,t.prototype.compileNode=function(){return[this.makeCode("null")]},t}(r),e.Bool=function(e){function t(e){this.val=e}return kt(t,e),t.prototype.isAssignable=D,t.prototype.isComplex=D,t.prototype.compileNode=function(){return[this.makeCode(this.val)]},t}(r),e.Return=M=function(e){function t(e){this.expression=e}return kt(t,e),t.prototype.children=["expression"],t.prototype.isStatement=Q,t.prototype.makeReturn=X,t.prototype.jumps=X,t.prototype.compileToFragments=function(e,n){var i,r;return i=null!=(r=this.expression)?r.makeReturn():void 0,!i||i instanceof t?t.__super__.compileToFragments.call(this,e,n):i.compileToFragments(e,n)},t.prototype.compileNode=function(e){var t,n,i;return t=[],n=null!=(i=this.expression)?"function"==typeof i.isYieldReturn?i.isYieldReturn():void 0:void 0,n||t.push(this.makeCode(this.tab+("return"+(this.expression?" ":"")))),this.expression&&(t=t.concat(this.expression.compileToFragments(e,N))),n||t.push(this.makeCode(";")),t},t}(r),e.Value=z=function(e){function t(e,n,i){return!n&&e instanceof t?e:(this.base=e,this.properties=n||[],i&&(this[i]=!0),this)}return kt(t,e),t.prototype.children=["base","properties"],t.prototype.add=function(e){return this.properties=this.properties.concat(e),this},t.prototype.hasProperties=function(){return!!this.properties.length},t.prototype.bareLiteral=function(e){return!this.properties.length&&this.base instanceof e},t.prototype.isArray=function(){return this.bareLiteral(n)},t.prototype.isRange=function(){return this.bareLiteral(j)},t.prototype.isComplex=function(){return this.hasProperties()||this.base.isComplex()},t.prototype.isAssignable=function(){return this.hasProperties()||this.base.isAssignable()},t.prototype.isSimpleNumber=function(){return this.bareLiteral(x)&&B.test(this.base.value)},t.prototype.isString=function(){return this.bareLiteral(x)&&y.test(this.base.value)},t.prototype.isRegex=function(){return this.bareLiteral(x)&&v.test(this.base.value)},t.prototype.isAtomic=function(){var e,t,n,i;for(i=this.properties.concat(this.base),e=0,t=i.length;t>e;e++)if(n=i[e],n.soak||n instanceof o)return!1;return!0},t.prototype.isNotCallable=function(){return this.isSimpleNumber()||this.isString()||this.isRegex()||this.isArray()||this.isRange()||this.isSplice()||this.isObject()},t.prototype.isStatement=function(e){return!this.properties.length&&this.base.isStatement(e)},t.prototype.assigns=function(e){return!this.properties.length&&this.base.assigns(e)},t.prototype.jumps=function(e){return!this.properties.length&&this.base.jumps(e)},t.prototype.isObject=function(e){return this.properties.length?!1:this.base instanceof A&&(!e||this.base.generated)},t.prototype.isSplice=function(){var e,t;return t=this.properties,e=t[t.length-1],e instanceof U},t.prototype.looksStatic=function(e){var t;return this.base.value===e&&1===this.properties.length&&"prototype"!==(null!=(t=this.properties[0].name)?t.value:void 0)},t.prototype.unwrap=function(){return this.properties.length?this:this.base},t.prototype.cacheReference=function(e){var n,r,s,o,a;return a=this.properties,s=a[a.length-1],2>this.properties.length&&!this.base.isComplex()&&!(null!=s?s.isComplex():void 0)?[this,this]:(n=new t(this.base,this.properties.slice(0,-1)),n.isComplex()&&(r=new x(e.scope.freeVariable("base")),n=new t(new O(new i(r,n)))),s?(s.isComplex()&&(o=new x(e.scope.freeVariable("name")),s=new w(new i(o,s.index)),o=new w(o)),[n.add(s),new t(r||n.base,[o||s])]):[n,r])},t.prototype.compileNode=function(e){var t,n,i,r,s;for(this.base.front=this.front,s=this.properties,t=this.base.compileToFragments(e,s.length?T:null),(this.base instanceof O||s.length)&&B.test(st(t))&&t.push(this.makeCode(".")),n=0,i=s.length;i>n;n++)r=s[n],t.push.apply(t,r.compileToFragments(e));return t},t.prototype.unfoldSoak=function(e){return null!=this.unfoldedSoak?this.unfoldedSoak:this.unfoldedSoak=function(n){return function(){var r,s,o,a,c,h,l,p,d,f;if(o=n.base.unfoldSoak(e))return(p=o.body.properties).push.apply(p,n.properties),o;for(d=n.properties,s=a=0,c=d.length;c>a;s=++a)if(h=d[s],h.soak)return h.soak=!1,r=new t(n.base,n.properties.slice(0,s)),f=new t(n.base,n.properties.slice(s)),r.isComplex()&&(l=new x(e.scope.freeVariable("ref")),r=new O(new i(l,r)),f.base=l),new b(new u(r),f,{soak:!0});return!1}}(this)()},t}(r),e.Comment=l=function(e){function t(e){this.comment=e}return kt(t,e),t.prototype.isStatement=Q,t.prototype.makeReturn=X,t.prototype.compileNode=function(e,t){var n,i;return i=this.comment.replace(/^(\s*)#(?=\s)/gm,"$1 *"),n="/*"+ut(i,this.tab)+(Tt.call(i,"\n")>=0?"\n"+this.tab:"")+" */",(t||e.level)===L&&(n=e.indent+n),[this.makeCode("\n"),this.makeCode(n)]},t}(r),e.Call=o=function(e){function n(e,t,n){this.args=null!=t?t:[],this.soak=n,this.isNew=!1,this.isSuper="super"===e,this.variable=this.isSuper?null:e,e instanceof z&&e.isNotCallable()&&e.error("literal is not a function")}return kt(n,e),n.prototype.children=["variable","args"],n.prototype.newInstance=function(){var e,t;return e=(null!=(t=this.variable)?t.base:void 0)||this.variable,e instanceof n&&!e.isNew?e.newInstance():this.isNew=!0,this},n.prototype.superReference=function(e){var n,r,s,o,a,c,h,l;return a=e.scope.namedMethod(),(null!=a?a.klass:void 0)?(o=a.klass,c=a.name,l=a.variable,o.isComplex()&&(s=new x(e.scope.parent.freeVariable("base")),r=new z(new O(new i(s,o))),l.base=r,l.properties.splice(0,o.properties.length)),(c.isComplex()||c instanceof w&&c.index.isAssignable())&&(h=new x(e.scope.parent.freeVariable("name")),c=new w(new i(h,c.index)),l.properties.pop(),l.properties.push(c)),n=[new t(new x("__super__"))],a["static"]&&n.push(new t(new x("constructor"))),n.push(null!=h?new w(h):c),new z(null!=s?s:o,n).compile(e)):(null!=a?a.ctor:void 0)?a.name+".__super__.constructor":this.error("cannot call super outside of an instance method.")},n.prototype.superThis=function(e){var t;return t=e.scope.method,t&&!t.klass&&t.context||"this"},n.prototype.unfoldSoak=function(e){var t,i,r,s,o,a,c,h,l;if(this.soak){if(this.variable){if(i=yt(e,this,"variable"))return i;c=new z(this.variable).cacheReference(e),s=c[0],l=c[1]}else s=new x(this.superReference(e)),l=new z(s);return l=new n(l,this.args),l.isNew=this.isNew,s=new x("typeof "+s.compile(e)+' === "function"'),new b(s,new z(l),{soak:!0})}for(t=this,a=[];;)if(t.variable instanceof n)a.push(t),t=t.variable;else{if(!(t.variable instanceof z))break;if(a.push(t),!((t=t.variable.base)instanceof n))break}for(h=a.reverse(),r=0,o=h.length;o>r;r++)t=h[r],i&&(t.variable instanceof n?t.variable=i:t.variable.base=i),i=yt(e,t,"variable");return i},n.prototype.compileNode=function(e){var t,n,i,r,s,o,a,c,h,l;if(null!=(h=this.variable)&&(h.front=this.front),r=G.compileSplattedArray(e,this.args,!0),r.length)return this.compileSplat(e,r);for(i=[],l=this.args,n=o=0,a=l.length;a>o;n=++o)t=l[n],n&&i.push(this.makeCode(", ")),i.push.apply(i,t.compileToFragments(e,E));return s=[],this.isSuper?(c=this.superReference(e)+(".call("+this.superThis(e)),i.length&&(c+=", "),s.push(this.makeCode(c))):(this.isNew&&s.push(this.makeCode("new ")),s.push.apply(s,this.variable.compileToFragments(e,T)),s.push(this.makeCode("("))),s.push.apply(s,i),s.push(this.makeCode(")")),s},n.prototype.compileSplat=function(e,t){var n,i,r,s,o,a;return this.isSuper?[].concat(this.makeCode(this.superReference(e)+".apply("+this.superThis(e)+", "),t,this.makeCode(")")):this.isNew?(s=this.tab+q,[].concat(this.makeCode("(function(func, args, ctor) {\n"+s+"ctor.prototype = func.prototype;\n"+s+"var child = new ctor, result = func.apply(child, args);\n"+s+"return Object(result) === result ? result : child;\n"+this.tab+"})("),this.variable.compileToFragments(e,E),this.makeCode(", "),t,this.makeCode(", function(){})"))):(n=[],i=new z(this.variable),(o=i.properties.pop())&&i.isComplex()?(a=e.scope.freeVariable("ref"),n=n.concat(this.makeCode("("+a+" = "),i.compileToFragments(e,E),this.makeCode(")"),o.compileToFragments(e))):(r=i.compileToFragments(e,T),B.test(st(r))&&(r=this.wrapInBraces(r)),o?(a=st(r),r.push.apply(r,o.compileToFragments(e))):a="null",n=n.concat(r)),n=n.concat(this.makeCode(".apply("+a+", "),t,this.makeCode(")")))},n}(r),e.Extends=d=function(e){function t(e,t){this.child=e,this.parent=t}return kt(t,e),t.prototype.children=["child","parent"],t.prototype.compileToFragments=function(e){return new o(new z(new x(bt("extend",e))),[this.child,this.parent]).compileToFragments(e)},t}(r),e.Access=t=function(e){function t(e,t){this.name=e,this.name.asKey=!0,this.soak="soak"===t}return kt(t,e),t.prototype.children=["name"],t.prototype.compileToFragments=function(e){var t;return t=this.name.compileToFragments(e),g.test(st(t))?t.unshift(this.makeCode(".")):(t.unshift(this.makeCode("[")),t.push(this.makeCode("]"))),t},t.prototype.isComplex=D,t}(r),e.Index=w=function(e){function t(e){this.index=e}return kt(t,e),t.prototype.children=["index"],t.prototype.compileToFragments=function(e){return[].concat(this.makeCode("["),this.index.compileToFragments(e,N),this.makeCode("]"))},t.prototype.isComplex=function(){return this.index.isComplex()},t}(r),e.Range=j=function(e){function t(e,t,n){this.from=e,this.to=t,this.exclusive="exclusive"===n,this.equals=this.exclusive?"":"="}return kt(t,e),t.prototype.children=["from","to"],t.prototype.compileVariables=function(e){var t,n,i,r,s,o;return e=lt(e,{top:!0}),t=tt(e,"isComplex"),n=this.cacheToCodeFragments(this.from.cache(e,E,t)),this.fromC=n[0],this.fromVar=n[1],i=this.cacheToCodeFragments(this.to.cache(e,E,t)),this.toC=i[0],this.toVar=i[1],(o=tt(e,"step"))&&(r=this.cacheToCodeFragments(o.cache(e,E,t)),this.step=r[0],this.stepVar=r[1]),s=[this.fromVar.match(R),this.toVar.match(R)],this.fromNum=s[0],this.toNum=s[1],this.stepVar?this.stepNum=this.stepVar.match(R):void 0},t.prototype.compileNode=function(e){var t,n,i,r,s,o,a,c,h,l,u,p,d,f;return this.fromVar||this.compileVariables(e),e.index?(a=this.fromNum&&this.toNum,s=tt(e,"index"),o=tt(e,"name"),h=o&&o!==s,f=s+" = "+this.fromC,this.toC!==this.toVar&&(f+=", "+this.toC),this.step!==this.stepVar&&(f+=", "+this.step),l=[s+" <"+this.equals,s+" >"+this.equals],c=l[0],r=l[1],n=this.stepNum?pt(this.stepNum[0])>0?c+" "+this.toVar:r+" "+this.toVar:a?(u=[pt(this.fromNum[0]),pt(this.toNum[0])],i=u[0],d=u[1],u,d>=i?c+" "+d:r+" "+d):(t=this.stepVar?this.stepVar+" > 0":this.fromVar+" <= "+this.toVar,t+" ? "+c+" "+this.toVar+" : "+r+" "+this.toVar),p=this.stepVar?s+" += "+this.stepVar:a?h?d>=i?"++"+s:"--"+s:d>=i?s+"++":s+"--":h?t+" ? ++"+s+" : --"+s:t+" ? "+s+"++ : "+s+"--",h&&(f=o+" = "+f),h&&(p=o+" = "+p),[this.makeCode(f+"; "+n+"; "+p)]):this.compileArray(e)},t.prototype.compileArray=function(e){var t,n,i,r,s,o,a,c,h,l,u,p,d;return this.fromNum&&this.toNum&&20>=Math.abs(this.fromNum-this.toNum)?(h=function(){p=[];for(var e=l=+this.fromNum,t=+this.toNum;t>=l?t>=e:e>=t;t>=l?e++:e--)p.push(e);return p}.apply(this),this.exclusive&&h.pop(),[this.makeCode("["+h.join(", ")+"]")]):(o=this.tab+q,s=e.scope.freeVariable("i",{single:!0}),u=e.scope.freeVariable("results"),c="\n"+o+u+" = [];",this.fromNum&&this.toNum?(e.index=s,n=st(this.compileNode(e))):(d=s+" = "+this.fromC+(this.toC!==this.toVar?", "+this.toC:""),i=this.fromVar+" <= "+this.toVar,n="var "+d+"; "+i+" ? "+s+" <"+this.equals+" "+this.toVar+" : "+s+" >"+this.equals+" "+this.toVar+"; "+i+" ? "+s+"++ : "+s+"--"),a="{ "+u+".push("+s+"); }\n"+o+"return "+u+";\n"+e.indent,r=function(e){return null!=e?e.contains(at):void 0},(r(this.from)||r(this.to))&&(t=", arguments"),[this.makeCode("(function() {"+c+"\n"+o+"for ("+n+")"+a+"}).apply(this"+(null!=t?t:"")+")")])},t}(r),e.Slice=U=function(e){function t(e){this.range=e,t.__super__.constructor.call(this)}return kt(t,e),t.prototype.children=["range"],t.prototype.compileNode=function(e){var t,n,i,r,s,o,a;return s=this.range,o=s.to,i=s.from,r=i&&i.compileToFragments(e,N)||[this.makeCode("0")],o&&(t=o.compileToFragments(e,N),n=st(t),(this.range.exclusive||-1!==+n)&&(a=", "+(this.range.exclusive?n:B.test(n)?""+(+n+1):(t=o.compileToFragments(e,T),"+"+st(t)+" + 1 || 9e9")))),[this.makeCode(".slice("+st(r)+(a||"")+")")]},t}(r),e.Obj=A=function(e){function n(e,t){this.generated=null!=t?t:!1,this.objects=this.properties=e||[]}return kt(n,e),n.prototype.children=["properties"],n.prototype.compileNode=function(e){var n,r,s,o,a,c,h,u,p,d,f,m,g,v,y,b,k,w,T,C,E;if(T=this.properties,this.generated)for(h=0,g=T.length;g>h;h++)b=T[h],b instanceof z&&b.error("cannot have an implicit value in an implicit object");for(r=p=0,v=T.length;v>p&&(w=T[r],!((w.variable||w).base instanceof O));r=++p);for(s=T.length>r,a=e.indent+=q,m=this.lastNonComment(this.properties),n=[],s&&(k=e.scope.freeVariable("obj"),n.push(this.makeCode("(\n"+a+k+" = "))),n.push(this.makeCode("{"+(0===T.length||0===r?"}":"\n"))),o=f=0,y=T.length;y>f;o=++f)w=T[o],o===r&&(0!==o&&n.push(this.makeCode("\n"+a+"}")),n.push(this.makeCode(",\n"))),u=o===T.length-1||o===r-1?"":w===m||w instanceof l?"\n":",\n",c=w instanceof l?"":a,s&&r>o&&(c+=q),w instanceof i&&w.variable instanceof z&&w.variable.hasProperties()&&w.variable.error("invalid object key"),w instanceof z&&w["this"]&&(w=new i(w.properties[0].name,w,"object")),w instanceof l||(r>o?(w instanceof i||(w=new i(w,w,"object")),(w.variable.base||w.variable).asKey=!0):(w instanceof i?(d=w.variable,E=w.value):(C=w.base.cache(e),d=C[0],E=C[1]),w=new i(new z(new x(k),[new t(d)]),E))),c&&n.push(this.makeCode(c)),n.push.apply(n,w.compileToFragments(e,L)),u&&n.push(this.makeCode(u));return s?n.push(this.makeCode(",\n"+a+k+"\n"+this.tab+")")):0!==T.length&&n.push(this.makeCode("\n"+this.tab+"}")),this.front&&!s?this.wrapInBraces(n):n},n.prototype.assigns=function(e){var t,n,i,r;for(r=this.properties,t=0,n=r.length;n>t;t++)if(i=r[t],i.assigns(e))return!0;return!1},n}(r),e.Arr=n=function(e){function t(e){this.objects=e||[]}return kt(t,e),t.prototype.children=["objects"],t.prototype.compileNode=function(e){var t,n,i,r,s,o,a;if(!this.objects.length)return[this.makeCode("[]")];if(e.indent+=q,t=G.compileSplattedArray(e,this.objects),t.length)return t;for(t=[],n=function(){var t,n,i,r;for(i=this.objects,r=[],t=0,n=i.length;n>t;t++)a=i[t],r.push(a.compileToFragments(e,E));return r}.call(this),r=s=0,o=n.length;o>s;r=++s)i=n[r],r&&t.push(this.makeCode(", ")),t.push.apply(t,i);return st(t).indexOf("\n")>=0?(t.unshift(this.makeCode("[\n"+e.indent)),t.push(this.makeCode("\n"+this.tab+"]"))):(t.unshift(this.makeCode("[")),t.push(this.makeCode("]"))),t},t.prototype.assigns=function(e){var t,n,i,r;for(r=this.objects,t=0,n=r.length;n>t;t++)if(i=r[t],i.assigns(e))return!0;return!1},t}(r),e.Class=a=function(e){function n(e,t,n){this.variable=e,this.parent=t,this.body=null!=n?n:new s,this.boundFuncs=[],this.body.classBody=!0}return kt(n,e),n.prototype.children=["variable","parent","body"],n.prototype.determineName=function(){var e,n,i;return this.variable?(n=this.variable.properties,i=n[n.length-1],e=i?i instanceof t&&i.name.value:this.variable.base.value,Tt.call(V,e)>=0&&this.variable.error("class variable name may not be "+e),e&&(e=g.test(e)&&e)):null},n.prototype.setContext=function(e){return this.body.traverseChildren(!1,function(t){return t.classBody?!1:t instanceof x&&"this"===t.value?t.value=e:t instanceof c&&t.bound?t.context=e:void 0})},n.prototype.addBoundFunctions=function(e){var n,i,r,s,o;for(o=this.boundFuncs,i=0,r=o.length;r>i;i++)n=o[i],s=new z(new x("this"),[new t(n)]).compile(e),this.ctor.body.unshift(new x(s+" = "+bt("bind",e)+"("+s+", this)"))},n.prototype.addProperties=function(e,n,r){var s,o,a,h,l,u;return u=e.base.properties.slice(0),h=function(){var e;for(e=[];o=u.shift();)o instanceof i&&(a=o.variable.base,delete o.context,l=o.value,"constructor"===a.value?(this.ctor&&o.error("cannot define more than one constructor in a class"),l.bound&&o.error("cannot define a constructor as a bound function"),l instanceof c?o=this.ctor=l:(this.externalCtor=r.classScope.freeVariable("class"),o=new i(new x(this.externalCtor),l))):o.variable["this"]?l["static"]=!0:(s=a.isComplex()?new w(a):new t(a),o.variable=new z(new x(n),[new t(new x("prototype")),s]),l instanceof c&&l.bound&&(this.boundFuncs.push(a),l.bound=!1))),e.push(o);return e}.call(this),et(h)},n.prototype.walkBody=function(e,t){return this.traverseChildren(!1,function(r){return function(o){var a,c,h,l,u,p,d;if(a=!0,o instanceof n)return!1;if(o instanceof s){for(d=c=o.expressions,h=l=0,u=d.length;u>l;h=++l)p=d[h],p instanceof i&&p.variable.looksStatic(e)?p.value["static"]=!0:p instanceof z&&p.isObject(!0)&&(a=!1,c[h]=r.addProperties(p,e,t));o.expressions=c=rt(c)}return a&&!(o instanceof n)}}(this))},n.prototype.hoistDirectivePrologue=function(){var e,t,n;for(t=0,e=this.body.expressions;(n=e[t])&&n instanceof l||n instanceof z&&n.isString();)++t;return this.directives=e.splice(0,t)},n.prototype.ensureConstructor=function(e){return this.ctor||(this.ctor=new c,this.externalCtor?this.ctor.body.push(new x(this.externalCtor+".apply(this, arguments)")):this.parent&&this.ctor.body.push(new x(e+".__super__.constructor.apply(this, arguments)")),this.ctor.body.makeReturn(),this.body.expressions.unshift(this.ctor)),this.ctor.ctor=this.ctor.name=e,this.ctor.klass=null,this.ctor.noReturn=!0},n.prototype.compileNode=function(e){var t,n,r,a,h,l,u,p,f;return(a=this.body.jumps())&&a.error("Class bodies cannot contain pure statements"),(n=this.body.contains(at))&&n.error("Class bodies shouldn't reference arguments"),u=this.determineName()||"_Class",u.reserved&&(u="_"+u),l=new x(u),r=new c([],s.wrap([this.body])),t=[],e.classScope=r.makeScope(e.scope),this.hoistDirectivePrologue(),this.setContext(u),this.walkBody(u,e),this.ensureConstructor(u),this.addBoundFunctions(e),this.body.spaced=!0,this.body.expressions.push(l),this.parent&&(f=new x(e.classScope.freeVariable("superClass",{reserve:!1})),this.body.expressions.unshift(new d(l,f)),r.params.push(new _(f)),t.push(this.parent)),(p=this.body.expressions).unshift.apply(p,this.directives),h=new O(new o(r,t)),this.variable&&(h=new i(this.variable,h)),h.compileToFragments(e)},n}(r),e.Assign=i=function(e){function n(e,t,n,i){var r,s,o;this.variable=e,this.value=t,this.context=n,this.param=i&&i.param,this.subpattern=i&&i.subpattern,o=s=this.variable.unwrapAll().value,r=Tt.call(V,o)>=0,r&&"object"!==this.context&&this.variable.error('variable name may not be "'+s+'"')}return kt(n,e),n.prototype.children=["variable","value"],n.prototype.isStatement=function(e){return(null!=e?e.level:void 0)===L&&null!=this.context&&Tt.call(this.context,"?")>=0
-},n.prototype.assigns=function(e){return this["object"===this.context?"value":"variable"].assigns(e)},n.prototype.unfoldSoak=function(e){return yt(e,this,"variable")},n.prototype.compileNode=function(e){var t,n,i,r,s,o,a,h,l,u,p,d,f,m;if(i=this.variable instanceof z){if(this.variable.isArray()||this.variable.isObject())return this.compilePatternMatch(e);if(this.variable.isSplice())return this.compileSplice(e);if("||="===(h=this.context)||"&&="===h||"?="===h)return this.compileConditional(e);if("**="===(l=this.context)||"//="===l||"%%="===l)return this.compileSpecialMath(e)}return this.value instanceof c&&(this.value["static"]?(this.value.klass=this.variable.base,this.value.name=this.variable.properties[0],this.value.variable=this.variable):(null!=(u=this.variable.properties)?u.length:void 0)>=2&&(p=this.variable.properties,o=p.length>=3?Ct.call(p,0,r=p.length-2):(r=0,[]),a=p[r++],s=p[r++],"prototype"===(null!=(d=a.name)?d.value:void 0)&&(this.value.klass=new z(this.variable.base,o),this.value.name=s,this.value.variable=this.variable))),this.context||(m=this.variable.unwrapAll(),m.isAssignable()||this.variable.error('"'+this.variable.compile(e)+'" cannot be assigned'),("function"==typeof m.hasProperties?m.hasProperties():void 0)||(this.param?e.scope.add(m.value,"var"):e.scope.find(m.value))),f=this.value.compileToFragments(e,E),n=this.variable.compileToFragments(e,E),"object"===this.context?n.concat(this.makeCode(": "),f):(t=n.concat(this.makeCode(" "+(this.context||"=")+" "),f),E>=e.level?t:this.wrapInBraces(t))},n.prototype.compilePatternMatch=function(e){var i,r,s,o,a,c,h,l,u,d,f,m,v,y,b,k,T,C,N,S,D,R,A,I,_,j,M,B;if(I=e.level===L,j=this.value,y=this.variable.base.objects,!(b=y.length))return s=j.compileToFragments(e),e.level>=F?this.wrapInBraces(s):s;if(l=this.variable.isObject(),I&&1===b&&!((v=y[0])instanceof G))return v instanceof n?(T=v,C=T.variable,h=C.base,v=T.value):h=l?v["this"]?v.properties[0].name:v:new x(0),i=g.test(h.unwrap().value||0),j=new z(j),j.properties.push(new(i?t:w)(h)),N=v.unwrap().value,Tt.call($,N)>=0&&v.error("assignment to a reserved word: "+v.compile(e)),new n(v,j,null,{param:this.param}).compileToFragments(e,L);for(M=j.compileToFragments(e,E),B=st(M),r=[],o=!1,(!g.test(B)||this.variable.assigns(B))&&(r.push([this.makeCode((k=e.scope.freeVariable("ref"))+" = ")].concat(Ct.call(M))),M=[this.makeCode(k)],B=k),c=d=0,f=y.length;f>d;c=++d){if(v=y[c],h=c,l&&(v instanceof n?(S=v,D=S.variable,h=D.base,v=S.value):v.base instanceof O?(R=new z(v.unwrapAll()).cacheReference(e),v=R[0],h=R[1]):h=v["this"]?v.properties[0].name:v),!o&&v instanceof G)m=v.name.unwrap().value,v=v.unwrap(),_=b+" <= "+B+".length ? "+bt("slice",e)+".call("+B+", "+c,(A=b-c-1)?(u=e.scope.freeVariable("i",{single:!0}),_+=", "+u+" = "+B+".length - "+A+") : ("+u+" = "+c+", [])"):_+=") : []",_=new x(_),o=u+"++";else{if(!o&&v instanceof p){(A=b-c-1)&&(1===A?o=B+".length - 1":(u=e.scope.freeVariable("i",{single:!0}),_=new x(u+" = "+B+".length - "+A),o=u+"++",r.push(_.compileToFragments(e,E))));continue}m=v.unwrap().value,(v instanceof G||v instanceof p)&&v.error("multiple splats/expansions are disallowed in an assignment"),"number"==typeof h?(h=new x(o||h),i=!1):i=l&&g.test(h.unwrap().value||0),_=new z(new x(B),[new(i?t:w)(h)])}null!=m&&Tt.call($,m)>=0&&v.error("assignment to a reserved word: "+v.compile(e)),r.push(new n(v,_,null,{param:this.param,subpattern:!0}).compileToFragments(e,E))}return I||this.subpattern||r.push(M),a=this.joinFragmentArrays(r,", "),E>e.level?a:this.wrapInBraces(a)},n.prototype.compileConditional=function(e){var t,i,r,s;return r=this.variable.cacheReference(e),i=r[0],s=r[1],!i.properties.length&&i.base instanceof x&&"this"!==i.base.value&&!e.scope.check(i.base.value)&&this.variable.error('the variable "'+i.base.value+"\" can't be assigned with "+this.context+" because it has not been declared before"),Tt.call(this.context,"?")>=0?(e.isExistentialEquals=!0,new b(new u(i),s,{type:"if"}).addElse(new n(s,this.value,"=")).compileToFragments(e)):(t=new I(this.context.slice(0,-1),i,new n(s,this.value,"=")).compileToFragments(e),E>=e.level?t:this.wrapInBraces(t))},n.prototype.compileSpecialMath=function(e){var t,i,r;return i=this.variable.cacheReference(e),t=i[0],r=i[1],new n(t,new I(this.context.slice(0,-1),r,this.value)).compileToFragments(e)},n.prototype.compileSplice=function(e){var t,n,i,r,s,o,a,c,h,l,u,p;return a=this.variable.properties.pop().range,i=a.from,l=a.to,n=a.exclusive,o=this.variable.compile(e),i?(c=this.cacheToCodeFragments(i.cache(e,F)),r=c[0],s=c[1]):r=s="0",l?i instanceof z&&i.isSimpleNumber()&&l instanceof z&&l.isSimpleNumber()?(l=l.compile(e)-s,n||(l+=1)):(l=l.compile(e,T)+" - "+s,n||(l+=" + 1")):l="9e9",h=this.value.cache(e,E),u=h[0],p=h[1],t=[].concat(this.makeCode("[].splice.apply("+o+", ["+r+", "+l+"].concat("),u,this.makeCode(")), "),p),e.level>L?this.wrapInBraces(t):t},n}(r),e.Code=c=function(e){function t(e,t,n){this.params=e||[],this.body=t||new s,this.bound="boundfunc"===n,this.isGenerator=!!this.body.contains(function(e){var t;return e instanceof I&&("yield"===(t=e.operator)||"yield*"===t)})}return kt(t,e),t.prototype.children=["params","body"],t.prototype.isStatement=function(){return!!this.ctor},t.prototype.jumps=D,t.prototype.makeScope=function(e){return new P(e,this.body,this)},t.prototype.compileNode=function(e){var r,a,c,h,l,u,d,f,m,g,v,y,k,w,C,E,F,N,L,S,D,R,A,O,$,j,M,B,V,P,U,G,H;if(this.bound&&(null!=(A=e.scope.method)?A.bound:void 0)&&(this.context=e.scope.method.context),this.bound&&!this.context)return this.context="_this",H=new t([new _(new x(this.context))],new s([this])),a=new o(H,[new x("this")]),a.updateLocationDataIfMissing(this.locationData),a.compileNode(e);for(e.scope=tt(e,"classScope")||this.makeScope(e.scope),e.scope.shared=tt(e,"sharedScope"),e.indent+=q,delete e.bare,delete e.isExistentialEquals,L=[],h=[],O=this.params,u=0,m=O.length;m>u;u++)N=O[u],N instanceof p||e.scope.parameter(N.asReference(e));for($=this.params,d=0,g=$.length;g>d;d++)if(N=$[d],N.splat||N instanceof p){for(j=this.params,f=0,v=j.length;v>f;f++)F=j[f],F instanceof p||!F.name.value||e.scope.add(F.name.value,"var",!0);V=new i(new z(new n(function(){var t,n,i,r;for(i=this.params,r=[],n=0,t=i.length;t>n;n++)F=i[n],r.push(F.asReference(e));return r}.call(this))),new z(new x("arguments")));break}for(M=this.params,E=0,y=M.length;y>E;E++)N=M[E],N.isComplex()?(U=R=N.asReference(e),N.value&&(U=new I("?",R,N.value)),h.push(new i(new z(N.name),U,"=",{param:!0}))):(R=N,N.value&&(C=new x(R.name.value+" == null"),U=new i(new z(N.name),N.value,"="),h.push(new b(C,U)))),V||L.push(R);for(G=this.body.isEmpty(),V&&h.unshift(V),h.length&&(B=this.body.expressions).unshift.apply(B,h),l=S=0,k=L.length;k>S;l=++S)F=L[l],L[l]=F.compileToFragments(e),e.scope.parameter(st(L[l]));for(P=[],this.eachParamName(function(e,t){return Tt.call(P,e)>=0&&t.error("multiple parameters named "+e),P.push(e)}),G||this.noReturn||this.body.makeReturn(),c="function",this.isGenerator&&(c+="*"),this.ctor&&(c+=" "+this.name),c+="(",r=[this.makeCode(c)],l=D=0,w=L.length;w>D;l=++D)F=L[l],l&&r.push(this.makeCode(", ")),r.push.apply(r,F);return r.push(this.makeCode(") {")),this.body.isEmpty()||(r=r.concat(this.makeCode("\n"),this.body.compileWithDeclarations(e),this.makeCode("\n"+this.tab))),r.push(this.makeCode("}")),this.ctor?[this.makeCode(this.tab)].concat(Ct.call(r)):this.front||e.level>=T?this.wrapInBraces(r):r},t.prototype.eachParamName=function(e){var t,n,i,r,s;for(r=this.params,s=[],t=0,n=r.length;n>t;t++)i=r[t],s.push(i.eachName(e));return s},t.prototype.traverseChildren=function(e,n){return e?t.__super__.traverseChildren.call(this,e,n):void 0},t}(r),e.Param=_=function(e){function t(e,t,n){var i,r;this.name=e,this.value=t,this.splat=n,r=i=this.name.unwrapAll().value,Tt.call(V,r)>=0&&this.name.error('parameter name "'+i+'" is not allowed')}return kt(t,e),t.prototype.children=["name","value"],t.prototype.compileToFragments=function(e){return this.name.compileToFragments(e,E)},t.prototype.asReference=function(e){var t,n;return this.reference?this.reference:(n=this.name,n["this"]?(t=n.properties[0].name.value,t.reserved&&(t="_"+t),n=new x(e.scope.freeVariable(t))):n.isComplex()&&(n=new x(e.scope.freeVariable("arg"))),n=new z(n),this.splat&&(n=new G(n)),n.updateLocationDataIfMissing(this.locationData),this.reference=n)},t.prototype.isComplex=function(){return this.name.isComplex()},t.prototype.eachName=function(e,t){var n,r,s,o,a,c;if(null==t&&(t=this.name),n=function(t){return e("@"+t.properties[0].name.value,t)},t instanceof x)return e(t.value,t);if(t instanceof z)return n(t);for(c=t.objects,r=0,s=c.length;s>r;r++)a=c[r],a instanceof i?this.eachName(e,a.value.unwrap()):a instanceof G?(o=a.name.unwrap(),e(o.value,o)):a instanceof z?a.isArray()||a.isObject()?this.eachName(e,a.base):a["this"]?n(a):e(a.base.value,a.base):a instanceof p||a.error("illegal parameter "+a.compile())},t}(r),e.Splat=G=function(e){function t(e){this.name=e.compile?e:new x(e)}return kt(t,e),t.prototype.children=["name"],t.prototype.isAssignable=Q,t.prototype.assigns=function(e){return this.name.assigns(e)},t.prototype.compileToFragments=function(e){return this.name.compileToFragments(e)},t.prototype.unwrap=function(){return this.name},t.compileSplattedArray=function(e,n,i){var r,s,o,a,c,h,l,u,p,d,f;for(l=-1;(f=n[++l])&&!(f instanceof t););if(l>=n.length)return[];if(1===n.length)return f=n[0],c=f.compileToFragments(e,E),i?c:[].concat(f.makeCode(bt("slice",e)+".call("),c,f.makeCode(")"));for(r=n.slice(l),h=u=0,d=r.length;d>u;h=++u)f=r[h],o=f.compileToFragments(e,E),r[h]=f instanceof t?[].concat(f.makeCode(bt("slice",e)+".call("),o,f.makeCode(")")):[].concat(f.makeCode("["),o,f.makeCode("]"));return 0===l?(f=n[0],a=f.joinFragmentArrays(r.slice(1),", "),r[0].concat(f.makeCode(".concat("),a,f.makeCode(")"))):(s=function(){var t,i,r,s;for(r=n.slice(0,l),s=[],t=0,i=r.length;i>t;t++)f=r[t],s.push(f.compileToFragments(e,E));return s}(),s=n[0].joinFragmentArrays(s,", "),a=n[l].joinFragmentArrays(r,", "),p=n[n.length-1],[].concat(n[0].makeCode("["),s,n[l].makeCode("].concat("),a,p.makeCode(")")))},t}(r),e.Expansion=p=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return kt(t,e),t.prototype.isComplex=D,t.prototype.compileNode=function(){return this.error("Expansion must be used inside a destructuring assignment or parameter list")},t.prototype.asReference=function(){return this},t.prototype.eachName=function(){},t}(r),e.While=J=function(e){function t(e,t){this.condition=(null!=t?t.invert:void 0)?e.invert():e,this.guard=null!=t?t.guard:void 0}return kt(t,e),t.prototype.children=["condition","guard","body"],t.prototype.isStatement=Q,t.prototype.makeReturn=function(e){return e?t.__super__.makeReturn.apply(this,arguments):(this.returns=!this.jumps({loop:!0}),this)},t.prototype.addBody=function(e){return this.body=e,this},t.prototype.jumps=function(){var e,t,n,i,r;if(e=this.body.expressions,!e.length)return!1;for(t=0,i=e.length;i>t;t++)if(r=e[t],n=r.jumps({loop:!0}))return n;return!1},t.prototype.compileNode=function(e){var t,n,i,r;return e.indent+=q,r="",n=this.body,n.isEmpty()?n=this.makeCode(""):(this.returns&&(n.makeReturn(i=e.scope.freeVariable("results")),r=""+this.tab+i+" = [];\n"),this.guard&&(n.expressions.length>1?n.expressions.unshift(new b(new O(this.guard).invert(),new x("continue"))):this.guard&&(n=s.wrap([new b(this.guard,n)]))),n=[].concat(this.makeCode("\n"),n.compileToFragments(e,L),this.makeCode("\n"+this.tab))),t=[].concat(this.makeCode(r+this.tab+"while ("),this.condition.compileToFragments(e,N),this.makeCode(") {"),n,this.makeCode("}")),this.returns&&t.push(this.makeCode("\n"+this.tab+"return "+i+";")),t},t}(r),e.Op=I=function(e){function n(e,t,n,i){if("in"===e)return new k(t,n);if("do"===e)return this.generateDo(t);if("new"===e){if(t instanceof o&&!t["do"]&&!t.isNew)return t.newInstance();(t instanceof c&&t.bound||t["do"])&&(t=new O(t))}return this.operator=r[e]||e,this.first=t,this.second=n,this.flip=!!i,this}var r,s;return kt(n,e),r={"==":"===","!=":"!==",of:"in",yieldfrom:"yield*"},s={"!==":"===","===":"!=="},n.prototype.children=["first","second"],n.prototype.isSimpleNumber=D,n.prototype.isYield=function(){var e;return"yield"===(e=this.operator)||"yield*"===e},n.prototype.isYieldReturn=function(){return this.isYield()&&this.first instanceof M},n.prototype.isUnary=function(){return!this.second},n.prototype.isComplex=function(){var e;return!(this.isUnary()&&("+"===(e=this.operator)||"-"===e)&&this.first instanceof z&&this.first.isSimpleNumber())},n.prototype.isChainable=function(){var e;return"<"===(e=this.operator)||">"===e||">="===e||"<="===e||"==="===e||"!=="===e},n.prototype.invert=function(){var e,t,i,r,o;if(this.isChainable()&&this.first.isChainable()){for(e=!0,t=this;t&&t.operator;)e&&(e=t.operator in s),t=t.first;if(!e)return new O(this).invert();for(t=this;t&&t.operator;)t.invert=!t.invert,t.operator=s[t.operator],t=t.first;return this}return(r=s[this.operator])?(this.operator=r,this.first.unwrap()instanceof n&&this.first.invert(),this):this.second?new O(this).invert():"!"===this.operator&&(i=this.first.unwrap())instanceof n&&("!"===(o=i.operator)||"in"===o||"instanceof"===o)?i:new n("!",this)},n.prototype.unfoldSoak=function(e){var t;return("++"===(t=this.operator)||"--"===t||"delete"===t)&&yt(e,this,"first")},n.prototype.generateDo=function(e){var t,n,r,s,a,h,l,u;for(h=[],n=e instanceof i&&(l=e.value.unwrap())instanceof c?l:e,u=n.params||[],r=0,s=u.length;s>r;r++)a=u[r],a.value?(h.push(a.value),delete a.value):h.push(a);return t=new o(e,h),t["do"]=!0,t},n.prototype.compileNode=function(e){var t,n,i,r,s,o;if(n=this.isChainable()&&this.first.isChainable(),n||(this.first.front=this.front),"delete"===this.operator&&e.scope.check(this.first.unwrapAll().value)&&this.error("delete operand may not be argument or var"),("--"===(r=this.operator)||"++"===r)&&(s=this.first.unwrapAll().value,Tt.call(V,s)>=0)&&this.error('cannot increment/decrement "'+this.first.unwrapAll().value+'"'),this.isYield())return this.compileYield(e);if(this.isUnary())return this.compileUnary(e);if(n)return this.compileChain(e);switch(this.operator){case"?":return this.compileExistence(e);case"**":return this.compilePower(e);case"//":return this.compileFloorDivision(e);case"%%":return this.compileModulo(e);default:return i=this.first.compileToFragments(e,F),o=this.second.compileToFragments(e,F),t=[].concat(i,this.makeCode(" "+this.operator+" "),o),F>=e.level?t:this.wrapInBraces(t)}},n.prototype.compileChain=function(e){var t,n,i,r;return i=this.first.second.cache(e),this.first.second=i[0],r=i[1],n=this.first.compileToFragments(e,F),t=n.concat(this.makeCode(" "+(this.invert?"&&":"||")+" "),r.compileToFragments(e),this.makeCode(" "+this.operator+" "),this.second.compileToFragments(e,F)),this.wrapInBraces(t)},n.prototype.compileExistence=function(e){var t,n;return this.first.isComplex()?(n=new x(e.scope.freeVariable("ref")),t=new O(new i(n,this.first))):(t=this.first,n=t),new b(new u(t),n,{type:"if"}).addElse(this.second).compileToFragments(e)},n.prototype.compileUnary=function(e){var t,i,r;return i=[],t=this.operator,i.push([this.makeCode(t)]),"!"===t&&this.first instanceof u?(this.first.negated=!this.first.negated,this.first.compileToFragments(e)):e.level>=T?new O(this).compileToFragments(e):(r="+"===t||"-"===t,("new"===t||"typeof"===t||"delete"===t||r&&this.first instanceof n&&this.first.operator===t)&&i.push([this.makeCode(" ")]),(r&&this.first instanceof n||"new"===t&&this.first.isStatement(e))&&(this.first=new O(this.first)),i.push(this.first.compileToFragments(e,F)),this.flip&&i.reverse(),this.joinFragmentArrays(i,""))},n.prototype.compileYield=function(e){var t,n;return n=[],t=this.operator,null==e.scope.parent&&this.error("yield statements must occur within a function generator."),Tt.call(Object.keys(this.first),"expression")>=0&&!(this.first instanceof W)?this.isYieldReturn()?n.push(this.first.compileToFragments(e,L)):null!=this.first.expression&&n.push(this.first.expression.compileToFragments(e,F)):(n.push([this.makeCode("("+t+" ")]),n.push(this.first.compileToFragments(e,F)),n.push([this.makeCode(")")])),this.joinFragmentArrays(n,"")},n.prototype.compilePower=function(e){var n;return n=new z(new x("Math"),[new t(new x("pow"))]),new o(n,[this.first,this.second]).compileToFragments(e)},n.prototype.compileFloorDivision=function(e){var i,r;return r=new z(new x("Math"),[new t(new x("floor"))]),i=new n("/",this.first,this.second),new o(r,[i]).compileToFragments(e)},n.prototype.compileModulo=function(e){var t;return t=new z(new x(bt("modulo",e))),new o(t,[this.first,this.second]).compileToFragments(e)},n.prototype.toString=function(e){return n.__super__.toString.call(this,e,this.constructor.name+" "+this.operator)},n}(r),e.In=k=function(e){function t(e,t){this.object=e,this.array=t}return kt(t,e),t.prototype.children=["object","array"],t.prototype.invert=S,t.prototype.compileNode=function(e){var t,n,i,r,s;if(this.array instanceof z&&this.array.isArray()&&this.array.base.objects.length){for(s=this.array.base.objects,n=0,i=s.length;i>n;n++)if(r=s[n],r instanceof G){t=!0;break}if(!t)return this.compileOrTest(e)}return this.compileLoopTest(e)},t.prototype.compileOrTest=function(e){var t,n,i,r,s,o,a,c,h,l,u,p;for(c=this.object.cache(e,F),u=c[0],a=c[1],h=this.negated?[" !== "," && "]:[" === "," || "],t=h[0],n=h[1],p=[],l=this.array.base.objects,i=s=0,o=l.length;o>s;i=++s)r=l[i],i&&p.push(this.makeCode(n)),p=p.concat(i?a:u,this.makeCode(t),r.compileToFragments(e,T));return F>e.level?p:this.wrapInBraces(p)},t.prototype.compileLoopTest=function(e){var t,n,i,r;return i=this.object.cache(e,E),r=i[0],n=i[1],t=[].concat(this.makeCode(bt("indexOf",e)+".call("),this.array.compileToFragments(e,E),this.makeCode(", "),n,this.makeCode(") "+(this.negated?"< 0":">= 0"))),st(r)===st(n)?t:(t=r.concat(this.makeCode(", "),t),E>e.level?t:this.wrapInBraces(t))},t.prototype.toString=function(e){return t.__super__.toString.call(this,e,this.constructor.name+(this.negated?"!":""))},t}(r),e.Try=Y=function(e){function t(e,t,n,i){this.attempt=e,this.errorVariable=t,this.recovery=n,this.ensure=i}return kt(t,e),t.prototype.children=["attempt","recovery","ensure"],t.prototype.isStatement=Q,t.prototype.jumps=function(e){var t;return this.attempt.jumps(e)||(null!=(t=this.recovery)?t.jumps(e):void 0)},t.prototype.makeReturn=function(e){return this.attempt&&(this.attempt=this.attempt.makeReturn(e)),this.recovery&&(this.recovery=this.recovery.makeReturn(e)),this},t.prototype.compileNode=function(e){var t,n,r,s;return e.indent+=q,s=this.attempt.compileToFragments(e,L),t=this.recovery?(r=new x("_error"),this.errorVariable?this.recovery.unshift(new i(this.errorVariable,r)):void 0,[].concat(this.makeCode(" catch ("),r.compileToFragments(e),this.makeCode(") {\n"),this.recovery.compileToFragments(e,L),this.makeCode("\n"+this.tab+"}"))):this.ensure||this.recovery?[]:[this.makeCode(" catch (_error) {}")],n=this.ensure?[].concat(this.makeCode(" finally {\n"),this.ensure.compileToFragments(e,L),this.makeCode("\n"+this.tab+"}")):[],[].concat(this.makeCode(this.tab+"try {\n"),s,this.makeCode("\n"+this.tab+"}"),t,n)},t}(r),e.Throw=W=function(e){function t(e){this.expression=e}return kt(t,e),t.prototype.children=["expression"],t.prototype.isStatement=Q,t.prototype.jumps=D,t.prototype.makeReturn=X,t.prototype.compileNode=function(e){return[].concat(this.makeCode(this.tab+"throw "),this.expression.compileToFragments(e),this.makeCode(";"))},t}(r),e.Existence=u=function(e){function t(e){this.expression=e}return kt(t,e),t.prototype.children=["expression"],t.prototype.invert=S,t.prototype.compileNode=function(e){var t,n,i,r;return this.expression.front=this.front,i=this.expression.compile(e,F),g.test(i)&&!e.scope.check(i)?(r=this.negated?["===","||"]:["!==","&&"],t=r[0],n=r[1],i="typeof "+i+" "+t+' "undefined" '+n+" "+i+" "+t+" null"):i=i+" "+(this.negated?"==":"!=")+" null",[this.makeCode(C>=e.level?i:"("+i+")")]},t}(r),e.Parens=O=function(e){function t(e){this.body=e}return kt(t,e),t.prototype.children=["body"],t.prototype.unwrap=function(){return this.body},t.prototype.isComplex=function(){return this.body.isComplex()},t.prototype.compileNode=function(e){var t,n,i;return n=this.body.unwrap(),n instanceof z&&n.isAtomic()?(n.front=this.front,n.compileToFragments(e)):(i=n.compileToFragments(e,N),t=F>e.level&&(n instanceof I||n instanceof o||n instanceof f&&n.returns),t?i:this.wrapInBraces(i))},t}(r),e.For=f=function(e){function t(e,t){var n;this.source=t.source,this.guard=t.guard,this.step=t.step,this.name=t.name,this.index=t.index,this.body=s.wrap([e]),this.own=!!t.own,this.object=!!t.object,this.object&&(n=[this.index,this.name],this.name=n[0],this.index=n[1]),this.index instanceof z&&this.index.error("index cannot be a pattern matching expression"),this.range=this.source instanceof z&&this.source.base instanceof j&&!this.source.properties.length,this.pattern=this.name instanceof z,this.range&&this.index&&this.index.error("indexes do not apply to range loops"),this.range&&this.pattern&&this.name.error("cannot pattern match over range loops"),this.own&&!this.object&&this.name.error("cannot use own with for-in"),this.returns=!1}return kt(t,e),t.prototype.children=["body","source","guard","step"],t.prototype.compileNode=function(e){var t,n,r,o,a,c,h,l,u,p,d,f,m,v,y,k,w,T,C,F,N,S,D,A,I,_,$,j,B,V,P,U,G,H;return t=s.wrap([this.body]),D=t.expressions,T=D[D.length-1],(null!=T?T.jumps():void 0)instanceof M&&(this.returns=!1),B=this.range?this.source.base:this.source,j=e.scope,this.pattern||(F=this.name&&this.name.compile(e,E)),v=this.index&&this.index.compile(e,E),F&&!this.pattern&&j.find(F),v&&j.find(v),this.returns&&($=j.freeVariable("results")),y=this.object&&v||j.freeVariable("i",{single:!0}),k=this.range&&F||v||y,w=k!==y?k+" = ":"",this.step&&!this.range&&(A=this.cacheToCodeFragments(this.step.cache(e,E,ot)),V=A[0],U=A[1],P=U.match(R)),this.pattern&&(F=y),H="",d="",h="",f=this.tab+q,this.range?p=B.compileToFragments(lt(e,{index:y,name:F,step:this.step,isComplex:ot})):(G=this.source.compile(e,E),!F&&!this.own||g.test(G)||(h+=""+this.tab+(S=j.freeVariable("ref"))+" = "+G+";\n",G=S),F&&!this.pattern&&(N=F+" = "+G+"["+k+"]"),this.object||(V!==U&&(h+=""+this.tab+V+";\n"),this.step&&P&&(u=0>pt(P[0]))||(C=j.freeVariable("len")),a=""+w+y+" = 0, "+C+" = "+G+".length",c=""+w+y+" = "+G+".length - 1",r=y+" < "+C,o=y+" >= 0",this.step?(P?u&&(r=o,a=c):(r=U+" > 0 ? "+r+" : "+o,a="("+U+" > 0 ? ("+a+") : "+c+")"),m=y+" += "+U):m=""+(k!==y?"++"+y:y+"++"),p=[this.makeCode(a+"; "+r+"; "+w+m)])),this.returns&&(I=""+this.tab+$+" = [];\n",_="\n"+this.tab+"return "+$+";",t.makeReturn($)),this.guard&&(t.expressions.length>1?t.expressions.unshift(new b(new O(this.guard).invert(),new x("continue"))):this.guard&&(t=s.wrap([new b(this.guard,t)]))),this.pattern&&t.expressions.unshift(new i(this.name,new x(G+"["+k+"]"))),l=[].concat(this.makeCode(h),this.pluckDirectCall(e,t)),N&&(H="\n"+f+N+";"),this.object&&(p=[this.makeCode(k+" in "+G)],this.own&&(d="\n"+f+"if (!"+bt("hasProp",e)+".call("+G+", "+k+")) continue;")),n=t.compileToFragments(lt(e,{indent:f}),L),n&&n.length>0&&(n=[].concat(this.makeCode("\n"),n,this.makeCode("\n"))),[].concat(l,this.makeCode(""+(I||"")+this.tab+"for ("),p,this.makeCode(") {"+d+H),n,this.makeCode(this.tab+"}"+(_||"")))},t.prototype.pluckDirectCall=function(e,t){var n,r,s,a,h,l,u,p,d,f,m,g,v,y,b,k;for(r=[],d=t.expressions,h=l=0,u=d.length;u>l;h=++l)s=d[h],s=s.unwrapAll(),s instanceof o&&(k=null!=(f=s.variable)?f.unwrapAll():void 0,(k instanceof c||k instanceof z&&(null!=(m=k.base)?m.unwrapAll():void 0)instanceof c&&1===k.properties.length&&("call"===(g=null!=(v=k.properties[0].name)?v.value:void 0)||"apply"===g))&&(a=(null!=(y=k.base)?y.unwrapAll():void 0)||k,p=new x(e.scope.freeVariable("fn")),n=new z(p),k.base&&(b=[n,k],k.base=b[0],n=b[1]),t.expressions[h]=new o(n,s.args),r=r.concat(this.makeCode(this.tab),new i(p,a).compileToFragments(e,L),this.makeCode(";\n"))));return r},t}(J),e.Switch=H=function(e){function t(e,t,n){this.subject=e,this.cases=t,this.otherwise=n}return kt(t,e),t.prototype.children=["subject","cases","otherwise"],t.prototype.isStatement=Q,t.prototype.jumps=function(e){var t,n,i,r,s,o,a,c;for(null==e&&(e={block:!0}),o=this.cases,i=0,s=o.length;s>i;i++)if(a=o[i],n=a[0],t=a[1],r=t.jumps(e))return r;return null!=(c=this.otherwise)?c.jumps(e):void 0},t.prototype.makeReturn=function(e){var t,n,i,r,o;for(r=this.cases,t=0,n=r.length;n>t;t++)i=r[t],i[1].makeReturn(e);return e&&(this.otherwise||(this.otherwise=new s([new x("void 0")]))),null!=(o=this.otherwise)&&o.makeReturn(e),this},t.prototype.compileNode=function(e){var t,n,i,r,s,o,a,c,h,l,u,p,d,f,m,g;for(c=e.indent+q,h=e.indent=c+q,o=[].concat(this.makeCode(this.tab+"switch ("),this.subject?this.subject.compileToFragments(e,N):this.makeCode("false"),this.makeCode(") {\n")),f=this.cases,a=l=0,p=f.length;p>l;a=++l){for(m=f[a],r=m[0],t=m[1],g=rt([r]),u=0,d=g.length;d>u;u++)i=g[u],this.subject||(i=i.invert()),o=o.concat(this.makeCode(c+"case "),i.compileToFragments(e,N),this.makeCode(":\n"));if((n=t.compileToFragments(e,L)).length>0&&(o=o.concat(n,this.makeCode("\n"))),a===this.cases.length-1&&!this.otherwise)break;s=this.lastNonComment(t.expressions),s instanceof M||s instanceof x&&s.jumps()&&"debugger"!==s.value||o.push(i.makeCode(h+"break;\n"))}return this.otherwise&&this.otherwise.expressions.length&&o.push.apply(o,[this.makeCode(c+"default:\n")].concat(Ct.call(this.otherwise.compileToFragments(e,L)),[this.makeCode("\n")])),o.push(this.makeCode(this.tab+"}")),o},t}(r),e.If=b=function(e){function t(e,t,n){this.body=t,null==n&&(n={}),this.condition="unless"===n.type?e.invert():e,this.elseBody=null,this.isChain=!1,this.soak=n.soak}return kt(t,e),t.prototype.children=["condition","body","elseBody"],t.prototype.bodyNode=function(){var e;return null!=(e=this.body)?e.unwrap():void 0},t.prototype.elseBodyNode=function(){var e;return null!=(e=this.elseBody)?e.unwrap():void 0},t.prototype.addElse=function(e){return this.isChain?this.elseBodyNode().addElse(e):(this.isChain=e instanceof t,this.elseBody=this.ensureBlock(e),this.elseBody.updateLocationDataIfMissing(e.locationData)),this},t.prototype.isStatement=function(e){var t;return(null!=e?e.level:void 0)===L||this.bodyNode().isStatement(e)||(null!=(t=this.elseBodyNode())?t.isStatement(e):void 0)},t.prototype.jumps=function(e){var t;return this.body.jumps(e)||(null!=(t=this.elseBody)?t.jumps(e):void 0)},t.prototype.compileNode=function(e){return this.isStatement(e)?this.compileStatement(e):this.compileExpression(e)},t.prototype.makeReturn=function(e){return e&&(this.elseBody||(this.elseBody=new s([new x("void 0")]))),this.body&&(this.body=new s([this.body.makeReturn(e)])),this.elseBody&&(this.elseBody=new s([this.elseBody.makeReturn(e)])),this},t.prototype.ensureBlock=function(e){return e instanceof s?e:new s([e])},t.prototype.compileStatement=function(e){var n,i,r,s,o,a,c;return r=tt(e,"chainChild"),(o=tt(e,"isExistentialEquals"))?new t(this.condition.invert(),this.elseBodyNode(),{type:"if"}).compileToFragments(e):(c=e.indent+q,s=this.condition.compileToFragments(e,N),i=this.ensureBlock(this.body).compileToFragments(lt(e,{indent:c})),a=[].concat(this.makeCode("if ("),s,this.makeCode(") {\n"),i,this.makeCode("\n"+this.tab+"}")),r||a.unshift(this.makeCode(this.tab)),this.elseBody?(n=a.concat(this.makeCode(" else ")),this.isChain?(e.chainChild=!0,n=n.concat(this.elseBody.unwrap().compileToFragments(e,L))):n=n.concat(this.makeCode("{\n"),this.elseBody.compileToFragments(lt(e,{indent:c}),L),this.makeCode("\n"+this.tab+"}")),n):a)},t.prototype.compileExpression=function(e){var t,n,i,r;return i=this.condition.compileToFragments(e,C),n=this.bodyNode().compileToFragments(e,E),t=this.elseBodyNode()?this.elseBodyNode().compileToFragments(e,E):[this.makeCode("void 0")],r=i.concat(this.makeCode(" ? "),n,this.makeCode(" : "),t),e.level>=C?this.wrapInBraces(r):r},t.prototype.unfoldSoak=function(){return this.soak&&this},t}(r),K={extend:function(e){return"function(child, parent) { for (var key in parent) { if ("+bt("hasProp",e)+".call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }"},bind:function(){return"function(fn, me){ return function(){ return fn.apply(me, arguments); }; }"},indexOf:function(){return"[].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }"},modulo:function(){return"function(a, b) { return (+a % (b = +b) + b) % b; }"},hasProp:function(){return"{}.hasOwnProperty"},slice:function(){return"[].slice"}},L=1,N=2,E=3,C=4,F=5,T=6,q=" ",g=/^(?!\d)[$\w\x7f-\uffff]+$/,B=/^[+-]?\d+$/,m=/^[+-]?0x[\da-f]+/i,R=/^[+-]?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)$/i,y=/^['"]/,v=/^\//,bt=function(e,t){var n,i;return i=t.scope.root,e in i.utilities?i.utilities[e]:(n=i.freeVariable(e),i.assign(n,K[e](t)),i.utilities[e]=n)},ut=function(e,t){return e=e.replace(/\n/g,"$&"+t),e.replace(/\s+$/,"")},pt=function(e){return null==e?0:e.match(m)?parseInt(e,16):parseFloat(e)},at=function(e){return e instanceof x&&"arguments"===e.value&&!e.asKey},ct=function(e){return e instanceof x&&"this"===e.value&&!e.asKey||e instanceof c&&e.bound||e instanceof o&&e.isSuper},ot=function(e){return e.isComplex()||("function"==typeof e.isAssignable?e.isAssignable():void 0)},yt=function(e,t,n){var i;if(i=t[n].unfoldSoak(e))return t[n]=i.body,i.body=new z(t),i}}.call(this),t.exports}(),_dereq_["./sourcemap"]=function(){var e={},t={exports:e};return function(){var e,n;e=function(){function e(e){this.line=e,this.columns=[]}return e.prototype.add=function(e,t,n){var i,r;return r=t[0],i=t[1],null==n&&(n={}),this.columns[e]&&n.noReplace?void 0:this.columns[e]={line:this.line,column:e,sourceLine:r,sourceColumn:i}},e.prototype.sourceLocation=function(e){for(var t;!((t=this.columns[e])||0>=e);)e--;return t&&[t.sourceLine,t.sourceColumn]},e}(),n=function(){function t(){this.lines=[]}var n,i,r,s;return t.prototype.add=function(t,n,i){var r,s,o,a;return null==i&&(i={}),o=n[0],s=n[1],a=(r=this.lines)[o]||(r[o]=new e(o)),a.add(s,t,i)},t.prototype.sourceLocation=function(e){var t,n,i;for(n=e[0],t=e[1];!((i=this.lines[n])||0>=n);)n--;return i&&i.sourceLocation(t)},t.prototype.generate=function(e,t){var n,i,r,s,o,a,c,h,l,u,p,d,f,m,g,v;for(null==e&&(e={}),null==t&&(t=null),v=0,s=0,a=0,o=0,d=!1,n="",f=this.lines,u=i=0,c=f.length;c>i;u=++i)if(l=f[u])for(m=l.columns,r=0,h=m.length;h>r;r++)if(p=m[r]){for(;p.line>v;)s=0,d=!1,n+=";",v++;d&&(n+=",",d=!1),n+=this.encodeVlq(p.column-s),s=p.column,n+=this.encodeVlq(0),n+=this.encodeVlq(p.sourceLine-a),a=p.sourceLine,n+=this.encodeVlq(p.sourceColumn-o),o=p.sourceColumn,d=!0}return g={version:3,file:e.generatedFile||"",sourceRoot:e.sourceRoot||"",sources:e.sourceFiles||[""],names:[],mappings:n},e.inline&&(g.sourcesContent=[t]),JSON.stringify(g,null,2)},r=5,i=1<e?1:0,a=(Math.abs(e)<<1)+o;a||!t;)n=a&s,a>>=r,a&&(n|=i),t+=this.encodeBase64(n);return t},n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t.prototype.encodeBase64=function(e){return n[e]||function(){throw Error("Cannot Base64 encode value: "+e)}()},t}(),t.exports=n}.call(this),t.exports}(),_dereq_["./coffee-script"]=function(){var e={},t={exports:e};return function(){var t,n,i,r,s,o,a,c,h,l,u,p,d,f,m,g,v,y,b={}.hasOwnProperty,k=[].indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(t in this&&this[t]===e)return t;return-1};if(a=_dereq_("fs"),v=_dereq_("vm"),f=_dereq_("path"),t=_dereq_("./lexer").Lexer,d=_dereq_("./parser").parser,h=_dereq_("./helpers"),n=_dereq_("./sourcemap"),e.VERSION="1.9.3",e.FILE_EXTENSIONS=[".coffee",".litcoffee",".coffee.md"],e.helpers=h,y=function(e){return function(t,n){var i;null==n&&(n={});try{return e.call(this,t,n)
-}catch(r){if(i=r,"string"!=typeof t)throw i;throw h.updateSyntaxError(i,t,n.filename)}}},e.compile=r=y(function(e,t){var i,r,s,o,a,c,l,u,f,m,g,v,y,b,k;for(v=h.merge,o=h.extend,t=o({},t),t.sourceMap&&(g=new n),k=p.tokenize(e,t),t.referencedVars=function(){var e,t,n;for(n=[],e=0,t=k.length;t>e;e++)b=k[e],b.variable&&n.push(b[1]);return n}(),c=d.parse(k).compileToFragments(t),s=0,t.header&&(s+=1),t.shiftLine&&(s+=1),r=0,f="",u=0,m=c.length;m>u;u++)a=c[u],t.sourceMap&&(a.locationData&&!/^[;\s]*$/.test(a.code)&&g.add([a.locationData.first_line,a.locationData.first_column],[s,r],{noReplace:!0}),y=h.count(a.code,"\n"),s+=y,y?r=a.code.length-(a.code.lastIndexOf("\n")+1):r+=a.code.length),f+=a.code;return t.header&&(l="Generated by CoffeeScript "+this.VERSION,f="// "+l+"\n"+f),t.sourceMap?(i={js:f},i.sourceMap=g,i.v3SourceMap=g.generate(t,e),i):f}),e.tokens=y(function(e,t){return p.tokenize(e,t)}),e.nodes=y(function(e,t){return"string"==typeof e?d.parse(p.tokenize(e,t)):d.parse(e)}),e.run=function(e,t){var n,i,s,o;return null==t&&(t={}),s=_dereq_.main,s.filename=process.argv[1]=t.filename?a.realpathSync(t.filename):".",s.moduleCache&&(s.moduleCache={}),i=t.filename?f.dirname(a.realpathSync(t.filename)):a.realpathSync("."),s.paths=_dereq_("module")._nodeModulePaths(i),(!h.isCoffee(s.filename)||_dereq_.extensions)&&(n=r(e,t),e=null!=(o=n.js)?o:n),s._compile(e,s.filename)},e.eval=function(e,t){var n,i,s,o,a,c,h,l,u,p,d,m,g,y,k,w,T;if(null==t&&(t={}),e=e.trim()){if(o=null!=(m=v.Script.createContext)?m:v.createContext,c=null!=(g=v.isContext)?g:function(){return t.sandbox instanceof o().constructor},o){if(null!=t.sandbox){if(c(t.sandbox))w=t.sandbox;else{w=o(),y=t.sandbox;for(l in y)b.call(y,l)&&(T=y[l],w[l]=T)}w.global=w.root=w.GLOBAL=w}else w=global;if(w.__filename=t.filename||"eval",w.__dirname=f.dirname(w.__filename),w===global&&!w.module&&!w.require){for(n=_dereq_("module"),w.module=i=new n(t.modulename||"eval"),w.require=s=function(e){return n._load(e,i,!0)},i.filename=w.__filename,k=Object.getOwnPropertyNames(_dereq_),a=0,u=k.length;u>a;a++)d=k[a],"paths"!==d&&(s[d]=_dereq_[d]);s.paths=i.paths=n._nodeModulePaths(process.cwd()),s.resolve=function(e){return n._resolveFilename(e,i)}}}p={};for(l in t)b.call(t,l)&&(T=t[l],p[l]=T);return p.bare=!0,h=r(e,p),w===global?v.runInThisContext(h):v.runInContext(h,w)}},e.register=function(){return _dereq_("./register")},_dereq_.extensions)for(m=this.FILE_EXTENSIONS,l=0,u=m.length;u>l;l++)s=m[l],null==(i=_dereq_.extensions)[s]&&(i[s]=function(){throw Error("Use CoffeeScript.register() or require the coffee-script/register module to require "+s+" files.")});e._compileFile=function(e,t){var n,i,s,o;null==t&&(t=!1),s=a.readFileSync(e,"utf8"),o=65279===s.charCodeAt(0)?s.substring(1):s;try{n=r(o,{filename:e,sourceMap:t,literate:h.isLiterate(e)})}catch(c){throw i=c,h.updateSyntaxError(i,o,e)}return n},p=new t,d.lexer={lex:function(){var e,t;return t=d.tokens[this.pos++],t?(e=t[0],this.yytext=t[1],this.yylloc=t[2],d.errorToken=t.origin||t,this.yylineno=this.yylloc.first_line):e="",e},setInput:function(e){return d.tokens=e,this.pos=0},upcomingInput:function(){return""}},d.yy=_dereq_("./nodes"),d.yy.parseError=function(e,t){var n,i,r,s,o,a;return o=t.token,s=d.errorToken,a=d.tokens,i=s[0],r=s[1],n=s[2],r=function(){switch(!1){case s!==a[a.length-1]:return"end of input";case"INDENT"!==i&&"OUTDENT"!==i:return"indentation";case"IDENTIFIER"!==i&&"NUMBER"!==i&&"STRING"!==i&&"STRING_START"!==i&&"REGEX"!==i&&"REGEX_START"!==i:return i.replace(/_START$/,"").toLowerCase();default:return h.nameWhitespaceCharacter(r)}}(),h.throwSyntaxError("unexpected "+r,n)},o=function(e,t){var n,i,r,s,o,a,c,h,l,u,p,d;return s=void 0,r="",e.isNative()?r="native":(e.isEval()?(s=e.getScriptNameOrSourceURL(),s||(r=e.getEvalOrigin()+", ")):s=e.getFileName(),s||(s=""),h=e.getLineNumber(),i=e.getColumnNumber(),u=t(s,h,i),r=u?s+":"+u[0]+":"+u[1]:s+":"+h+":"+i),o=e.getFunctionName(),a=e.isConstructor(),c=!(e.isToplevel()||a),c?(l=e.getMethodName(),d=e.getTypeName(),o?(p=n="",d&&o.indexOf(d)&&(p=d+"."),l&&o.indexOf("."+l)!==o.length-l.length-1&&(n=" [as "+l+"]"),""+p+o+n+" ("+r+")"):d+"."+(l||"")+" ("+r+")"):a?"new "+(o||"")+" ("+r+")":o?o+" ("+r+")":r},g={},c=function(t){var n,i;if(g[t])return g[t];if(i=null!=f?f.extname(t):void 0,!(0>k.call(e.FILE_EXTENSIONS,i)))return n=e._compileFile(t,!0),g[t]=n.sourceMap},Error.prepareStackTrace=function(t,n){var i,r,s;return s=function(e,t,n){var i,r;return r=c(e),r&&(i=r.sourceLocation([t-1,n-1])),i?[i[0]+1,i[1]+1]:null},r=function(){var t,r,a;for(a=[],t=0,r=n.length;r>t&&(i=n[t],i.getFunction()!==e.run);t++)a.push(" at "+o(i,s));return a}(),""+t+"\n"+r.join("\n")+"\n"}}.call(this),t.exports}(),_dereq_["./browser"]=function(){var exports={},module={exports:exports};return function(){var CoffeeScript,compile,runScripts,indexOf=[].indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(t in this&&this[t]===e)return t;return-1};CoffeeScript=_dereq_("./coffee-script"),CoffeeScript.require=_dereq_,compile=CoffeeScript.compile,CoffeeScript.eval=function(code,options){return null==options&&(options={}),null==options.bare&&(options.bare=!0),eval(compile(code,options))},CoffeeScript.run=function(e,t){return null==t&&(t={}),t.bare=!0,t.shiftLine=!0,Function(compile(e,t))()},"undefined"!=typeof window&&null!==window&&("undefined"!=typeof btoa&&null!==btoa&&"undefined"!=typeof JSON&&null!==JSON&&"undefined"!=typeof unescape&&null!==unescape&&"undefined"!=typeof encodeURIComponent&&null!==encodeURIComponent&&(compile=function(e,t){var n,i,r;return null==t&&(t={}),t.sourceMap=!0,t.inline=!0,i=CoffeeScript.compile(e,t),n=i.js,r=i.v3SourceMap,n+"\n//# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(r)))+"\n//# sourceURL=coffeescript"}),CoffeeScript.load=function(e,t,n,i){var r;return null==n&&(n={}),null==i&&(i=!1),n.sourceFiles=[e],r=window.ActiveXObject?new window.ActiveXObject("Microsoft.XMLHTTP"):new window.XMLHttpRequest,r.open("GET",e,!0),"overrideMimeType"in r&&r.overrideMimeType("text/plain"),r.onreadystatechange=function(){var s,o;if(4===r.readyState){if(0!==(o=r.status)&&200!==o)throw Error("Could not load "+e);if(s=[r.responseText,n],i||CoffeeScript.run.apply(CoffeeScript,s),t)return t(s)}},r.send(null)},runScripts=function(){var e,t,n,i,r,s,o,a,c,h,l;for(l=window.document.getElementsByTagName("script"),t=["text/coffeescript","text/literate-coffeescript"],e=function(){var e,n,i,r;for(r=[],e=0,n=l.length;n>e;e++)c=l[e],i=c.type,indexOf.call(t,i)>=0&&r.push(c);return r}(),s=0,n=function(){var t;return t=e[s],t instanceof Array?(CoffeeScript.run.apply(CoffeeScript,t),s++,n()):void 0},i=function(i,r){var s,o;return s={literate:i.type===t[1]},o=i.src||i.getAttribute("data-src"),o?CoffeeScript.load(o,function(t){return e[r]=t,n()},s,!0):(s.sourceFiles=["embedded"],e[r]=[i.innerHTML,s])},r=o=0,a=e.length;a>o;r=++o)h=e[r],i(h,r);return n()},window.addEventListener?window.addEventListener("DOMContentLoaded",runScripts,!1):window.attachEvent("onload",runScripts))}.call(this),module.exports}(),_dereq_["./coffee-script"]}();"function"==typeof define&&define.amd?define(function(){return CoffeeScript}):root.CoffeeScript=CoffeeScript})(this);
-});
-
-ace.define("ace/mode/coffee_worker",["require","exports","module","ace/lib/oop","ace/worker/mirror","ace/mode/coffee/coffee"], function(require, exports, module) {
-"use strict";
-
-var oop = require("../lib/oop");
-var Mirror = require("../worker/mirror").Mirror;
-var coffee = require("../mode/coffee/coffee");
-
-window.addEventListener = function() {};
-
-
-var Worker = exports.Worker = function(sender) {
- Mirror.call(this, sender);
- this.setTimeout(250);
-};
-
-oop.inherits(Worker, Mirror);
-
-(function() {
-
- this.onUpdate = function() {
- var value = this.doc.getValue();
- var errors = [];
- try {
- coffee.compile(value);
- } catch(e) {
- var loc = e.location;
- if (loc) {
- errors.push({
- row: loc.first_line,
- column: loc.first_column,
- endRow: loc.last_line,
- endColumn: loc.last_column,
- text: e.message,
- type: "error"
- });
- }
- }
- this.sender.emit("annotate", errors);
- };
-
-}).call(Worker.prototype);
-
-});
-
-ace.define("ace/lib/es5-shim",["require","exports","module"], function(require, exports, module) {
-
-function Empty() {}
-
-if (!Function.prototype.bind) {
- Function.prototype.bind = function bind(that) { // .length is 1
- var target = this;
- if (typeof target != "function") {
- throw new TypeError("Function.prototype.bind called on incompatible " + target);
- }
- var args = slice.call(arguments, 1); // for normal call
- var bound = function () {
-
- if (this instanceof bound) {
-
- var result = target.apply(
- this,
- args.concat(slice.call(arguments))
- );
- if (Object(result) === result) {
- return result;
- }
- return this;
-
- } else {
- return target.apply(
- that,
- args.concat(slice.call(arguments))
- );
-
- }
-
- };
- if(target.prototype) {
- Empty.prototype = target.prototype;
- bound.prototype = new Empty();
- Empty.prototype = null;
- }
- return bound;
- };
-}
-var call = Function.prototype.call;
-var prototypeOfArray = Array.prototype;
-var prototypeOfObject = Object.prototype;
-var slice = prototypeOfArray.slice;
-var _toString = call.bind(prototypeOfObject.toString);
-var owns = call.bind(prototypeOfObject.hasOwnProperty);
-var defineGetter;
-var defineSetter;
-var lookupGetter;
-var lookupSetter;
-var supportsAccessors;
-if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) {
- defineGetter = call.bind(prototypeOfObject.__defineGetter__);
- defineSetter = call.bind(prototypeOfObject.__defineSetter__);
- lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
- lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
-}
-if ([1,2].splice(0).length != 2) {
- if(function() { // test IE < 9 to splice bug - see issue #138
- function makeArray(l) {
- var a = new Array(l+2);
- a[0] = a[1] = 0;
- return a;
- }
- var array = [], lengthBefore;
-
- array.splice.apply(array, makeArray(20));
- array.splice.apply(array, makeArray(26));
-
- lengthBefore = array.length; //46
- array.splice(5, 0, "XXX"); // add one element
-
- lengthBefore + 1 == array.length
-
- if (lengthBefore + 1 == array.length) {
- return true;// has right splice implementation without bugs
- }
- }()) {//IE 6/7
- var array_splice = Array.prototype.splice;
- Array.prototype.splice = function(start, deleteCount) {
- if (!arguments.length) {
- return [];
- } else {
- return array_splice.apply(this, [
- start === void 0 ? 0 : start,
- deleteCount === void 0 ? (this.length - start) : deleteCount
- ].concat(slice.call(arguments, 2)))
- }
- };
- } else {//IE8
- Array.prototype.splice = function(pos, removeCount){
- var length = this.length;
- if (pos > 0) {
- if (pos > length)
- pos = length;
- } else if (pos == void 0) {
- pos = 0;
- } else if (pos < 0) {
- pos = Math.max(length + pos, 0);
- }
-
- if (!(pos+removeCount < length))
- removeCount = length - pos;
-
- var removed = this.slice(pos, pos+removeCount);
- var insert = slice.call(arguments, 2);
- var add = insert.length;
- if (pos === length) {
- if (add) {
- this.push.apply(this, insert);
- }
- } else {
- var remove = Math.min(removeCount, length - pos);
- var tailOldPos = pos + remove;
- var tailNewPos = tailOldPos + add - remove;
- var tailCount = length - tailOldPos;
- var lengthAfterRemove = length - remove;
-
- if (tailNewPos < tailOldPos) { // case A
- for (var i = 0; i < tailCount; ++i) {
- this[tailNewPos+i] = this[tailOldPos+i];
- }
- } else if (tailNewPos > tailOldPos) { // case B
- for (i = tailCount; i--; ) {
- this[tailNewPos+i] = this[tailOldPos+i];
- }
- } // else, add == remove (nothing to do)
-
- if (add && pos === lengthAfterRemove) {
- this.length = lengthAfterRemove; // truncate array
- this.push.apply(this, insert);
- } else {
- this.length = lengthAfterRemove + add; // reserves space
- for (i = 0; i < add; ++i) {
- this[pos+i] = insert[i];
- }
- }
- }
- return removed;
- };
- }
-}
-if (!Array.isArray) {
- Array.isArray = function isArray(obj) {
- return _toString(obj) == "[object Array]";
- };
-}
-var boxedString = Object("a"),
- splitString = boxedString[0] != "a" || !(0 in boxedString);
-
-if (!Array.prototype.forEach) {
- Array.prototype.forEach = function forEach(fun /*, thisp*/) {
- var object = toObject(this),
- self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- object,
- thisp = arguments[1],
- i = -1,
- length = self.length >>> 0;
- if (_toString(fun) != "[object Function]") {
- throw new TypeError(); // TODO message
- }
-
- while (++i < length) {
- if (i in self) {
- fun.call(thisp, self[i], i, object);
- }
- }
- };
-}
-if (!Array.prototype.map) {
- Array.prototype.map = function map(fun /*, thisp*/) {
- var object = toObject(this),
- self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- object,
- length = self.length >>> 0,
- result = Array(length),
- thisp = arguments[1];
- if (_toString(fun) != "[object Function]") {
- throw new TypeError(fun + " is not a function");
- }
-
- for (var i = 0; i < length; i++) {
- if (i in self)
- result[i] = fun.call(thisp, self[i], i, object);
- }
- return result;
- };
-}
-if (!Array.prototype.filter) {
- Array.prototype.filter = function filter(fun /*, thisp */) {
- var object = toObject(this),
- self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- object,
- length = self.length >>> 0,
- result = [],
- value,
- thisp = arguments[1];
- if (_toString(fun) != "[object Function]") {
- throw new TypeError(fun + " is not a function");
- }
-
- for (var i = 0; i < length; i++) {
- if (i in self) {
- value = self[i];
- if (fun.call(thisp, value, i, object)) {
- result.push(value);
- }
- }
- }
- return result;
- };
-}
-if (!Array.prototype.every) {
- Array.prototype.every = function every(fun /*, thisp */) {
- var object = toObject(this),
- self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- object,
- length = self.length >>> 0,
- thisp = arguments[1];
- if (_toString(fun) != "[object Function]") {
- throw new TypeError(fun + " is not a function");
- }
-
- for (var i = 0; i < length; i++) {
- if (i in self && !fun.call(thisp, self[i], i, object)) {
- return false;
- }
- }
- return true;
- };
-}
-if (!Array.prototype.some) {
- Array.prototype.some = function some(fun /*, thisp */) {
- var object = toObject(this),
- self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- object,
- length = self.length >>> 0,
- thisp = arguments[1];
- if (_toString(fun) != "[object Function]") {
- throw new TypeError(fun + " is not a function");
- }
-
- for (var i = 0; i < length; i++) {
- if (i in self && fun.call(thisp, self[i], i, object)) {
- return true;
- }
- }
- return false;
- };
-}
-if (!Array.prototype.reduce) {
- Array.prototype.reduce = function reduce(fun /*, initial*/) {
- var object = toObject(this),
- self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- object,
- length = self.length >>> 0;
- if (_toString(fun) != "[object Function]") {
- throw new TypeError(fun + " is not a function");
- }
- if (!length && arguments.length == 1) {
- throw new TypeError("reduce of empty array with no initial value");
- }
-
- var i = 0;
- var result;
- if (arguments.length >= 2) {
- result = arguments[1];
- } else {
- do {
- if (i in self) {
- result = self[i++];
- break;
- }
- if (++i >= length) {
- throw new TypeError("reduce of empty array with no initial value");
- }
- } while (true);
- }
-
- for (; i < length; i++) {
- if (i in self) {
- result = fun.call(void 0, result, self[i], i, object);
- }
- }
-
- return result;
- };
-}
-if (!Array.prototype.reduceRight) {
- Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
- var object = toObject(this),
- self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- object,
- length = self.length >>> 0;
- if (_toString(fun) != "[object Function]") {
- throw new TypeError(fun + " is not a function");
- }
- if (!length && arguments.length == 1) {
- throw new TypeError("reduceRight of empty array with no initial value");
- }
-
- var result, i = length - 1;
- if (arguments.length >= 2) {
- result = arguments[1];
- } else {
- do {
- if (i in self) {
- result = self[i--];
- break;
- }
- if (--i < 0) {
- throw new TypeError("reduceRight of empty array with no initial value");
- }
- } while (true);
- }
-
- do {
- if (i in this) {
- result = fun.call(void 0, result, self[i], i, object);
- }
- } while (i--);
-
- return result;
- };
-}
-if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) {
- Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
- var self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- toObject(this),
- length = self.length >>> 0;
-
- if (!length) {
- return -1;
- }
-
- var i = 0;
- if (arguments.length > 1) {
- i = toInteger(arguments[1]);
- }
- i = i >= 0 ? i : Math.max(0, length + i);
- for (; i < length; i++) {
- if (i in self && self[i] === sought) {
- return i;
- }
- }
- return -1;
- };
-}
-if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) {
- Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
- var self = splitString && _toString(this) == "[object String]" ?
- this.split("") :
- toObject(this),
- length = self.length >>> 0;
-
- if (!length) {
- return -1;
- }
- var i = length - 1;
- if (arguments.length > 1) {
- i = Math.min(i, toInteger(arguments[1]));
- }
- i = i >= 0 ? i : length - Math.abs(i);
- for (; i >= 0; i--) {
- if (i in self && sought === self[i]) {
- return i;
- }
- }
- return -1;
- };
-}
-if (!Object.getPrototypeOf) {
- Object.getPrototypeOf = function getPrototypeOf(object) {
- return object.__proto__ || (
- object.constructor ?
- object.constructor.prototype :
- prototypeOfObject
- );
- };
-}
-if (!Object.getOwnPropertyDescriptor) {
- var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " +
- "non-object: ";
- Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
- if ((typeof object != "object" && typeof object != "function") || object === null)
- throw new TypeError(ERR_NON_OBJECT + object);
- if (!owns(object, property))
- return;
-
- var descriptor, getter, setter;
- descriptor = { enumerable: true, configurable: true };
- if (supportsAccessors) {
- var prototype = object.__proto__;
- object.__proto__ = prototypeOfObject;
-
- var getter = lookupGetter(object, property);
- var setter = lookupSetter(object, property);
- object.__proto__ = prototype;
-
- if (getter || setter) {
- if (getter) descriptor.get = getter;
- if (setter) descriptor.set = setter;
- return descriptor;
- }
- }
- descriptor.value = object[property];
- return descriptor;
- };
-}
-if (!Object.getOwnPropertyNames) {
- Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
- return Object.keys(object);
- };
-}
-if (!Object.create) {
- var createEmpty;
- if (Object.prototype.__proto__ === null) {
- createEmpty = function () {
- return { "__proto__": null };
- };
- } else {
- createEmpty = function () {
- var empty = {};
- for (var i in empty)
- empty[i] = null;
- empty.constructor =
- empty.hasOwnProperty =
- empty.propertyIsEnumerable =
- empty.isPrototypeOf =
- empty.toLocaleString =
- empty.toString =
- empty.valueOf =
- empty.__proto__ = null;
- return empty;
- }
- }
-
- Object.create = function create(prototype, properties) {
- var object;
- if (prototype === null) {
- object = createEmpty();
- } else {
- if (typeof prototype != "object")
- throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
- var Type = function () {};
- Type.prototype = prototype;
- object = new Type();
- object.__proto__ = prototype;
- }
- if (properties !== void 0)
- Object.defineProperties(object, properties);
- return object;
- };
-}
-
-function doesDefinePropertyWork(object) {
- try {
- Object.defineProperty(object, "sentinel", {});
- return "sentinel" in object;
- } catch (exception) {
- }
-}
-if (Object.defineProperty) {
- var definePropertyWorksOnObject = doesDefinePropertyWork({});
- var definePropertyWorksOnDom = typeof document == "undefined" ||
- doesDefinePropertyWork(document.createElement("div"));
- if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
- var definePropertyFallback = Object.defineProperty;
- }
-}
-
-if (!Object.defineProperty || definePropertyFallback) {
- var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
- var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
- var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
- "on this javascript engine";
-
- Object.defineProperty = function defineProperty(object, property, descriptor) {
- if ((typeof object != "object" && typeof object != "function") || object === null)
- throw new TypeError(ERR_NON_OBJECT_TARGET + object);
- if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null)
- throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
- if (definePropertyFallback) {
- try {
- return definePropertyFallback.call(Object, object, property, descriptor);
- } catch (exception) {
- }
- }
- if (owns(descriptor, "value")) {
-
- if (supportsAccessors && (lookupGetter(object, property) ||
- lookupSetter(object, property)))
- {
- var prototype = object.__proto__;
- object.__proto__ = prototypeOfObject;
- delete object[property];
- object[property] = descriptor.value;
- object.__proto__ = prototype;
- } else {
- object[property] = descriptor.value;
- }
- } else {
- if (!supportsAccessors)
- throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
- if (owns(descriptor, "get"))
- defineGetter(object, property, descriptor.get);
- if (owns(descriptor, "set"))
- defineSetter(object, property, descriptor.set);
- }
-
- return object;
- };
-}
-if (!Object.defineProperties) {
- Object.defineProperties = function defineProperties(object, properties) {
- for (var property in properties) {
- if (owns(properties, property))
- Object.defineProperty(object, property, properties[property]);
- }
- return object;
- };
-}
-if (!Object.seal) {
- Object.seal = function seal(object) {
- return object;
- };
-}
-if (!Object.freeze) {
- Object.freeze = function freeze(object) {
- return object;
- };
-}
-try {
- Object.freeze(function () {});
-} catch (exception) {
- Object.freeze = (function freeze(freezeObject) {
- return function freeze(object) {
- if (typeof object == "function") {
- return object;
- } else {
- return freezeObject(object);
- }
- };
- })(Object.freeze);
-}
-if (!Object.preventExtensions) {
- Object.preventExtensions = function preventExtensions(object) {
- return object;
- };
-}
-if (!Object.isSealed) {
- Object.isSealed = function isSealed(object) {
- return false;
- };
-}
-if (!Object.isFrozen) {
- Object.isFrozen = function isFrozen(object) {
- return false;
- };
-}
-if (!Object.isExtensible) {
- Object.isExtensible = function isExtensible(object) {
- if (Object(object) === object) {
- throw new TypeError(); // TODO message
- }
- var name = '';
- while (owns(object, name)) {
- name += '?';
- }
- object[name] = true;
- var returnValue = owns(object, name);
- delete object[name];
- return returnValue;
- };
-}
-if (!Object.keys) {
- var hasDontEnumBug = true,
- dontEnums = [
- "toString",
- "toLocaleString",
- "valueOf",
- "hasOwnProperty",
- "isPrototypeOf",
- "propertyIsEnumerable",
- "constructor"
- ],
- dontEnumsLength = dontEnums.length;
-
- for (var key in {"toString": null}) {
- hasDontEnumBug = false;
- }
-
- Object.keys = function keys(object) {
-
- if (
- (typeof object != "object" && typeof object != "function") ||
- object === null
- ) {
- throw new TypeError("Object.keys called on a non-object");
- }
-
- var keys = [];
- for (var name in object) {
- if (owns(object, name)) {
- keys.push(name);
- }
- }
-
- if (hasDontEnumBug) {
- for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
- var dontEnum = dontEnums[i];
- if (owns(object, dontEnum)) {
- keys.push(dontEnum);
- }
- }
- }
- return keys;
- };
-
-}
-if (!Date.now) {
- Date.now = function now() {
- return new Date().getTime();
- };
-}
-var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
- "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
- "\u2029\uFEFF";
-if (!String.prototype.trim || ws.trim()) {
- ws = "[" + ws + "]";
- var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
- trimEndRegexp = new RegExp(ws + ws + "*$");
- String.prototype.trim = function trim() {
- return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, "");
- };
-}
-
-function toInteger(n) {
- n = +n;
- if (n !== n) { // isNaN
- n = 0;
- } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) {
- n = (n > 0 || -1) * Math.floor(Math.abs(n));
- }
- return n;
-}
-
-function isPrimitive(input) {
- var type = typeof input;
- return (
- input === null ||
- type === "undefined" ||
- type === "boolean" ||
- type === "number" ||
- type === "string"
- );
-}
-
-function toPrimitive(input) {
- var val, valueOf, toString;
- if (isPrimitive(input)) {
- return input;
- }
- valueOf = input.valueOf;
- if (typeof valueOf === "function") {
- val = valueOf.call(input);
- if (isPrimitive(val)) {
- return val;
- }
- }
- toString = input.toString;
- if (typeof toString === "function") {
- val = toString.call(input);
- if (isPrimitive(val)) {
- return val;
- }
- }
- throw new TypeError();
-}
-var toObject = function (o) {
- if (o == null) { // this matches both null and undefined
- throw new TypeError("can't convert "+o+" to object");
- }
- return Object(o);
-};
-
-});
diff --git a/icestudio/lib/ace-builds/src-noconflict/worker-css.js b/icestudio/lib/ace-builds/src-noconflict/worker-css.js
deleted file mode 100644
index a21d3e504..000000000
--- a/icestudio/lib/ace-builds/src-noconflict/worker-css.js
+++ /dev/null
@@ -1,8762 +0,0 @@
-"no use strict";
-;(function(window) {
-if (typeof window.window != "undefined" && window.document)
- return;
-if (window.require && window.define)
- return;
-
-if (!window.console) {
- window.console = function() {
- var msgs = Array.prototype.slice.call(arguments, 0);
- postMessage({type: "log", data: msgs});
- };
- window.console.error =
- window.console.warn =
- window.console.log =
- window.console.trace = window.console;
-}
-window.window = window;
-window.ace = window;
-
-window.onerror = function(message, file, line, col, err) {
- postMessage({type: "error", data: {
- message: message,
- data: err.data,
- file: file,
- line: line,
- col: col,
- stack: err.stack
- }});
-};
-
-window.normalizeModule = function(parentId, moduleName) {
- // normalize plugin requires
- if (moduleName.indexOf("!") !== -1) {
- var chunks = moduleName.split("!");
- return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]);
- }
- // normalize relative requires
- if (moduleName.charAt(0) == ".") {
- var base = parentId.split("/").slice(0, -1).join("/");
- moduleName = (base ? base + "/" : "") + moduleName;
-
- while (moduleName.indexOf(".") !== -1 && previous != moduleName) {
- var previous = moduleName;
- moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
- }
- }
-
- return moduleName;
-};
-
-window.require = function require(parentId, id) {
- if (!id) {
- id = parentId;
- parentId = null;
- }
- if (!id.charAt)
- throw new Error("worker.js require() accepts only (parentId, id) as arguments");
-
- id = window.normalizeModule(parentId, id);
-
- var module = window.require.modules[id];
- if (module) {
- if (!module.initialized) {
- module.initialized = true;
- module.exports = module.factory().exports;
- }
- return module.exports;
- }
-
- if (!window.require.tlns)
- return console.log("unable to load " + id);
-
- var path = resolveModuleId(id, window.require.tlns);
- if (path.slice(-3) != ".js") path += ".js";
-
- window.require.id = id;
- window.require.modules[id] = {}; // prevent infinite loop on broken modules
- importScripts(path);
- return window.require(parentId, id);
-};
-function resolveModuleId(id, paths) {
- var testPath = id, tail = "";
- while (testPath) {
- var alias = paths[testPath];
- if (typeof alias == "string") {
- return alias + tail;
- } else if (alias) {
- return alias.location.replace(/\/*$/, "/") + (tail || alias.main || alias.name);
- } else if (alias === false) {
- return "";
- }
- var i = testPath.lastIndexOf("/");
- if (i === -1) break;
- tail = testPath.substr(i) + tail;
- testPath = testPath.slice(0, i);
- }
- return id;
-}
-window.require.modules = {};
-window.require.tlns = {};
-
-window.define = function(id, deps, factory) {
- if (arguments.length == 2) {
- factory = deps;
- if (typeof id != "string") {
- deps = id;
- id = window.require.id;
- }
- } else if (arguments.length == 1) {
- factory = id;
- deps = [];
- id = window.require.id;
- }
-
- if (typeof factory != "function") {
- window.require.modules[id] = {
- exports: factory,
- initialized: true
- };
- return;
- }
-
- if (!deps.length)
- // If there is no dependencies, we inject "require", "exports" and
- // "module" as dependencies, to provide CommonJS compatibility.
- deps = ["require", "exports", "module"];
-
- var req = function(childId) {
- return window.require(id, childId);
- };
-
- window.require.modules[id] = {
- exports: {},
- factory: function() {
- var module = this;
- var returnExports = factory.apply(this, deps.map(function(dep) {
- switch (dep) {
- // Because "require", "exports" and "module" aren't actual
- // dependencies, we must handle them seperately.
- case "require": return req;
- case "exports": return module.exports;
- case "module": return module;
- // But for all other dependencies, we can just go ahead and
- // require them.
- default: return req(dep);
- }
- }));
- if (returnExports)
- module.exports = returnExports;
- return module;
- }
- };
-};
-window.define.amd = {};
-require.tlns = {};
-window.initBaseUrls = function initBaseUrls(topLevelNamespaces) {
- for (var i in topLevelNamespaces)
- require.tlns[i] = topLevelNamespaces[i];
-};
-
-window.initSender = function initSender() {
-
- var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter;
- var oop = window.require("ace/lib/oop");
-
- var Sender = function() {};
-
- (function() {
-
- oop.implement(this, EventEmitter);
-
- this.callback = function(data, callbackId) {
- postMessage({
- type: "call",
- id: callbackId,
- data: data
- });
- };
-
- this.emit = function(name, data) {
- postMessage({
- type: "event",
- name: name,
- data: data
- });
- };
-
- }).call(Sender.prototype);
-
- return new Sender();
-};
-
-var main = window.main = null;
-var sender = window.sender = null;
-
-window.onmessage = function(e) {
- var msg = e.data;
- if (msg.event && sender) {
- sender._signal(msg.event, msg.data);
- }
- else if (msg.command) {
- if (main[msg.command])
- main[msg.command].apply(main, msg.args);
- else if (window[msg.command])
- window[msg.command].apply(window, msg.args);
- else
- throw new Error("Unknown command:" + msg.command);
- }
- else if (msg.init) {
- window.initBaseUrls(msg.tlns);
- require("ace/lib/es5-shim");
- sender = window.sender = window.initSender();
- var clazz = require(msg.module)[msg.classname];
- main = window.main = new clazz(sender);
- }
-};
-})(this);
-
-ace.define("ace/lib/oop",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-exports.inherits = function(ctor, superCtor) {
- ctor.super_ = superCtor;
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
-};
-
-exports.mixin = function(obj, mixin) {
- for (var key in mixin) {
- obj[key] = mixin[key];
- }
- return obj;
-};
-
-exports.implement = function(proto, mixin) {
- exports.mixin(proto, mixin);
-};
-
-});
-
-ace.define("ace/lib/lang",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-exports.last = function(a) {
- return a[a.length - 1];
-};
-
-exports.stringReverse = function(string) {
- return string.split("").reverse().join("");
-};
-
-exports.stringRepeat = function (string, count) {
- var result = '';
- while (count > 0) {
- if (count & 1)
- result += string;
-
- if (count >>= 1)
- string += string;
- }
- return result;
-};
-
-var trimBeginRegexp = /^\s\s*/;
-var trimEndRegexp = /\s\s*$/;
-
-exports.stringTrimLeft = function (string) {
- return string.replace(trimBeginRegexp, '');
-};
-
-exports.stringTrimRight = function (string) {
- return string.replace(trimEndRegexp, '');
-};
-
-exports.copyObject = function(obj) {
- var copy = {};
- for (var key in obj) {
- copy[key] = obj[key];
- }
- return copy;
-};
-
-exports.copyArray = function(array){
- var copy = [];
- for (var i=0, l=array.length; i [" + this.end.row + "/" + this.end.column + "]");
- };
-
- this.contains = function(row, column) {
- return this.compare(row, column) == 0;
- };
- this.compareRange = function(range) {
- var cmp,
- end = range.end,
- start = range.start;
-
- cmp = this.compare(end.row, end.column);
- if (cmp == 1) {
- cmp = this.compare(start.row, start.column);
- if (cmp == 1) {
- return 2;
- } else if (cmp == 0) {
- return 1;
- } else {
- return 0;
- }
- } else if (cmp == -1) {
- return -2;
- } else {
- cmp = this.compare(start.row, start.column);
- if (cmp == -1) {
- return -1;
- } else if (cmp == 1) {
- return 42;
- } else {
- return 0;
- }
- }
- };
- this.comparePoint = function(p) {
- return this.compare(p.row, p.column);
- };
- this.containsRange = function(range) {
- return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0;
- };
- this.intersects = function(range) {
- var cmp = this.compareRange(range);
- return (cmp == -1 || cmp == 0 || cmp == 1);
- };
- this.isEnd = function(row, column) {
- return this.end.row == row && this.end.column == column;
- };
- this.isStart = function(row, column) {
- return this.start.row == row && this.start.column == column;
- };
- this.setStart = function(row, column) {
- if (typeof row == "object") {
- this.start.column = row.column;
- this.start.row = row.row;
- } else {
- this.start.row = row;
- this.start.column = column;
- }
- };
- this.setEnd = function(row, column) {
- if (typeof row == "object") {
- this.end.column = row.column;
- this.end.row = row.row;
- } else {
- this.end.row = row;
- this.end.column = column;
- }
- };
- this.inside = function(row, column) {
- if (this.compare(row, column) == 0) {
- if (this.isEnd(row, column) || this.isStart(row, column)) {
- return false;
- } else {
- return true;
- }
- }
- return false;
- };
- this.insideStart = function(row, column) {
- if (this.compare(row, column) == 0) {
- if (this.isEnd(row, column)) {
- return false;
- } else {
- return true;
- }
- }
- return false;
- };
- this.insideEnd = function(row, column) {
- if (this.compare(row, column) == 0) {
- if (this.isStart(row, column)) {
- return false;
- } else {
- return true;
- }
- }
- return false;
- };
- this.compare = function(row, column) {
- if (!this.isMultiLine()) {
- if (row === this.start.row) {
- return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0);
- }
- }
-
- if (row < this.start.row)
- return -1;
-
- if (row > this.end.row)
- return 1;
-
- if (this.start.row === row)
- return column >= this.start.column ? 0 : -1;
-
- if (this.end.row === row)
- return column <= this.end.column ? 0 : 1;
-
- return 0;
- };
- this.compareStart = function(row, column) {
- if (this.start.row == row && this.start.column == column) {
- return -1;
- } else {
- return this.compare(row, column);
- }
- };
- this.compareEnd = function(row, column) {
- if (this.end.row == row && this.end.column == column) {
- return 1;
- } else {
- return this.compare(row, column);
- }
- };
- this.compareInside = function(row, column) {
- if (this.end.row == row && this.end.column == column) {
- return 1;
- } else if (this.start.row == row && this.start.column == column) {
- return -1;
- } else {
- return this.compare(row, column);
- }
- };
- this.clipRows = function(firstRow, lastRow) {
- if (this.end.row > lastRow)
- var end = {row: lastRow + 1, column: 0};
- else if (this.end.row < firstRow)
- var end = {row: firstRow, column: 0};
-
- if (this.start.row > lastRow)
- var start = {row: lastRow + 1, column: 0};
- else if (this.start.row < firstRow)
- var start = {row: firstRow, column: 0};
-
- return Range.fromPoints(start || this.start, end || this.end);
- };
- this.extend = function(row, column) {
- var cmp = this.compare(row, column);
-
- if (cmp == 0)
- return this;
- else if (cmp == -1)
- var start = {row: row, column: column};
- else
- var end = {row: row, column: column};
-
- return Range.fromPoints(start || this.start, end || this.end);
- };
-
- this.isEmpty = function() {
- return (this.start.row === this.end.row && this.start.column === this.end.column);
- };
- this.isMultiLine = function() {
- return (this.start.row !== this.end.row);
- };
- this.clone = function() {
- return Range.fromPoints(this.start, this.end);
- };
- this.collapseRows = function() {
- if (this.end.column == 0)
- return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0)
- else
- return new Range(this.start.row, 0, this.end.row, 0)
- };
- this.toScreenRange = function(session) {
- var screenPosStart = session.documentToScreenPosition(this.start);
- var screenPosEnd = session.documentToScreenPosition(this.end);
-
- return new Range(
- screenPosStart.row, screenPosStart.column,
- screenPosEnd.row, screenPosEnd.column
- );
- };
- this.moveBy = function(row, column) {
- this.start.row += row;
- this.start.column += column;
- this.end.row += row;
- this.end.column += column;
- };
-
-}).call(Range.prototype);
-Range.fromPoints = function(start, end) {
- return new Range(start.row, start.column, end.row, end.column);
-};
-Range.comparePoints = comparePoints;
-
-Range.comparePoints = function(p1, p2) {
- return p1.row - p2.row || p1.column - p2.column;
-};
-
-
-exports.Range = Range;
-});
-
-ace.define("ace/apply_delta",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-function throwDeltaError(delta, errorText){
- console.log("Invalid Delta:", delta);
- throw "Invalid Delta: " + errorText;
-}
-
-function positionInDocument(docLines, position) {
- return position.row >= 0 && position.row < docLines.length &&
- position.column >= 0 && position.column <= docLines[position.row].length;
-}
-
-function validateDelta(docLines, delta) {
- if (delta.action != "insert" && delta.action != "remove")
- throwDeltaError(delta, "delta.action must be 'insert' or 'remove'");
- if (!(delta.lines instanceof Array))
- throwDeltaError(delta, "delta.lines must be an Array");
- if (!delta.start || !delta.end)
- throwDeltaError(delta, "delta.start/end must be an present");
- var start = delta.start;
- if (!positionInDocument(docLines, delta.start))
- throwDeltaError(delta, "delta.start must be contained in document");
- var end = delta.end;
- if (delta.action == "remove" && !positionInDocument(docLines, end))
- throwDeltaError(delta, "delta.end must contained in document for 'remove' actions");
- var numRangeRows = end.row - start.row;
- var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0));
- if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars)
- throwDeltaError(delta, "delta.range must match delta lines");
-}
-
-exports.applyDelta = function(docLines, delta, doNotValidate) {
-
- var row = delta.start.row;
- var startColumn = delta.start.column;
- var line = docLines[row] || "";
- switch (delta.action) {
- case "insert":
- var lines = delta.lines;
- if (lines.length === 1) {
- docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn);
- } else {
- var args = [row, 1].concat(delta.lines);
- docLines.splice.apply(docLines, args);
- docLines[row] = line.substring(0, startColumn) + docLines[row];
- docLines[row + delta.lines.length - 1] += line.substring(startColumn);
- }
- break;
- case "remove":
- var endColumn = delta.end.column;
- var endRow = delta.end.row;
- if (row === endRow) {
- docLines[row] = line.substring(0, startColumn) + line.substring(endColumn);
- } else {
- docLines.splice(
- row, endRow - row + 1,
- line.substring(0, startColumn) + docLines[endRow].substring(endColumn)
- );
- }
- break;
- }
-}
-});
-
-ace.define("ace/lib/event_emitter",["require","exports","module"], function(require, exports, module) {
-"use strict";
-
-var EventEmitter = {};
-var stopPropagation = function() { this.propagationStopped = true; };
-var preventDefault = function() { this.defaultPrevented = true; };
-
-EventEmitter._emit =
-EventEmitter._dispatchEvent = function(eventName, e) {
- this._eventRegistry || (this._eventRegistry = {});
- this._defaultHandlers || (this._defaultHandlers = {});
-
- var listeners = this._eventRegistry[eventName] || [];
- var defaultHandler = this._defaultHandlers[eventName];
- if (!listeners.length && !defaultHandler)
- return;
-
- if (typeof e != "object" || !e)
- e = {};
-
- if (!e.type)
- e.type = eventName;
- if (!e.stopPropagation)
- e.stopPropagation = stopPropagation;
- if (!e.preventDefault)
- e.preventDefault = preventDefault;
-
- listeners = listeners.slice();
- for (var i=0; i this.row)
- return;
-
- var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight);
- this.setPosition(point.row, point.column, true);
- };
-
- function $pointsInOrder(point1, point2, equalPointsInOrder) {
- var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column;
- return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter);
- }
-
- function $getTransformedPoint(delta, point, moveIfEqual) {
- var deltaIsInsert = delta.action == "insert";
- var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row);
- var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column);
- var deltaStart = delta.start;
- var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range.
- if ($pointsInOrder(point, deltaStart, moveIfEqual)) {
- return {
- row: point.row,
- column: point.column
- };
- }
- if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) {
- return {
- row: point.row + deltaRowShift,
- column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0)
- };
- }
-
- return {
- row: deltaStart.row,
- column: deltaStart.column
- };
- }
- this.setPosition = function(row, column, noClip) {
- var pos;
- if (noClip) {
- pos = {
- row: row,
- column: column
- };
- } else {
- pos = this.$clipPositionToDocument(row, column);
- }
-
- if (this.row == pos.row && this.column == pos.column)
- return;
-
- var old = {
- row: this.row,
- column: this.column
- };
-
- this.row = pos.row;
- this.column = pos.column;
- this._signal("change", {
- old: old,
- value: pos
- });
- };
- this.detach = function() {
- this.document.removeEventListener("change", this.$onChange);
- };
- this.attach = function(doc) {
- this.document = doc || this.document;
- this.document.on("change", this.$onChange);
- };
- this.$clipPositionToDocument = function(row, column) {
- var pos = {};
-
- if (row >= this.document.getLength()) {
- pos.row = Math.max(0, this.document.getLength() - 1);
- pos.column = this.document.getLine(pos.row).length;
- }
- else if (row < 0) {
- pos.row = 0;
- pos.column = 0;
- }
- else {
- pos.row = row;
- pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column));
- }
-
- if (column < 0)
- pos.column = 0;
-
- return pos;
- };
-
-}).call(Anchor.prototype);
-
-});
-
-ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(require, exports, module) {
-"use strict";
-
-var oop = require("./lib/oop");
-var applyDelta = require("./apply_delta").applyDelta;
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-var Range = require("./range").Range;
-var Anchor = require("./anchor").Anchor;
-
-var Document = function(textOrLines) {
- this.$lines = [""];
- if (textOrLines.length === 0) {
- this.$lines = [""];
- } else if (Array.isArray(textOrLines)) {
- this.insertMergedLines({row: 0, column: 0}, textOrLines);
- } else {
- this.insert({row: 0, column:0}, textOrLines);
- }
-};
-
-(function() {
-
- oop.implement(this, EventEmitter);
- this.setValue = function(text) {
- var len = this.getLength() - 1;
- this.remove(new Range(0, 0, len, this.getLine(len).length));
- this.insert({row: 0, column: 0}, text);
- };
- this.getValue = function() {
- return this.getAllLines().join(this.getNewLineCharacter());
- };
- this.createAnchor = function(row, column) {
- return new Anchor(this, row, column);
- };
- if ("aaa".split(/a/).length === 0) {
- this.$split = function(text) {
- return text.replace(/\r\n|\r/g, "\n").split("\n");
- };
- } else {
- this.$split = function(text) {
- return text.split(/\r\n|\r|\n/);
- };
- }
-
-
- this.$detectNewLine = function(text) {
- var match = text.match(/^.*?(\r\n|\r|\n)/m);
- this.$autoNewLine = match ? match[1] : "\n";
- this._signal("changeNewLineMode");
- };
- this.getNewLineCharacter = function() {
- switch (this.$newLineMode) {
- case "windows":
- return "\r\n";
- case "unix":
- return "\n";
- default:
- return this.$autoNewLine || "\n";
- }
- };
-
- this.$autoNewLine = "";
- this.$newLineMode = "auto";
- this.setNewLineMode = function(newLineMode) {
- if (this.$newLineMode === newLineMode)
- return;
-
- this.$newLineMode = newLineMode;
- this._signal("changeNewLineMode");
- };
- this.getNewLineMode = function() {
- return this.$newLineMode;
- };
- this.isNewLine = function(text) {
- return (text == "\r\n" || text == "\r" || text == "\n");
- };
- this.getLine = function(row) {
- return this.$lines[row] || "";
- };
- this.getLines = function(firstRow, lastRow) {
- return this.$lines.slice(firstRow, lastRow + 1);
- };
- this.getAllLines = function() {
- return this.getLines(0, this.getLength());
- };
- this.getLength = function() {
- return this.$lines.length;
- };
- this.getTextRange = function(range) {
- return this.getLinesForRange(range).join(this.getNewLineCharacter());
- };
- this.getLinesForRange = function(range) {
- var lines;
- if (range.start.row === range.end.row) {
- lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)];
- } else {
- lines = this.getLines(range.start.row, range.end.row);
- lines[0] = (lines[0] || "").substring(range.start.column);
- var l = lines.length - 1;
- if (range.end.row - range.start.row == l)
- lines[l] = lines[l].substring(0, range.end.column);
- }
- return lines;
- };
- this.insertLines = function(row, lines) {
- console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead.");
- return this.insertFullLines(row, lines);
- };
- this.removeLines = function(firstRow, lastRow) {
- console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead.");
- return this.removeFullLines(firstRow, lastRow);
- };
- this.insertNewLine = function(position) {
- console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, [\'\', \'\']) instead.");
- return this.insertMergedLines(position, ["", ""]);
- };
- this.insert = function(position, text) {
- if (this.getLength() <= 1)
- this.$detectNewLine(text);
-
- return this.insertMergedLines(position, this.$split(text));
- };
- this.insertInLine = function(position, text) {
- var start = this.clippedPos(position.row, position.column);
- var end = this.pos(position.row, position.column + text.length);
-
- this.applyDelta({
- start: start,
- end: end,
- action: "insert",
- lines: [text]
- }, true);
-
- return this.clonePos(end);
- };
-
- this.clippedPos = function(row, column) {
- var length = this.getLength();
- if (row === undefined) {
- row = length;
- } else if (row < 0) {
- row = 0;
- } else if (row >= length) {
- row = length - 1;
- column = undefined;
- }
- var line = this.getLine(row);
- if (column == undefined)
- column = line.length;
- column = Math.min(Math.max(column, 0), line.length);
- return {row: row, column: column};
- };
-
- this.clonePos = function(pos) {
- return {row: pos.row, column: pos.column};
- };
-
- this.pos = function(row, column) {
- return {row: row, column: column};
- };
-
- this.$clipPosition = function(position) {
- var length = this.getLength();
- if (position.row >= length) {
- position.row = Math.max(0, length - 1);
- position.column = this.getLine(length - 1).length;
- } else {
- position.row = Math.max(0, position.row);
- position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length);
- }
- return position;
- };
- this.insertFullLines = function(row, lines) {
- row = Math.min(Math.max(row, 0), this.getLength());
- var column = 0;
- if (row < this.getLength()) {
- lines = lines.concat([""]);
- column = 0;
- } else {
- lines = [""].concat(lines);
- row--;
- column = this.$lines[row].length;
- }
- this.insertMergedLines({row: row, column: column}, lines);
- };
- this.insertMergedLines = function(position, lines) {
- var start = this.clippedPos(position.row, position.column);
- var end = {
- row: start.row + lines.length - 1,
- column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length
- };
-
- this.applyDelta({
- start: start,
- end: end,
- action: "insert",
- lines: lines
- });
-
- return this.clonePos(end);
- };
- this.remove = function(range) {
- var start = this.clippedPos(range.start.row, range.start.column);
- var end = this.clippedPos(range.end.row, range.end.column);
- this.applyDelta({
- start: start,
- end: end,
- action: "remove",
- lines: this.getLinesForRange({start: start, end: end})
- });
- return this.clonePos(start);
- };
- this.removeInLine = function(row, startColumn, endColumn) {
- var start = this.clippedPos(row, startColumn);
- var end = this.clippedPos(row, endColumn);
-
- this.applyDelta({
- start: start,
- end: end,
- action: "remove",
- lines: this.getLinesForRange({start: start, end: end})
- }, true);
-
- return this.clonePos(start);
- };
- this.removeFullLines = function(firstRow, lastRow) {
- firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1);
- lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1);
- var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0;
- var deleteLastNewLine = lastRow < this.getLength() - 1;
- var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow );
- var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 );
- var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow );
- var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length );
- var range = new Range(startRow, startCol, endRow, endCol);
- var deletedLines = this.$lines.slice(firstRow, lastRow + 1);
-
- this.applyDelta({
- start: range.start,
- end: range.end,
- action: "remove",
- lines: this.getLinesForRange(range)
- });
- return deletedLines;
- };
- this.removeNewLine = function(row) {
- if (row < this.getLength() - 1 && row >= 0) {
- this.applyDelta({
- start: this.pos(row, this.getLine(row).length),
- end: this.pos(row + 1, 0),
- action: "remove",
- lines: ["", ""]
- });
- }
- };
- this.replace = function(range, text) {
- if (!(range instanceof Range))
- range = Range.fromPoints(range.start, range.end);
- if (text.length === 0 && range.isEmpty())
- return range.start;
- if (text == this.getTextRange(range))
- return range.end;
-
- this.remove(range);
- var end;
- if (text) {
- end = this.insert(range.start, text);
- }
- else {
- end = range.start;
- }
-
- return end;
- };
- this.applyDeltas = function(deltas) {
- for (var i=0; i=0; i--) {
- this.revertDelta(deltas[i]);
- }
- };
- this.applyDelta = function(delta, doNotValidate) {
- var isInsert = delta.action == "insert";
- if (isInsert ? delta.lines.length <= 1 && !delta.lines[0]
- : !Range.comparePoints(delta.start, delta.end)) {
- return;
- }
-
- if (isInsert && delta.lines.length > 20000)
- this.$splitAndapplyLargeDelta(delta, 20000);
- applyDelta(this.$lines, delta, doNotValidate);
- this._signal("change", delta);
- };
-
- this.$splitAndapplyLargeDelta = function(delta, MAX) {
- var lines = delta.lines;
- var l = lines.length;
- var row = delta.start.row;
- var column = delta.start.column;
- var from = 0, to = 0;
- do {
- from = to;
- to += MAX - 1;
- var chunk = lines.slice(from, to);
- if (to > l) {
- delta.lines = chunk;
- delta.start.row = row + from;
- delta.start.column = column;
- break;
- }
- chunk.push("");
- this.applyDelta({
- start: this.pos(row + from, column),
- end: this.pos(row + to, column = 0),
- action: delta.action,
- lines: chunk
- }, true);
- } while(true);
- };
- this.revertDelta = function(delta) {
- this.applyDelta({
- start: this.clonePos(delta.start),
- end: this.clonePos(delta.end),
- action: (delta.action == "insert" ? "remove" : "insert"),
- lines: delta.lines.slice()
- });
- };
- this.indexToPosition = function(index, startRow) {
- var lines = this.$lines || this.getAllLines();
- var newlineLength = this.getNewLineCharacter().length;
- for (var i = startRow || 0, l = lines.length; i < l; i++) {
- index -= lines[i].length + newlineLength;
- if (index < 0)
- return {row: i, column: index + lines[i].length + newlineLength};
- }
- return {row: l-1, column: lines[l-1].length};
- };
- this.positionToIndex = function(pos, startRow) {
- var lines = this.$lines || this.getAllLines();
- var newlineLength = this.getNewLineCharacter().length;
- var index = 0;
- var row = Math.min(pos.row, lines.length);
- for (var i = startRow || 0; i < row; ++i)
- index += lines[i].length + newlineLength;
-
- return index + pos.column;
- };
-
-}).call(Document.prototype);
-
-exports.Document = Document;
-});
-
-ace.define("ace/worker/mirror",["require","exports","module","ace/range","ace/document","ace/lib/lang"], function(require, exports, module) {
-"use strict";
-
-var Range = require("../range").Range;
-var Document = require("../document").Document;
-var lang = require("../lib/lang");
-
-var Mirror = exports.Mirror = function(sender) {
- this.sender = sender;
- var doc = this.doc = new Document("");
-
- var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this));
-
- var _self = this;
- sender.on("change", function(e) {
- var data = e.data;
- if (data[0].start) {
- doc.applyDeltas(data);
- } else {
- for (var i = 0; i < data.length; i += 2) {
- if (Array.isArray(data[i+1])) {
- var d = {action: "insert", start: data[i], lines: data[i+1]};
- } else {
- var d = {action: "remove", start: data[i], end: data[i+1]};
- }
- doc.applyDelta(d, true);
- }
- }
- if (_self.$timeout)
- return deferredUpdate.schedule(_self.$timeout);
- _self.onUpdate();
- });
-};
-
-(function() {
-
- this.$timeout = 500;
-
- this.setTimeout = function(timeout) {
- this.$timeout = timeout;
- };
-
- this.setValue = function(value) {
- this.doc.setValue(value);
- this.deferredUpdate.schedule(this.$timeout);
- };
-
- this.getValue = function(callbackId) {
- this.sender.callback(this.doc.getValue(), callbackId);
- };
-
- this.onUpdate = function() {
- };
-
- this.isPending = function() {
- return this.deferredUpdate.isPending();
- };
-
-}).call(Mirror.prototype);
-
-});
-
-ace.define("ace/mode/css/csslint",["require","exports","module"], function(require, exports, module) {
-var parserlib = {};
-(function(){
-function EventTarget(){
- this._listeners = {};
-}
-
-EventTarget.prototype = {
- constructor: EventTarget,
- addListener: function(type, listener){
- if (!this._listeners[type]){
- this._listeners[type] = [];
- }
-
- this._listeners[type].push(listener);
- },
- fire: function(event){
- if (typeof event == "string"){
- event = { type: event };
- }
- if (typeof event.target != "undefined"){
- event.target = this;
- }
-
- if (typeof event.type == "undefined"){
- throw new Error("Event object missing 'type' property.");
- }
-
- if (this._listeners[event.type]){
- var listeners = this._listeners[event.type].concat();
- for (var i=0, len=listeners.length; i < len; i++){
- listeners[i].call(this, event);
- }
- }
- },
- removeListener: function(type, listener){
- if (this._listeners[type]){
- var listeners = this._listeners[type];
- for (var i=0, len=listeners.length; i < len; i++){
- if (listeners[i] === listener){
- listeners.splice(i, 1);
- break;
- }
- }
-
-
- }
- }
-};
-function StringReader(text){
- this._input = text.replace(/\n\r?/g, "\n");
- this._line = 1;
- this._col = 1;
- this._cursor = 0;
-}
-
-StringReader.prototype = {
- constructor: StringReader,
- getCol: function(){
- return this._col;
- },
- getLine: function(){
- return this._line ;
- },
- eof: function(){
- return (this._cursor == this._input.length);
- },
- peek: function(count){
- var c = null;
- count = (typeof count == "undefined" ? 1 : count);
- if (this._cursor < this._input.length){
- c = this._input.charAt(this._cursor + count - 1);
- }
-
- return c;
- },
- read: function(){
- var c = null;
- if (this._cursor < this._input.length){
- if (this._input.charAt(this._cursor) == "\n"){
- this._line++;
- this._col=1;
- } else {
- this._col++;
- }
- c = this._input.charAt(this._cursor++);
- }
-
- return c;
- },
- mark: function(){
- this._bookmark = {
- cursor: this._cursor,
- line: this._line,
- col: this._col
- };
- },
-
- reset: function(){
- if (this._bookmark){
- this._cursor = this._bookmark.cursor;
- this._line = this._bookmark.line;
- this._col = this._bookmark.col;
- delete this._bookmark;
- }
- },
- readTo: function(pattern){
-
- var buffer = "",
- c;
- while (buffer.length < pattern.length || buffer.lastIndexOf(pattern) != buffer.length - pattern.length){
- c = this.read();
- if (c){
- buffer += c;
- } else {
- throw new Error("Expected \"" + pattern + "\" at line " + this._line + ", col " + this._col + ".");
- }
- }
-
- return buffer;
-
- },
- readWhile: function(filter){
-
- var buffer = "",
- c = this.read();
-
- while(c !== null && filter(c)){
- buffer += c;
- c = this.read();
- }
-
- return buffer;
-
- },
- readMatch: function(matcher){
-
- var source = this._input.substring(this._cursor),
- value = null;
- if (typeof matcher == "string"){
- if (source.indexOf(matcher) === 0){
- value = this.readCount(matcher.length);
- }
- } else if (matcher instanceof RegExp){
- if (matcher.test(source)){
- value = this.readCount(RegExp.lastMatch.length);
- }
- }
-
- return value;
- },
- readCount: function(count){
- var buffer = "";
-
- while(count--){
- buffer += this.read();
- }
-
- return buffer;
- }
-
-};
-function SyntaxError(message, line, col){
- this.col = col;
- this.line = line;
- this.message = message;
-
-}
-SyntaxError.prototype = new Error();
-function SyntaxUnit(text, line, col, type){
- this.col = col;
- this.line = line;
- this.text = text;
- this.type = type;
-}
-SyntaxUnit.fromToken = function(token){
- return new SyntaxUnit(token.value, token.startLine, token.startCol);
-};
-
-SyntaxUnit.prototype = {
- constructor: SyntaxUnit,
- valueOf: function(){
- return this.text;
- },
- toString: function(){
- return this.text;
- }
-
-};
-function TokenStreamBase(input, tokenData){
- this._reader = input ? new StringReader(input.toString()) : null;
- this._token = null;
- this._tokenData = tokenData;
- this._lt = [];
- this._ltIndex = 0;
-
- this._ltIndexCache = [];
-}
-TokenStreamBase.createTokenData = function(tokens){
-
- var nameMap = [],
- typeMap = {},
- tokenData = tokens.concat([]),
- i = 0,
- len = tokenData.length+1;
-
- tokenData.UNKNOWN = -1;
- tokenData.unshift({name:"EOF"});
-
- for (; i < len; i++){
- nameMap.push(tokenData[i].name);
- tokenData[tokenData[i].name] = i;
- if (tokenData[i].text){
- typeMap[tokenData[i].text] = i;
- }
- }
-
- tokenData.name = function(tt){
- return nameMap[tt];
- };
-
- tokenData.type = function(c){
- return typeMap[c];
- };
-
- return tokenData;
-};
-
-TokenStreamBase.prototype = {
- constructor: TokenStreamBase,
- match: function(tokenTypes, channel){
- if (!(tokenTypes instanceof Array)){
- tokenTypes = [tokenTypes];
- }
-
- var tt = this.get(channel),
- i = 0,
- len = tokenTypes.length;
-
- while(i < len){
- if (tt == tokenTypes[i++]){
- return true;
- }
- }
- this.unget();
- return false;
- },
- mustMatch: function(tokenTypes, channel){
-
- var token;
- if (!(tokenTypes instanceof Array)){
- tokenTypes = [tokenTypes];
- }
-
- if (!this.match.apply(this, arguments)){
- token = this.LT(1);
- throw new SyntaxError("Expected " + this._tokenData[tokenTypes[0]].name +
- " at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
- }
- },
- advance: function(tokenTypes, channel){
-
- while(this.LA(0) !== 0 && !this.match(tokenTypes, channel)){
- this.get();
- }
-
- return this.LA(0);
- },
- get: function(channel){
-
- var tokenInfo = this._tokenData,
- reader = this._reader,
- value,
- i =0,
- len = tokenInfo.length,
- found = false,
- token,
- info;
- if (this._lt.length && this._ltIndex >= 0 && this._ltIndex < this._lt.length){
-
- i++;
- this._token = this._lt[this._ltIndex++];
- info = tokenInfo[this._token.type];
- while((info.channel !== undefined && channel !== info.channel) &&
- this._ltIndex < this._lt.length){
- this._token = this._lt[this._ltIndex++];
- info = tokenInfo[this._token.type];
- i++;
- }
- if ((info.channel === undefined || channel === info.channel) &&
- this._ltIndex <= this._lt.length){
- this._ltIndexCache.push(i);
- return this._token.type;
- }
- }
- token = this._getToken();
- if (token.type > -1 && !tokenInfo[token.type].hide){
- token.channel = tokenInfo[token.type].channel;
- this._token = token;
- this._lt.push(token);
- this._ltIndexCache.push(this._lt.length - this._ltIndex + i);
- if (this._lt.length > 5){
- this._lt.shift();
- }
- if (this._ltIndexCache.length > 5){
- this._ltIndexCache.shift();
- }
- this._ltIndex = this._lt.length;
- }
- info = tokenInfo[token.type];
- if (info &&
- (info.hide ||
- (info.channel !== undefined && channel !== info.channel))){
- return this.get(channel);
- } else {
- return token.type;
- }
- },
- LA: function(index){
- var total = index,
- tt;
- if (index > 0){
- if (index > 5){
- throw new Error("Too much lookahead.");
- }
- while(total){
- tt = this.get();
- total--;
- }
- while(total < index){
- this.unget();
- total++;
- }
- } else if (index < 0){
-
- if(this._lt[this._ltIndex+index]){
- tt = this._lt[this._ltIndex+index].type;
- } else {
- throw new Error("Too much lookbehind.");
- }
-
- } else {
- tt = this._token.type;
- }
-
- return tt;
-
- },
- LT: function(index){
- this.LA(index);
- return this._lt[this._ltIndex+index-1];
- },
- peek: function(){
- return this.LA(1);
- },
- token: function(){
- return this._token;
- },
- tokenName: function(tokenType){
- if (tokenType < 0 || tokenType > this._tokenData.length){
- return "UNKNOWN_TOKEN";
- } else {
- return this._tokenData[tokenType].name;
- }
- },
- tokenType: function(tokenName){
- return this._tokenData[tokenName] || -1;
- },
- unget: function(){
- if (this._ltIndexCache.length){
- this._ltIndex -= this._ltIndexCache.pop();//--;
- this._token = this._lt[this._ltIndex - 1];
- } else {
- throw new Error("Too much lookahead.");
- }
- }
-
-};
-
-
-parserlib.util = {
-StringReader: StringReader,
-SyntaxError : SyntaxError,
-SyntaxUnit : SyntaxUnit,
-EventTarget : EventTarget,
-TokenStreamBase : TokenStreamBase
-};
-})();
-(function(){
-var EventTarget = parserlib.util.EventTarget,
-TokenStreamBase = parserlib.util.TokenStreamBase,
-StringReader = parserlib.util.StringReader,
-SyntaxError = parserlib.util.SyntaxError,
-SyntaxUnit = parserlib.util.SyntaxUnit;
-
-var Colors = {
- aliceblue :"#f0f8ff",
- antiquewhite :"#faebd7",
- aqua :"#00ffff",
- aquamarine :"#7fffd4",
- azure :"#f0ffff",
- beige :"#f5f5dc",
- bisque :"#ffe4c4",
- black :"#000000",
- blanchedalmond :"#ffebcd",
- blue :"#0000ff",
- blueviolet :"#8a2be2",
- brown :"#a52a2a",
- burlywood :"#deb887",
- cadetblue :"#5f9ea0",
- chartreuse :"#7fff00",
- chocolate :"#d2691e",
- coral :"#ff7f50",
- cornflowerblue :"#6495ed",
- cornsilk :"#fff8dc",
- crimson :"#dc143c",
- cyan :"#00ffff",
- darkblue :"#00008b",
- darkcyan :"#008b8b",
- darkgoldenrod :"#b8860b",
- darkgray :"#a9a9a9",
- darkgrey :"#a9a9a9",
- darkgreen :"#006400",
- darkkhaki :"#bdb76b",
- darkmagenta :"#8b008b",
- darkolivegreen :"#556b2f",
- darkorange :"#ff8c00",
- darkorchid :"#9932cc",
- darkred :"#8b0000",
- darksalmon :"#e9967a",
- darkseagreen :"#8fbc8f",
- darkslateblue :"#483d8b",
- darkslategray :"#2f4f4f",
- darkslategrey :"#2f4f4f",
- darkturquoise :"#00ced1",
- darkviolet :"#9400d3",
- deeppink :"#ff1493",
- deepskyblue :"#00bfff",
- dimgray :"#696969",
- dimgrey :"#696969",
- dodgerblue :"#1e90ff",
- firebrick :"#b22222",
- floralwhite :"#fffaf0",
- forestgreen :"#228b22",
- fuchsia :"#ff00ff",
- gainsboro :"#dcdcdc",
- ghostwhite :"#f8f8ff",
- gold :"#ffd700",
- goldenrod :"#daa520",
- gray :"#808080",
- grey :"#808080",
- green :"#008000",
- greenyellow :"#adff2f",
- honeydew :"#f0fff0",
- hotpink :"#ff69b4",
- indianred :"#cd5c5c",
- indigo :"#4b0082",
- ivory :"#fffff0",
- khaki :"#f0e68c",
- lavender :"#e6e6fa",
- lavenderblush :"#fff0f5",
- lawngreen :"#7cfc00",
- lemonchiffon :"#fffacd",
- lightblue :"#add8e6",
- lightcoral :"#f08080",
- lightcyan :"#e0ffff",
- lightgoldenrodyellow :"#fafad2",
- lightgray :"#d3d3d3",
- lightgrey :"#d3d3d3",
- lightgreen :"#90ee90",
- lightpink :"#ffb6c1",
- lightsalmon :"#ffa07a",
- lightseagreen :"#20b2aa",
- lightskyblue :"#87cefa",
- lightslategray :"#778899",
- lightslategrey :"#778899",
- lightsteelblue :"#b0c4de",
- lightyellow :"#ffffe0",
- lime :"#00ff00",
- limegreen :"#32cd32",
- linen :"#faf0e6",
- magenta :"#ff00ff",
- maroon :"#800000",
- mediumaquamarine:"#66cdaa",
- mediumblue :"#0000cd",
- mediumorchid :"#ba55d3",
- mediumpurple :"#9370d8",
- mediumseagreen :"#3cb371",
- mediumslateblue :"#7b68ee",
- mediumspringgreen :"#00fa9a",
- mediumturquoise :"#48d1cc",
- mediumvioletred :"#c71585",
- midnightblue :"#191970",
- mintcream :"#f5fffa",
- mistyrose :"#ffe4e1",
- moccasin :"#ffe4b5",
- navajowhite :"#ffdead",
- navy :"#000080",
- oldlace :"#fdf5e6",
- olive :"#808000",
- olivedrab :"#6b8e23",
- orange :"#ffa500",
- orangered :"#ff4500",
- orchid :"#da70d6",
- palegoldenrod :"#eee8aa",
- palegreen :"#98fb98",
- paleturquoise :"#afeeee",
- palevioletred :"#d87093",
- papayawhip :"#ffefd5",
- peachpuff :"#ffdab9",
- peru :"#cd853f",
- pink :"#ffc0cb",
- plum :"#dda0dd",
- powderblue :"#b0e0e6",
- purple :"#800080",
- red :"#ff0000",
- rosybrown :"#bc8f8f",
- royalblue :"#4169e1",
- saddlebrown :"#8b4513",
- salmon :"#fa8072",
- sandybrown :"#f4a460",
- seagreen :"#2e8b57",
- seashell :"#fff5ee",
- sienna :"#a0522d",
- silver :"#c0c0c0",
- skyblue :"#87ceeb",
- slateblue :"#6a5acd",
- slategray :"#708090",
- slategrey :"#708090",
- snow :"#fffafa",
- springgreen :"#00ff7f",
- steelblue :"#4682b4",
- tan :"#d2b48c",
- teal :"#008080",
- thistle :"#d8bfd8",
- tomato :"#ff6347",
- turquoise :"#40e0d0",
- violet :"#ee82ee",
- wheat :"#f5deb3",
- white :"#ffffff",
- whitesmoke :"#f5f5f5",
- yellow :"#ffff00",
- yellowgreen :"#9acd32",
- activeBorder :"Active window border.",
- activecaption :"Active window caption.",
- appworkspace :"Background color of multiple document interface.",
- background :"Desktop background.",
- buttonface :"The face background color for 3-D elements that appear 3-D due to one layer of surrounding border.",
- buttonhighlight :"The color of the border facing the light source for 3-D elements that appear 3-D due to one layer of surrounding border.",
- buttonshadow :"The color of the border away from the light source for 3-D elements that appear 3-D due to one layer of surrounding border.",
- buttontext :"Text on push buttons.",
- captiontext :"Text in caption, size box, and scrollbar arrow box.",
- graytext :"Grayed (disabled) text. This color is set to #000 if the current display driver does not support a solid gray color.",
- greytext :"Greyed (disabled) text. This color is set to #000 if the current display driver does not support a solid grey color.",
- highlight :"Item(s) selected in a control.",
- highlighttext :"Text of item(s) selected in a control.",
- inactiveborder :"Inactive window border.",
- inactivecaption :"Inactive window caption.",
- inactivecaptiontext :"Color of text in an inactive caption.",
- infobackground :"Background color for tooltip controls.",
- infotext :"Text color for tooltip controls.",
- menu :"Menu background.",
- menutext :"Text in menus.",
- scrollbar :"Scroll bar gray area.",
- threeddarkshadow :"The color of the darker (generally outer) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",
- threedface :"The face background color for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",
- threedhighlight :"The color of the lighter (generally outer) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",
- threedlightshadow :"The color of the darker (generally inner) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",
- threedshadow :"The color of the lighter (generally inner) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",
- window :"Window background.",
- windowframe :"Window frame.",
- windowtext :"Text in windows."
-};
-function Combinator(text, line, col){
-
- SyntaxUnit.call(this, text, line, col, Parser.COMBINATOR_TYPE);
- this.type = "unknown";
- if (/^\s+$/.test(text)){
- this.type = "descendant";
- } else if (text == ">"){
- this.type = "child";
- } else if (text == "+"){
- this.type = "adjacent-sibling";
- } else if (text == "~"){
- this.type = "sibling";
- }
-
-}
-
-Combinator.prototype = new SyntaxUnit();
-Combinator.prototype.constructor = Combinator;
-function MediaFeature(name, value){
-
- SyntaxUnit.call(this, "(" + name + (value !== null ? ":" + value : "") + ")", name.startLine, name.startCol, Parser.MEDIA_FEATURE_TYPE);
- this.name = name;
- this.value = value;
-}
-
-MediaFeature.prototype = new SyntaxUnit();
-MediaFeature.prototype.constructor = MediaFeature;
-function MediaQuery(modifier, mediaType, features, line, col){
-
- SyntaxUnit.call(this, (modifier ? modifier + " ": "") + (mediaType ? mediaType : "") + (mediaType && features.length > 0 ? " and " : "") + features.join(" and "), line, col, Parser.MEDIA_QUERY_TYPE);
- this.modifier = modifier;
- this.mediaType = mediaType;
- this.features = features;
-
-}
-
-MediaQuery.prototype = new SyntaxUnit();
-MediaQuery.prototype.constructor = MediaQuery;
-function Parser(options){
- EventTarget.call(this);
-
-
- this.options = options || {};
-
- this._tokenStream = null;
-}
-Parser.DEFAULT_TYPE = 0;
-Parser.COMBINATOR_TYPE = 1;
-Parser.MEDIA_FEATURE_TYPE = 2;
-Parser.MEDIA_QUERY_TYPE = 3;
-Parser.PROPERTY_NAME_TYPE = 4;
-Parser.PROPERTY_VALUE_TYPE = 5;
-Parser.PROPERTY_VALUE_PART_TYPE = 6;
-Parser.SELECTOR_TYPE = 7;
-Parser.SELECTOR_PART_TYPE = 8;
-Parser.SELECTOR_SUB_PART_TYPE = 9;
-
-Parser.prototype = function(){
-
- var proto = new EventTarget(), //new prototype
- prop,
- additions = {
- constructor: Parser,
- DEFAULT_TYPE : 0,
- COMBINATOR_TYPE : 1,
- MEDIA_FEATURE_TYPE : 2,
- MEDIA_QUERY_TYPE : 3,
- PROPERTY_NAME_TYPE : 4,
- PROPERTY_VALUE_TYPE : 5,
- PROPERTY_VALUE_PART_TYPE : 6,
- SELECTOR_TYPE : 7,
- SELECTOR_PART_TYPE : 8,
- SELECTOR_SUB_PART_TYPE : 9,
-
- _stylesheet: function(){
-
- var tokenStream = this._tokenStream,
- charset = null,
- count,
- token,
- tt;
-
- this.fire("startstylesheet");
- this._charset();
-
- this._skipCruft();
- while (tokenStream.peek() == Tokens.IMPORT_SYM){
- this._import();
- this._skipCruft();
- }
- while (tokenStream.peek() == Tokens.NAMESPACE_SYM){
- this._namespace();
- this._skipCruft();
- }
- tt = tokenStream.peek();
- while(tt > Tokens.EOF){
-
- try {
-
- switch(tt){
- case Tokens.MEDIA_SYM:
- this._media();
- this._skipCruft();
- break;
- case Tokens.PAGE_SYM:
- this._page();
- this._skipCruft();
- break;
- case Tokens.FONT_FACE_SYM:
- this._font_face();
- this._skipCruft();
- break;
- case Tokens.KEYFRAMES_SYM:
- this._keyframes();
- this._skipCruft();
- break;
- case Tokens.VIEWPORT_SYM:
- this._viewport();
- this._skipCruft();
- break;
- case Tokens.UNKNOWN_SYM: //unknown @ rule
- tokenStream.get();
- if (!this.options.strict){
- this.fire({
- type: "error",
- error: null,
- message: "Unknown @ rule: " + tokenStream.LT(0).value + ".",
- line: tokenStream.LT(0).startLine,
- col: tokenStream.LT(0).startCol
- });
- count=0;
- while (tokenStream.advance([Tokens.LBRACE, Tokens.RBRACE]) == Tokens.LBRACE){
- count++; //keep track of nesting depth
- }
-
- while(count){
- tokenStream.advance([Tokens.RBRACE]);
- count--;
- }
-
- } else {
- throw new SyntaxError("Unknown @ rule.", tokenStream.LT(0).startLine, tokenStream.LT(0).startCol);
- }
- break;
- case Tokens.S:
- this._readWhitespace();
- break;
- default:
- if(!this._ruleset()){
- switch(tt){
- case Tokens.CHARSET_SYM:
- token = tokenStream.LT(1);
- this._charset(false);
- throw new SyntaxError("@charset not allowed here.", token.startLine, token.startCol);
- case Tokens.IMPORT_SYM:
- token = tokenStream.LT(1);
- this._import(false);
- throw new SyntaxError("@import not allowed here.", token.startLine, token.startCol);
- case Tokens.NAMESPACE_SYM:
- token = tokenStream.LT(1);
- this._namespace(false);
- throw new SyntaxError("@namespace not allowed here.", token.startLine, token.startCol);
- default:
- tokenStream.get(); //get the last token
- this._unexpectedToken(tokenStream.token());
- }
-
- }
- }
- } catch(ex) {
- if (ex instanceof SyntaxError && !this.options.strict){
- this.fire({
- type: "error",
- error: ex,
- message: ex.message,
- line: ex.line,
- col: ex.col
- });
- } else {
- throw ex;
- }
- }
-
- tt = tokenStream.peek();
- }
-
- if (tt != Tokens.EOF){
- this._unexpectedToken(tokenStream.token());
- }
-
- this.fire("endstylesheet");
- },
-
- _charset: function(emit){
- var tokenStream = this._tokenStream,
- charset,
- token,
- line,
- col;
-
- if (tokenStream.match(Tokens.CHARSET_SYM)){
- line = tokenStream.token().startLine;
- col = tokenStream.token().startCol;
-
- this._readWhitespace();
- tokenStream.mustMatch(Tokens.STRING);
-
- token = tokenStream.token();
- charset = token.value;
-
- this._readWhitespace();
- tokenStream.mustMatch(Tokens.SEMICOLON);
-
- if (emit !== false){
- this.fire({
- type: "charset",
- charset:charset,
- line: line,
- col: col
- });
- }
- }
- },
-
- _import: function(emit){
-
- var tokenStream = this._tokenStream,
- tt,
- uri,
- importToken,
- mediaList = [];
- tokenStream.mustMatch(Tokens.IMPORT_SYM);
- importToken = tokenStream.token();
- this._readWhitespace();
-
- tokenStream.mustMatch([Tokens.STRING, Tokens.URI]);
- uri = tokenStream.token().value.replace(/^(?:url\()?["']?([^"']+?)["']?\)?$/, "$1");
-
- this._readWhitespace();
-
- mediaList = this._media_query_list();
- tokenStream.mustMatch(Tokens.SEMICOLON);
- this._readWhitespace();
-
- if (emit !== false){
- this.fire({
- type: "import",
- uri: uri,
- media: mediaList,
- line: importToken.startLine,
- col: importToken.startCol
- });
- }
-
- },
-
- _namespace: function(emit){
-
- var tokenStream = this._tokenStream,
- line,
- col,
- prefix,
- uri;
- tokenStream.mustMatch(Tokens.NAMESPACE_SYM);
- line = tokenStream.token().startLine;
- col = tokenStream.token().startCol;
- this._readWhitespace();
- if (tokenStream.match(Tokens.IDENT)){
- prefix = tokenStream.token().value;
- this._readWhitespace();
- }
-
- tokenStream.mustMatch([Tokens.STRING, Tokens.URI]);
- uri = tokenStream.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/, "$1");
-
- this._readWhitespace();
- tokenStream.mustMatch(Tokens.SEMICOLON);
- this._readWhitespace();
-
- if (emit !== false){
- this.fire({
- type: "namespace",
- prefix: prefix,
- uri: uri,
- line: line,
- col: col
- });
- }
-
- },
-
- _media: function(){
- var tokenStream = this._tokenStream,
- line,
- col,
- mediaList;// = [];
- tokenStream.mustMatch(Tokens.MEDIA_SYM);
- line = tokenStream.token().startLine;
- col = tokenStream.token().startCol;
-
- this._readWhitespace();
-
- mediaList = this._media_query_list();
-
- tokenStream.mustMatch(Tokens.LBRACE);
- this._readWhitespace();
-
- this.fire({
- type: "startmedia",
- media: mediaList,
- line: line,
- col: col
- });
-
- while(true) {
- if (tokenStream.peek() == Tokens.PAGE_SYM){
- this._page();
- } else if (tokenStream.peek() == Tokens.FONT_FACE_SYM){
- this._font_face();
- } else if (tokenStream.peek() == Tokens.VIEWPORT_SYM){
- this._viewport();
- } else if (!this._ruleset()){
- break;
- }
- }
-
- tokenStream.mustMatch(Tokens.RBRACE);
- this._readWhitespace();
-
- this.fire({
- type: "endmedia",
- media: mediaList,
- line: line,
- col: col
- });
- },
- _media_query_list: function(){
- var tokenStream = this._tokenStream,
- mediaList = [];
-
-
- this._readWhitespace();
-
- if (tokenStream.peek() == Tokens.IDENT || tokenStream.peek() == Tokens.LPAREN){
- mediaList.push(this._media_query());
- }
-
- while(tokenStream.match(Tokens.COMMA)){
- this._readWhitespace();
- mediaList.push(this._media_query());
- }
-
- return mediaList;
- },
- _media_query: function(){
- var tokenStream = this._tokenStream,
- type = null,
- ident = null,
- token = null,
- expressions = [];
-
- if (tokenStream.match(Tokens.IDENT)){
- ident = tokenStream.token().value.toLowerCase();
- if (ident != "only" && ident != "not"){
- tokenStream.unget();
- ident = null;
- } else {
- token = tokenStream.token();
- }
- }
-
- this._readWhitespace();
-
- if (tokenStream.peek() == Tokens.IDENT){
- type = this._media_type();
- if (token === null){
- token = tokenStream.token();
- }
- } else if (tokenStream.peek() == Tokens.LPAREN){
- if (token === null){
- token = tokenStream.LT(1);
- }
- expressions.push(this._media_expression());
- }
-
- if (type === null && expressions.length === 0){
- return null;
- } else {
- this._readWhitespace();
- while (tokenStream.match(Tokens.IDENT)){
- if (tokenStream.token().value.toLowerCase() != "and"){
- this._unexpectedToken(tokenStream.token());
- }
-
- this._readWhitespace();
- expressions.push(this._media_expression());
- }
- }
-
- return new MediaQuery(ident, type, expressions, token.startLine, token.startCol);
- },
- _media_type: function(){
- return this._media_feature();
- },
- _media_expression: function(){
- var tokenStream = this._tokenStream,
- feature = null,
- token,
- expression = null;
-
- tokenStream.mustMatch(Tokens.LPAREN);
-
- feature = this._media_feature();
- this._readWhitespace();
-
- if (tokenStream.match(Tokens.COLON)){
- this._readWhitespace();
- token = tokenStream.LT(1);
- expression = this._expression();
- }
-
- tokenStream.mustMatch(Tokens.RPAREN);
- this._readWhitespace();
-
- return new MediaFeature(feature, (expression ? new SyntaxUnit(expression, token.startLine, token.startCol) : null));
- },
- _media_feature: function(){
- var tokenStream = this._tokenStream;
-
- tokenStream.mustMatch(Tokens.IDENT);
-
- return SyntaxUnit.fromToken(tokenStream.token());
- },
- _page: function(){
- var tokenStream = this._tokenStream,
- line,
- col,
- identifier = null,
- pseudoPage = null;
- tokenStream.mustMatch(Tokens.PAGE_SYM);
- line = tokenStream.token().startLine;
- col = tokenStream.token().startCol;
-
- this._readWhitespace();
-
- if (tokenStream.match(Tokens.IDENT)){
- identifier = tokenStream.token().value;
- if (identifier.toLowerCase() === "auto"){
- this._unexpectedToken(tokenStream.token());
- }
- }
- if (tokenStream.peek() == Tokens.COLON){
- pseudoPage = this._pseudo_page();
- }
-
- this._readWhitespace();
-
- this.fire({
- type: "startpage",
- id: identifier,
- pseudo: pseudoPage,
- line: line,
- col: col
- });
-
- this._readDeclarations(true, true);
-
- this.fire({
- type: "endpage",
- id: identifier,
- pseudo: pseudoPage,
- line: line,
- col: col
- });
-
- },
- _margin: function(){
- var tokenStream = this._tokenStream,
- line,
- col,
- marginSym = this._margin_sym();
-
- if (marginSym){
- line = tokenStream.token().startLine;
- col = tokenStream.token().startCol;
-
- this.fire({
- type: "startpagemargin",
- margin: marginSym,
- line: line,
- col: col
- });
-
- this._readDeclarations(true);
-
- this.fire({
- type: "endpagemargin",
- margin: marginSym,
- line: line,
- col: col
- });
- return true;
- } else {
- return false;
- }
- },
- _margin_sym: function(){
-
- var tokenStream = this._tokenStream;
-
- if(tokenStream.match([Tokens.TOPLEFTCORNER_SYM, Tokens.TOPLEFT_SYM,
- Tokens.TOPCENTER_SYM, Tokens.TOPRIGHT_SYM, Tokens.TOPRIGHTCORNER_SYM,
- Tokens.BOTTOMLEFTCORNER_SYM, Tokens.BOTTOMLEFT_SYM,
- Tokens.BOTTOMCENTER_SYM, Tokens.BOTTOMRIGHT_SYM,
- Tokens.BOTTOMRIGHTCORNER_SYM, Tokens.LEFTTOP_SYM,
- Tokens.LEFTMIDDLE_SYM, Tokens.LEFTBOTTOM_SYM, Tokens.RIGHTTOP_SYM,
- Tokens.RIGHTMIDDLE_SYM, Tokens.RIGHTBOTTOM_SYM]))
- {
- return SyntaxUnit.fromToken(tokenStream.token());
- } else {
- return null;
- }
-
- },
-
- _pseudo_page: function(){
-
- var tokenStream = this._tokenStream;
-
- tokenStream.mustMatch(Tokens.COLON);
- tokenStream.mustMatch(Tokens.IDENT);
-
- return tokenStream.token().value;
- },
-
- _font_face: function(){
- var tokenStream = this._tokenStream,
- line,
- col;
- tokenStream.mustMatch(Tokens.FONT_FACE_SYM);
- line = tokenStream.token().startLine;
- col = tokenStream.token().startCol;
-
- this._readWhitespace();
-
- this.fire({
- type: "startfontface",
- line: line,
- col: col
- });
-
- this._readDeclarations(true);
-
- this.fire({
- type: "endfontface",
- line: line,
- col: col
- });
- },
-
- _viewport: function(){
- var tokenStream = this._tokenStream,
- line,
- col;
-
- tokenStream.mustMatch(Tokens.VIEWPORT_SYM);
- line = tokenStream.token().startLine;
- col = tokenStream.token().startCol;
-
- this._readWhitespace();
-
- this.fire({
- type: "startviewport",
- line: line,
- col: col
- });
-
- this._readDeclarations(true);
-
- this.fire({
- type: "endviewport",
- line: line,
- col: col
- });
-
- },
-
- _operator: function(inFunction){
-
- var tokenStream = this._tokenStream,
- token = null;
-
- if (tokenStream.match([Tokens.SLASH, Tokens.COMMA]) ||
- (inFunction && tokenStream.match([Tokens.PLUS, Tokens.STAR, Tokens.MINUS]))){
- token = tokenStream.token();
- this._readWhitespace();
- }
- return token ? PropertyValuePart.fromToken(token) : null;
-
- },
-
- _combinator: function(){
-
- var tokenStream = this._tokenStream,
- value = null,
- token;
-
- if(tokenStream.match([Tokens.PLUS, Tokens.GREATER, Tokens.TILDE])){
- token = tokenStream.token();
- value = new Combinator(token.value, token.startLine, token.startCol);
- this._readWhitespace();
- }
-
- return value;
- },
-
- _unary_operator: function(){
-
- var tokenStream = this._tokenStream;
-
- if (tokenStream.match([Tokens.MINUS, Tokens.PLUS])){
- return tokenStream.token().value;
- } else {
- return null;
- }
- },
-
- _property: function(){
-
- var tokenStream = this._tokenStream,
- value = null,
- hack = null,
- tokenValue,
- token,
- line,
- col;
- if (tokenStream.peek() == Tokens.STAR && this.options.starHack){
- tokenStream.get();
- token = tokenStream.token();
- hack = token.value;
- line = token.startLine;
- col = token.startCol;
- }
-
- if(tokenStream.match(Tokens.IDENT)){
- token = tokenStream.token();
- tokenValue = token.value;
- if (tokenValue.charAt(0) == "_" && this.options.underscoreHack){
- hack = "_";
- tokenValue = tokenValue.substring(1);
- }
-
- value = new PropertyName(tokenValue, hack, (line||token.startLine), (col||token.startCol));
- this._readWhitespace();
- }
-
- return value;
- },
- _ruleset: function(){
-
- var tokenStream = this._tokenStream,
- tt,
- selectors;
- try {
- selectors = this._selectors_group();
- } catch (ex){
- if (ex instanceof SyntaxError && !this.options.strict){
- this.fire({
- type: "error",
- error: ex,
- message: ex.message,
- line: ex.line,
- col: ex.col
- });
- tt = tokenStream.advance([Tokens.RBRACE]);
- if (tt == Tokens.RBRACE){
- } else {
- throw ex;
- }
-
- } else {
- throw ex;
- }
- return true;
- }
- if (selectors){
-
- this.fire({
- type: "startrule",
- selectors: selectors,
- line: selectors[0].line,
- col: selectors[0].col
- });
-
- this._readDeclarations(true);
-
- this.fire({
- type: "endrule",
- selectors: selectors,
- line: selectors[0].line,
- col: selectors[0].col
- });
-
- }
-
- return selectors;
-
- },
- _selectors_group: function(){
- var tokenStream = this._tokenStream,
- selectors = [],
- selector;
-
- selector = this._selector();
- if (selector !== null){
-
- selectors.push(selector);
- while(tokenStream.match(Tokens.COMMA)){
- this._readWhitespace();
- selector = this._selector();
- if (selector !== null){
- selectors.push(selector);
- } else {
- this._unexpectedToken(tokenStream.LT(1));
- }
- }
- }
-
- return selectors.length ? selectors : null;
- },
- _selector: function(){
-
- var tokenStream = this._tokenStream,
- selector = [],
- nextSelector = null,
- combinator = null,
- ws = null;
- nextSelector = this._simple_selector_sequence();
- if (nextSelector === null){
- return null;
- }
-
- selector.push(nextSelector);
-
- do {
- combinator = this._combinator();
-
- if (combinator !== null){
- selector.push(combinator);
- nextSelector = this._simple_selector_sequence();
- if (nextSelector === null){
- this._unexpectedToken(tokenStream.LT(1));
- } else {
- selector.push(nextSelector);
- }
- } else {
- if (this._readWhitespace()){
- ws = new Combinator(tokenStream.token().value, tokenStream.token().startLine, tokenStream.token().startCol);
- combinator = this._combinator();
- nextSelector = this._simple_selector_sequence();
- if (nextSelector === null){
- if (combinator !== null){
- this._unexpectedToken(tokenStream.LT(1));
- }
- } else {
-
- if (combinator !== null){
- selector.push(combinator);
- } else {
- selector.push(ws);
- }
-
- selector.push(nextSelector);
- }
- } else {
- break;
- }
-
- }
- } while(true);
-
- return new Selector(selector, selector[0].line, selector[0].col);
- },
- _simple_selector_sequence: function(){
-
- var tokenStream = this._tokenStream,
- elementName = null,
- modifiers = [],
- selectorText= "",
- components = [
- function(){
- return tokenStream.match(Tokens.HASH) ?
- new SelectorSubPart(tokenStream.token().value, "id", tokenStream.token().startLine, tokenStream.token().startCol) :
- null;
- },
- this._class,
- this._attrib,
- this._pseudo,
- this._negation
- ],
- i = 0,
- len = components.length,
- component = null,
- found = false,
- line,
- col;
- line = tokenStream.LT(1).startLine;
- col = tokenStream.LT(1).startCol;
-
- elementName = this._type_selector();
- if (!elementName){
- elementName = this._universal();
- }
-
- if (elementName !== null){
- selectorText += elementName;
- }
-
- while(true){
- if (tokenStream.peek() === Tokens.S){
- break;
- }
- while(i < len && component === null){
- component = components[i++].call(this);
- }
-
- if (component === null){
- if (selectorText === ""){
- return null;
- } else {
- break;
- }
- } else {
- i = 0;
- modifiers.push(component);
- selectorText += component.toString();
- component = null;
- }
- }
-
-
- return selectorText !== "" ?
- new SelectorPart(elementName, modifiers, selectorText, line, col) :
- null;
- },
- _type_selector: function(){
-
- var tokenStream = this._tokenStream,
- ns = this._namespace_prefix(),
- elementName = this._element_name();
-
- if (!elementName){
- if (ns){
- tokenStream.unget();
- if (ns.length > 1){
- tokenStream.unget();
- }
- }
-
- return null;
- } else {
- if (ns){
- elementName.text = ns + elementName.text;
- elementName.col -= ns.length;
- }
- return elementName;
- }
- },
- _class: function(){
-
- var tokenStream = this._tokenStream,
- token;
-
- if (tokenStream.match(Tokens.DOT)){
- tokenStream.mustMatch(Tokens.IDENT);
- token = tokenStream.token();
- return new SelectorSubPart("." + token.value, "class", token.startLine, token.startCol - 1);
- } else {
- return null;
- }
-
- },
- _element_name: function(){
-
- var tokenStream = this._tokenStream,
- token;
-
- if (tokenStream.match(Tokens.IDENT)){
- token = tokenStream.token();
- return new SelectorSubPart(token.value, "elementName", token.startLine, token.startCol);
-
- } else {
- return null;
- }
- },
- _namespace_prefix: function(){
- var tokenStream = this._tokenStream,
- value = "";
- if (tokenStream.LA(1) === Tokens.PIPE || tokenStream.LA(2) === Tokens.PIPE){
-
- if(tokenStream.match([Tokens.IDENT, Tokens.STAR])){
- value += tokenStream.token().value;
- }
-
- tokenStream.mustMatch(Tokens.PIPE);
- value += "|";
-
- }
-
- return value.length ? value : null;
- },
- _universal: function(){
- var tokenStream = this._tokenStream,
- value = "",
- ns;
-
- ns = this._namespace_prefix();
- if(ns){
- value += ns;
- }
-
- if(tokenStream.match(Tokens.STAR)){
- value += "*";
- }
-
- return value.length ? value : null;
-
- },
- _attrib: function(){
-
- var tokenStream = this._tokenStream,
- value = null,
- ns,
- token;
-
- if (tokenStream.match(Tokens.LBRACKET)){
- token = tokenStream.token();
- value = token.value;
- value += this._readWhitespace();
-
- ns = this._namespace_prefix();
-
- if (ns){
- value += ns;
- }
-
- tokenStream.mustMatch(Tokens.IDENT);
- value += tokenStream.token().value;
- value += this._readWhitespace();
-
- if(tokenStream.match([Tokens.PREFIXMATCH, Tokens.SUFFIXMATCH, Tokens.SUBSTRINGMATCH,
- Tokens.EQUALS, Tokens.INCLUDES, Tokens.DASHMATCH])){
-
- value += tokenStream.token().value;
- value += this._readWhitespace();
-
- tokenStream.mustMatch([Tokens.IDENT, Tokens.STRING]);
- value += tokenStream.token().value;
- value += this._readWhitespace();
- }
-
- tokenStream.mustMatch(Tokens.RBRACKET);
-
- return new SelectorSubPart(value + "]", "attribute", token.startLine, token.startCol);
- } else {
- return null;
- }
- },
- _pseudo: function(){
-
- var tokenStream = this._tokenStream,
- pseudo = null,
- colons = ":",
- line,
- col;
-
- if (tokenStream.match(Tokens.COLON)){
-
- if (tokenStream.match(Tokens.COLON)){
- colons += ":";
- }
-
- if (tokenStream.match(Tokens.IDENT)){
- pseudo = tokenStream.token().value;
- line = tokenStream.token().startLine;
- col = tokenStream.token().startCol - colons.length;
- } else if (tokenStream.peek() == Tokens.FUNCTION){
- line = tokenStream.LT(1).startLine;
- col = tokenStream.LT(1).startCol - colons.length;
- pseudo = this._functional_pseudo();
- }
-
- if (pseudo){
- pseudo = new SelectorSubPart(colons + pseudo, "pseudo", line, col);
- }
- }
-
- return pseudo;
- },
- _functional_pseudo: function(){
-
- var tokenStream = this._tokenStream,
- value = null;
-
- if(tokenStream.match(Tokens.FUNCTION)){
- value = tokenStream.token().value;
- value += this._readWhitespace();
- value += this._expression();
- tokenStream.mustMatch(Tokens.RPAREN);
- value += ")";
- }
-
- return value;
- },
- _expression: function(){
-
- var tokenStream = this._tokenStream,
- value = "";
-
- while(tokenStream.match([Tokens.PLUS, Tokens.MINUS, Tokens.DIMENSION,
- Tokens.NUMBER, Tokens.STRING, Tokens.IDENT, Tokens.LENGTH,
- Tokens.FREQ, Tokens.ANGLE, Tokens.TIME,
- Tokens.RESOLUTION, Tokens.SLASH])){
-
- value += tokenStream.token().value;
- value += this._readWhitespace();
- }
-
- return value.length ? value : null;
-
- },
- _negation: function(){
-
- var tokenStream = this._tokenStream,
- line,
- col,
- value = "",
- arg,
- subpart = null;
-
- if (tokenStream.match(Tokens.NOT)){
- value = tokenStream.token().value;
- line = tokenStream.token().startLine;
- col = tokenStream.token().startCol;
- value += this._readWhitespace();
- arg = this._negation_arg();
- value += arg;
- value += this._readWhitespace();
- tokenStream.match(Tokens.RPAREN);
- value += tokenStream.token().value;
-
- subpart = new SelectorSubPart(value, "not", line, col);
- subpart.args.push(arg);
- }
-
- return subpart;
- },
- _negation_arg: function(){
-
- var tokenStream = this._tokenStream,
- args = [
- this._type_selector,
- this._universal,
- function(){
- return tokenStream.match(Tokens.HASH) ?
- new SelectorSubPart(tokenStream.token().value, "id", tokenStream.token().startLine, tokenStream.token().startCol) :
- null;
- },
- this._class,
- this._attrib,
- this._pseudo
- ],
- arg = null,
- i = 0,
- len = args.length,
- elementName,
- line,
- col,
- part;
-
- line = tokenStream.LT(1).startLine;
- col = tokenStream.LT(1).startCol;
-
- while(i < len && arg === null){
-
- arg = args[i].call(this);
- i++;
- }
- if (arg === null){
- this._unexpectedToken(tokenStream.LT(1));
- }
- if (arg.type == "elementName"){
- part = new SelectorPart(arg, [], arg.toString(), line, col);
- } else {
- part = new SelectorPart(null, [arg], arg.toString(), line, col);
- }
-
- return part;
- },
-
- _declaration: function(){
-
- var tokenStream = this._tokenStream,
- property = null,
- expr = null,
- prio = null,
- error = null,
- invalid = null,
- propertyName= "";
-
- property = this._property();
- if (property !== null){
-
- tokenStream.mustMatch(Tokens.COLON);
- this._readWhitespace();
-
- expr = this._expr();
- if (!expr || expr.length === 0){
- this._unexpectedToken(tokenStream.LT(1));
- }
-
- prio = this._prio();
- propertyName = property.toString();
- if (this.options.starHack && property.hack == "*" ||
- this.options.underscoreHack && property.hack == "_") {
-
- propertyName = property.text;
- }
-
- try {
- this._validateProperty(propertyName, expr);
- } catch (ex) {
- invalid = ex;
- }
-
- this.fire({
- type: "property",
- property: property,
- value: expr,
- important: prio,
- line: property.line,
- col: property.col,
- invalid: invalid
- });
-
- return true;
- } else {
- return false;
- }
- },
-
- _prio: function(){
-
- var tokenStream = this._tokenStream,
- result = tokenStream.match(Tokens.IMPORTANT_SYM);
-
- this._readWhitespace();
- return result;
- },
-
- _expr: function(inFunction){
-
- var tokenStream = this._tokenStream,
- values = [],
- value = null,
- operator = null;
-
- value = this._term(inFunction);
- if (value !== null){
-
- values.push(value);
-
- do {
- operator = this._operator(inFunction);
- if (operator){
- values.push(operator);
- } /*else {
- values.push(new PropertyValue(valueParts, valueParts[0].line, valueParts[0].col));
- valueParts = [];
- }*/
-
- value = this._term(inFunction);
-
- if (value === null){
- break;
- } else {
- values.push(value);
- }
- } while(true);
- }
-
- return values.length > 0 ? new PropertyValue(values, values[0].line, values[0].col) : null;
- },
-
- _term: function(inFunction){
-
- var tokenStream = this._tokenStream,
- unary = null,
- value = null,
- endChar = null,
- token,
- line,
- col;
- unary = this._unary_operator();
- if (unary !== null){
- line = tokenStream.token().startLine;
- col = tokenStream.token().startCol;
- }
- if (tokenStream.peek() == Tokens.IE_FUNCTION && this.options.ieFilters){
-
- value = this._ie_function();
- if (unary === null){
- line = tokenStream.token().startLine;
- col = tokenStream.token().startCol;
- }
- } else if (inFunction && tokenStream.match([Tokens.LPAREN, Tokens.LBRACE, Tokens.LBRACKET])){
-
- token = tokenStream.token();
- endChar = token.endChar;
- value = token.value + this._expr(inFunction).text;
- if (unary === null){
- line = tokenStream.token().startLine;
- col = tokenStream.token().startCol;
- }
- tokenStream.mustMatch(Tokens.type(endChar));
- value += endChar;
- this._readWhitespace();
- } else if (tokenStream.match([Tokens.NUMBER, Tokens.PERCENTAGE, Tokens.LENGTH,
- Tokens.ANGLE, Tokens.TIME,
- Tokens.FREQ, Tokens.STRING, Tokens.IDENT, Tokens.URI, Tokens.UNICODE_RANGE])){
-
- value = tokenStream.token().value;
- if (unary === null){
- line = tokenStream.token().startLine;
- col = tokenStream.token().startCol;
- }
- this._readWhitespace();
- } else {
- token = this._hexcolor();
- if (token === null){
- if (unary === null){
- line = tokenStream.LT(1).startLine;
- col = tokenStream.LT(1).startCol;
- }
- if (value === null){
- if (tokenStream.LA(3) == Tokens.EQUALS && this.options.ieFilters){
- value = this._ie_function();
- } else {
- value = this._function();
- }
- }
-
- } else {
- value = token.value;
- if (unary === null){
- line = token.startLine;
- col = token.startCol;
- }
- }
-
- }
-
- return value !== null ?
- new PropertyValuePart(unary !== null ? unary + value : value, line, col) :
- null;
-
- },
-
- _function: function(){
-
- var tokenStream = this._tokenStream,
- functionText = null,
- expr = null,
- lt;
-
- if (tokenStream.match(Tokens.FUNCTION)){
- functionText = tokenStream.token().value;
- this._readWhitespace();
- expr = this._expr(true);
- functionText += expr;
- if (this.options.ieFilters && tokenStream.peek() == Tokens.EQUALS){
- do {
-
- if (this._readWhitespace()){
- functionText += tokenStream.token().value;
- }
- if (tokenStream.LA(0) == Tokens.COMMA){
- functionText += tokenStream.token().value;
- }
-
- tokenStream.match(Tokens.IDENT);
- functionText += tokenStream.token().value;
-
- tokenStream.match(Tokens.EQUALS);
- functionText += tokenStream.token().value;
- lt = tokenStream.peek();
- while(lt != Tokens.COMMA && lt != Tokens.S && lt != Tokens.RPAREN){
- tokenStream.get();
- functionText += tokenStream.token().value;
- lt = tokenStream.peek();
- }
- } while(tokenStream.match([Tokens.COMMA, Tokens.S]));
- }
-
- tokenStream.match(Tokens.RPAREN);
- functionText += ")";
- this._readWhitespace();
- }
-
- return functionText;
- },
-
- _ie_function: function(){
-
- var tokenStream = this._tokenStream,
- functionText = null,
- expr = null,
- lt;
- if (tokenStream.match([Tokens.IE_FUNCTION, Tokens.FUNCTION])){
- functionText = tokenStream.token().value;
-
- do {
-
- if (this._readWhitespace()){
- functionText += tokenStream.token().value;
- }
- if (tokenStream.LA(0) == Tokens.COMMA){
- functionText += tokenStream.token().value;
- }
-
- tokenStream.match(Tokens.IDENT);
- functionText += tokenStream.token().value;
-
- tokenStream.match(Tokens.EQUALS);
- functionText += tokenStream.token().value;
- lt = tokenStream.peek();
- while(lt != Tokens.COMMA && lt != Tokens.S && lt != Tokens.RPAREN){
- tokenStream.get();
- functionText += tokenStream.token().value;
- lt = tokenStream.peek();
- }
- } while(tokenStream.match([Tokens.COMMA, Tokens.S]));
-
- tokenStream.match(Tokens.RPAREN);
- functionText += ")";
- this._readWhitespace();
- }
-
- return functionText;
- },
-
- _hexcolor: function(){
-
- var tokenStream = this._tokenStream,
- token = null,
- color;
-
- if(tokenStream.match(Tokens.HASH)){
-
- token = tokenStream.token();
- color = token.value;
- if (!/#[a-f0-9]{3,6}/i.test(color)){
- throw new SyntaxError("Expected a hex color but found '" + color + "' at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
- }
- this._readWhitespace();
- }
-
- return token;
- },
-
- _keyframes: function(){
- var tokenStream = this._tokenStream,
- token,
- tt,
- name,
- prefix = "";
-
- tokenStream.mustMatch(Tokens.KEYFRAMES_SYM);
- token = tokenStream.token();
- if (/^@\-([^\-]+)\-/.test(token.value)) {
- prefix = RegExp.$1;
- }
-
- this._readWhitespace();
- name = this._keyframe_name();
-
- this._readWhitespace();
- tokenStream.mustMatch(Tokens.LBRACE);
-
- this.fire({
- type: "startkeyframes",
- name: name,
- prefix: prefix,
- line: token.startLine,
- col: token.startCol
- });
-
- this._readWhitespace();
- tt = tokenStream.peek();
- while(tt == Tokens.IDENT || tt == Tokens.PERCENTAGE) {
- this._keyframe_rule();
- this._readWhitespace();
- tt = tokenStream.peek();
- }
-
- this.fire({
- type: "endkeyframes",
- name: name,
- prefix: prefix,
- line: token.startLine,
- col: token.startCol
- });
-
- this._readWhitespace();
- tokenStream.mustMatch(Tokens.RBRACE);
-
- },
-
- _keyframe_name: function(){
- var tokenStream = this._tokenStream,
- token;
-
- tokenStream.mustMatch([Tokens.IDENT, Tokens.STRING]);
- return SyntaxUnit.fromToken(tokenStream.token());
- },
-
- _keyframe_rule: function(){
- var tokenStream = this._tokenStream,
- token,
- keyList = this._key_list();
-
- this.fire({
- type: "startkeyframerule",
- keys: keyList,
- line: keyList[0].line,
- col: keyList[0].col
- });
-
- this._readDeclarations(true);
-
- this.fire({
- type: "endkeyframerule",
- keys: keyList,
- line: keyList[0].line,
- col: keyList[0].col
- });
-
- },
-
- _key_list: function(){
- var tokenStream = this._tokenStream,
- token,
- key,
- keyList = [];
- keyList.push(this._key());
-
- this._readWhitespace();
-
- while(tokenStream.match(Tokens.COMMA)){
- this._readWhitespace();
- keyList.push(this._key());
- this._readWhitespace();
- }
-
- return keyList;
- },
-
- _key: function(){
-
- var tokenStream = this._tokenStream,
- token;
-
- if (tokenStream.match(Tokens.PERCENTAGE)){
- return SyntaxUnit.fromToken(tokenStream.token());
- } else if (tokenStream.match(Tokens.IDENT)){
- token = tokenStream.token();
-
- if (/from|to/i.test(token.value)){
- return SyntaxUnit.fromToken(token);
- }
-
- tokenStream.unget();
- }
- this._unexpectedToken(tokenStream.LT(1));
- },
- _skipCruft: function(){
- while(this._tokenStream.match([Tokens.S, Tokens.CDO, Tokens.CDC])){
- }
- },
- _readDeclarations: function(checkStart, readMargins){
- var tokenStream = this._tokenStream,
- tt;
-
-
- this._readWhitespace();
-
- if (checkStart){
- tokenStream.mustMatch(Tokens.LBRACE);
- }
-
- this._readWhitespace();
-
- try {
-
- while(true){
-
- if (tokenStream.match(Tokens.SEMICOLON) || (readMargins && this._margin())){
- } else if (this._declaration()){
- if (!tokenStream.match(Tokens.SEMICOLON)){
- break;
- }
- } else {
- break;
- }
- this._readWhitespace();
- }
-
- tokenStream.mustMatch(Tokens.RBRACE);
- this._readWhitespace();
-
- } catch (ex) {
- if (ex instanceof SyntaxError && !this.options.strict){
- this.fire({
- type: "error",
- error: ex,
- message: ex.message,
- line: ex.line,
- col: ex.col
- });
- tt = tokenStream.advance([Tokens.SEMICOLON, Tokens.RBRACE]);
- if (tt == Tokens.SEMICOLON){
- this._readDeclarations(false, readMargins);
- } else if (tt != Tokens.RBRACE){
- throw ex;
- }
-
- } else {
- throw ex;
- }
- }
-
- },
- _readWhitespace: function(){
-
- var tokenStream = this._tokenStream,
- ws = "";
-
- while(tokenStream.match(Tokens.S)){
- ws += tokenStream.token().value;
- }
-
- return ws;
- },
- _unexpectedToken: function(token){
- throw new SyntaxError("Unexpected token '" + token.value + "' at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
- },
- _verifyEnd: function(){
- if (this._tokenStream.LA(1) != Tokens.EOF){
- this._unexpectedToken(this._tokenStream.LT(1));
- }
- },
- _validateProperty: function(property, value){
- Validation.validate(property, value);
- },
-
- parse: function(input){
- this._tokenStream = new TokenStream(input, Tokens);
- this._stylesheet();
- },
-
- parseStyleSheet: function(input){
- return this.parse(input);
- },
-
- parseMediaQuery: function(input){
- this._tokenStream = new TokenStream(input, Tokens);
- var result = this._media_query();
- this._verifyEnd();
- return result;
- },
- parsePropertyValue: function(input){
-
- this._tokenStream = new TokenStream(input, Tokens);
- this._readWhitespace();
-
- var result = this._expr();
- this._readWhitespace();
- this._verifyEnd();
- return result;
- },
- parseRule: function(input){
- this._tokenStream = new TokenStream(input, Tokens);
- this._readWhitespace();
-
- var result = this._ruleset();
- this._readWhitespace();
- this._verifyEnd();
- return result;
- },
- parseSelector: function(input){
-
- this._tokenStream = new TokenStream(input, Tokens);
- this._readWhitespace();
-
- var result = this._selector();
- this._readWhitespace();
- this._verifyEnd();
- return result;
- },
- parseStyleAttribute: function(input){
- input += "}"; // for error recovery in _readDeclarations()
- this._tokenStream = new TokenStream(input, Tokens);
- this._readDeclarations();
- }
- };
- for (prop in additions){
- if (additions.hasOwnProperty(prop)){
- proto[prop] = additions[prop];
- }
- }
-
- return proto;
-}();
-var Properties = {
- "align-items" : "flex-start | flex-end | center | baseline | stretch",
- "align-content" : "flex-start | flex-end | center | space-between | space-around | stretch",
- "align-self" : "auto | flex-start | flex-end | center | baseline | stretch",
- "-webkit-align-items" : "flex-start | flex-end | center | baseline | stretch",
- "-webkit-align-content" : "flex-start | flex-end | center | space-between | space-around | stretch",
- "-webkit-align-self" : "auto | flex-start | flex-end | center | baseline | stretch",
- "alignment-adjust" : "auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | | ",
- "alignment-baseline" : "baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
- "animation" : 1,
- "animation-delay" : { multi: "